<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JiGuang\JSMS as JSMS;
use Redis;

/**
 * @description: 系统级接口
 * @author fengyichao
 * @date 2017年11月13日 上午11:06:13
 */
class SystemController extends ApiController {
	
	/**
	 * @api {post} /system/sendSms 发送验证码
	 * @apiName send-sms
	 * @apiGroup System
	 * @apiParam {String} mobile 手机号
	 */
	function sendSms(Request $request) {
		$phone = $request->mobile;
		//@todo 手机号限制发送时间间隔
		$phone = '15010361063';
		$temp_id = 1;
		$client = new JSMS ( env('JIGUANG_APP_KEY'), env('JIGUANG_APP_SECRET'), [ 
				'disable_ssl' => true 
		] );
		$res = $client->sendCode ( $phone, $temp_id );
		dd($res);
		if ($res ['http_code'] == '200' && isset ( $res ['body'] ['msg_id'] )) {
			//存redis mobile => msg_id
			$key = 'code:sms:' . $phone;
			Redis::setex ( $key, 600, $res ['body'] ['msg_id'] );
			return $this->success ();
		} else {
			return $this->error ( '404', '发送失败' );
		}
	}
	
	/**
	 * @api {post} /system/checkSms 验证码验证
	 * @apiName checkSms
	 * @apiGroup System
	 * @apiParam {String} mobile 手机号
	 * @apiParam {string} code 验证码
	 */
	function checkCode(Request $request) {
		// 		测试条件放开
		//	return $this->success ();
		$client = new JSMS ( self::$app_key, self::$master_secret, [ 
				'disable_ssl' => true 
		] );
		$phone = $request->mobile;
		//@todo 查找用户库是否有该手机号
		//$phone = '15010361063';
		$key = 'code:sms:' . $phone;
		$msg_id = Redis::get ( $key );
		if (! $msg_id) {
			return $this->success ();
		} else {
			$res = $client->checkCode ( $msg_id, $request->code );
			if ($res ['http_code'] == 200 && $res ['body'] ['is_valid'] === true) {
				return $this->success ();
			} else {
				return $this->error ( 4001, '验证失败' );
			}
		}
	}
	/**
	 * @api {post} /system/init 初始化接口(仅供IOS使用)
	 * @apiName init
	 * @apiGroup System
	 * @apiParam {String} type 1:家长 2:教师
	 * @apiSuccess {String} is_open_register 是否开放注册
	 */
	function init(Request $request) {
		$data ['is_open_register'] = 1;
		return $this->success ( $data );
	}
	
	/**
	 * @api {post} /system/my-init 我的列表显示项(仅供IOS使用)
	 * @apiName my-init
	 * @apiGroup System
	 */
	function myInit(Request $request) {
		$titleArray = [ 
				[ 
						'点击登陆' 
				],
				[ 
						'孩子列表',
						'孩子入托' 
				],
				[ 
						'会员中心',
						'优惠卷',
						
						'消费记录',
						'我的机构' 
				],
				[ 
						'我的收藏',
						'设置' 
				] 
		];
		$imageArray = [ 
				[ 
						'头像未登录',
						'男头像',
						'女头像' 
				],
				[ 
						'004孩子列表',
						'004孩子入托' 
				],
				[ 
						'004会员中心',
						'004优惠券',
						
						'004消费记录',
						'004我的机构' 
				],
				[ 
						'004收藏',
						'004设置' 
				] 
		];
		$data = [ 
				$titleArray,
				$imageArray 
		];
		return $this->success ( $data );
	}
}
