<?php
namespace App\Controller;
use App\Logic\AuthLogic;
use App\Logic\UserLogic;
use App\Model\UserModel;
use Think\Controller;
use User\Api\MemberApi;
use Org\XiguSDK\Xigu;
use Org\UcenterSDK\Ucservice;
use Base\Service\UserService;

class UserController extends BaseController
{

    /**
     * APP登录
     * @param account
     * @param password
     * author: xmy 280564871@qq.com
     */
    public function user_login($account, $password)
    {
               /*是否开启Ucenter*/
        if( C('UC_OPEN')==1 ){
            $member = new MemberApi();
            $user = new UserLogic();

            $username = $account;
            $password = $password;

            //Ucenter登录
            list($uc_uid, $uc_username, $uc_password, $uc_email) = uc_user_login($username,$password);
            if($uc_uid > 0) {
                //1.登录成功,验证在本地是否有此账号
                $user_res = M('user','tab_')->where(['account'=>$uc_username])->find();
                if(!empty($user_res)){//本地存在账号,验证密码直接登录

                    $user_id = $user->userLogin($account, $password);
                    if ($user_id > 0) {
                        $user_info = D('User')->getUserInfo($account);
                        $result['account'] = $user_info['account'];
                        $result['nickname'] = $user_info['nickname'];
                        $result['head_img'] = $user_info['head_img'];//头像
                        $result['balance'] = $user_info['balance'];   //平台币
                        $result['sex'] = $user_info['sex'];
                        $result['is_uc'] = 0;
                    }
                    if ($user_id > 0) {
                        $result['token'] = $this->login($account, $result['is_uc']);
                        $url= UC_WEB_URL.'/app.php/user/user_login/account/'.$username.'/password/'.$password;
                        $json_res=file_get_contents($url);
                        $h5_res=explode('token":"', $json_res);
                        $h5_token=substr($h5_res[1],0,-3);
                        if(empty($h5_token)){
                            $url= UC_WEB_URL.'/app.php/user/user_register/account/'.$username.'/password/'.$password;
                            $json_reg=file_get_contents($url);
                            $h5_reg=explode('token":"', $json_reg);
                            $h5_token=substr($h5_reg[1],0,-3);
                        }
                        $result['h5_token']=$h5_token;
                        $this->set_message(200, "登录成功", $result);
                    } else {
                        if($user_id==-1000){
                            $this->set_message(1004,"账号不存在");
                        }elseif($user_id==-10021){
                            $this->set_message(1005,"密码错误");
                        }elseif($user_id==-1100){
                            $this->set_message(1028,"密码错误");
                        }elseif($user_id==-1001) {
													$this->set_message(1004,"账号被禁用,请联系客服");
												}
                    }

                }else{//本地不存在账号,新增账号并登录

                    $resdata['account'] = $account;
                    $resdata['password'] = $password;
                    $resdata['sex'] = 1;
                    $resdata['nickname'] = '';

                    $res = D('User', 'Logic')->userRegisterByApp1($resdata);

                    if($res > 0 ){

                        $user_id = $user->userLogin($account, $password);
                        if ($user_id > 0) {
                            $user_info = D('User')->getUserInfo($account);
                            $result['account'] = $user_info['account'];
                            $result['nickname'] = $user_info['nickname'];
                            $result['head_img'] = $user_info['head_img'];//头像
                            $result['balance'] = $user_info['balance'];   //平台币
                            $result['sex'] = $user_info['sex'];
                            $result['is_uc'] = 0;
                        }
                        if ($user_id > 0) {
                            $result['token'] = $this->login($account, $result['is_uc']);

                            $url= UC_WEB_URL.'/app.php/user/user_login/account/'.$username.'/password/'.$password;
                            $json_res=file_get_contents($url);
                            $h5_res=explode('token":"', $json_res);
                            $h5_token=substr($h5_res[1],0,-3);
                            if(empty($h5_token)){
                                $url= UC_WEB_URL.'/app.php/user/user_register/account/'.$username.'/password/'.$password;
                                $json_reg=file_get_contents($url);
                                $h5_reg=explode('token":"', $json_reg);
                                $h5_token=substr($h5_reg[1],0,-3);
                            }
                            $result['h5_token']=$h5_token;

                            $this->set_message(200, "登录成功", $result);
                        }
                    }else{
                         $this->set_message(1004,"账号已存在");
                    }

                }

            } elseif($uc_uid == -1) {
                //用户不存在,验证本地用户账号密码
                $res = $user->userLogin($account, $password);
                if ($res > 0) {
                    $user_info = D('User')->getUserInfo($account);
                    $result['account'] = $user_info['account'];
                    $result['nickname'] = $user_info['nickname'];
                    $result['head_img'] = $user_info['head_img'];//头像
                    $result['balance'] = $user_info['balance'];   //平台币
                    $result['sex'] = $user_info['sex'];
                    $result['is_uc'] = 0;

                    //同步ucenter注册
                    cus_uc_register($username,$password,$username.'@vlcms.com');

                    $result['token'] = $this->login($account, $result['is_uc']);

                    $url= UC_WEB_URL.'/app.php/user/user_login/account/'.$username.'/password/'.$password;
                    $json_res=file_get_contents($url);
                    $h5_res=explode('token":"', $json_res);
                    $h5_token=substr($h5_res[1],0,-3);
                    if(empty($h5_token)){
                        $url= UC_WEB_URL.'/app.php/user/user_register/account/'.$username.'/password/'.$password;
                        $json_reg=file_get_contents($url);
                        $h5_reg=explode('token":"', $json_reg);
                        $h5_token=substr($h5_reg[1],0,-3);
                    }
                    $result['h5_token']=$h5_token;
                    $this->set_message(200, "登录成功", $result);
                } else {
                    switch ($res) {
                        case -1000:
                            $this->set_message(1004,"账号不存在");
                            break;
                        case -1001:
                            $this->set_message(1004,"账号被禁用,请联系客服");
                            break;
                        case -10021:
                            $this->set_message(1005,"密码错误");
                            break;
                        default:
                            $this->set_message(1004,"账号不存在");
                            break;
                    }
                }
            } elseif($uc_uid == -2) {
                //密码错误
               $this->set_message(1005,"密码错误");
            } else {
                //登录失败
            }
        }


        $user = new UserLogic();
        $user_id = $user->userLogin($account, $password);
        if ($user_id > 0) {
            $user_info = D('User')->getUserInfo($account);
            $result['account'] = $user_info['account'];
            $result['nickname'] = $user_info['nickname'];
            $result['head_img'] = $user_info['head_img'];//头像
            $result['balance'] = $user_info['balance'];   //平台币
            $result['sex'] = $user_info['sex'];
            $result['is_uc'] = 0;
        }
        if ($user_id > 0) {
            $result['token'] = $this->login($account, $result['is_uc']);
            $this->set_message(200, "登录成功", $result);
        } else {
            if($user_id==-1000){
                $this->set_message(1004,"账号不存在");
            }elseif($user_id==-10021){
                $this->set_message(1005,"密码错误");
            }elseif($user_id==-1100){
                $this->set_message(1028,"密码错误");
            }elseif($user_id==-1001) {
								$this->set_message(1004,"账号被禁用,请联系客服");
						}
        }
    }

		/**
		 * APP第三方登录
		 * @author 鹿文学
		 */
		public function user_third_login($nickname="",$unionid,$head_img="",$third_login_type,$access_token="",$promote_id=0){
	    /* $map['third_login_type'] = $third_login_type; */
	    $map['openid'] = get_union_id($access_token)?get_union_id($access_token):$unionid;
        if($third_login_type == 4){
            $uid = get_union_id($access_token);
            if($uid){
                $user_old = M('user','tab_')->where(array('openid'=>$unionid))->find();
                if($user_old){
                    M('user','tab_')->where(array('openid'=>$unionid))->save(array('openid'=>$uid));
                    $map['openid'] = $uid;
                }
            }
        }
	    $User = D('User');
	    $user = $User->where($map)->find();file_put_contents(dirname(__FILE__) . '/third_login.txt',json_encode($user));
	     if (empty($user)){
            switch ($third_login_type){
                case 2:
                $prefix = "wx_";
                $user['register_type'] = 3;
                break;
                case 4:
                $prefix = "qq_";
                 $user['register_type'] = 4;
                break;
            }

            do{

                $user['account'] = $prefix.'_'.sp_random_string();

                $account = M('user', 'tab_')->where(['account' => $user['account']])->find();

            } while (!empty($account));

            $user['password'] = sp_random_string(8);
            $user['nickname'] = $nickname;
            $user['head_img'] = !empty($head_img)?$head_img:'';
            $user['openid'] = $map['openid'];
            $user['third_login_type'] = $third_login_type;
            $user['promote_id'] = $promote_id;
            $user['promote_account'] = get_promote_account($promote_id);
            $user['register_way'] = 2;

            $user['id'] = D('User', 'Logic')->thirdRegisterByApp($user);
        } else {
	         if($user['lock_status'] == 0 || $user['check_status'] == 0){
                 $this->set_message(1004,"账号被禁用,请联系客服");
             }
             if(!empty($head_img)) {
	             M('user', 'tab_')->where(['id'=>$user['id']])->setField(['head_img'=>$head_img]);
	         }
        }
        $data['user_id'] = "1000".$user['id'];
        $data['account'] = $user['account'];
        $data['nickname'] = $user['nickname'];
        $data['head_img'] = !empty($head_img)?$head_img:(!empty($user['head_img'])?$user['head_img']:'');
        $data['balance'] = !empty($user['balance'])?$user['balance']:0;
        $data['sex'] = !empty($user['sex'])?$user['sex']:0;
        $data['is_uc'] = 0;
        $data['token'] = $this->login($user['account'],$data['is_uc']);

        $this->auth($data['token']);

        $this->set_message(200,'',$data);
    }

    /**
     * 普通注册
     * @param  [type] $account  用户名
     * @param  [type] $password 密码
     * @return [type] $sex      性别 0 1
     */
    public function user_register($account,$password,$sex){
        $user['account'] = $account;
        $user['password'] = $password;
        $user['sex'] = $sex;
        $user['nickname'] = '';
        /**是否开启ucenter**/
        if(C('UC_OPEN')==1){
            //Ucenter注册
            $userService = new UserService();
            if ($userService->isAccountExist($account)) {
                $this->set_message(1017, '用户名已存在');
            }

            //3.ucenter注册账号
            $ucresult = uc_user_checkname($account);
            if($ucresult == -1) {
                $this->ajaxReturn(array('status'=>0,'msg'=>'用户名不合法'));exit;
            } elseif($ucresult == -2) {
                $this->ajaxReturn(array('status'=>0,'msg'=>'包含要允许注册的词语'));exit;
            } elseif($ucresult == -3) {
                $this->ajaxReturn(array('status'=>0,'msg'=>'用户名已经存在'));exit;
            }else{
                //同步ucenter注册
                cus_uc_register($account,$password,$account.'@vlcms.com');
            }
        }

        $result = 1;
        if ($result > 0) {
            $result = D('User', 'Logic')->userRegisterByApp1($user);
        }
        if ($result < 0) {
                $this->set_message(1017, $result);
        }
        unset($user['password']);
        $user['token'] = $this->login($account, 0);
        $this->set_message(200, 1, $user);
    }


    /**
     * 手机注册
     * @param $phone
     * @param $password
     * @param $v_code 验证码
     * @param $sex
     * @param $nickname 昵称
     * author: xmy 280564871@qq.com
     */
    public function user_phone_register($phone, $password, $v_code, $sex, $nickname="")
    {
        #验证短信验证码

        $result = R('Common/Sms/verify_sms_code',array($phone,$v_code,false));

        if($result['code']==200) {
            $user['account'] = $phone;
            $user['password'] = $password;
            $user['sex'] = $sex;
            $user['nickname'] = $nickname;
            /**是否开启ucenter**/
            if(C('UC_OPEN')==1){
                $userService = new UserService();
                if ($userService->isAccountExist($phone)) {
                    $this->set_message(1017, '用户名已存在');
                }

                //3.ucenter注册账号
                $ucresult = uc_user_checkname($phone);
                if($ucresult == -1) {
                    $this->ajaxReturn(array('status'=>0,'msg'=>'用户名不合法'));exit;
                } elseif($ucresult == -2) {
                    $this->ajaxReturn(array('status'=>0,'msg'=>'包含要允许注册的词语'));exit;
                } elseif($ucresult == -3) {
                    $this->ajaxReturn(array('status'=>0,'msg'=>'用户名已经存在'));exit;
                }else{
                    //同步ucenter注册
                    cus_uc_register($phone,$password,$phone.'@vlcms.com');
                }
            }
            $result = 1;
            if ($result > 0) {
                $result = D('User', 'Logic')->userRegisterByApp($user);
            }
            if ($result < 0) {
                $this->set_message(1017, "用户已存在");
            }
            unset($user['password']);
            $user['token'] = $this->login($phone, 0);
            $this->set_message(200, "注册成功", $user);
        } else {
            switch ($result['code']){
                case 1020:
                    $this->set_message(1020,"请先获取验证码");
                    break;
                case 1021:
                    $this->set_message(1021,"验证码超时");
                    break;
                case 1022:
                    $this->set_message(1022,"验证码错误");
            }
            $this->set_message(-1, $result['msg']);
        }
    }

    /**
     * @param $email
     * @param $password
     * 邮箱注册
     */
    public function user_email_register($email,$password){
        $user['account']=$email;
        $user['password']=$password;
        $result=1;
        if ($result > 0) {
            $result = D('User', 'Logic')->userRegisterByApp($user);
        }
        if ($result < 0) {
            $this->set_message(1017, "用户名被占用");
        }
        unset($user['password']);
        $user['token'] = $this->login($email, 0);
        $this->set_message(200, 1, $user);
    }

    /**
     * 用户登录
     * 把账号和是否为UC用户状态 转为json
     * 使用系统加密 后返回客户端
     * 每次请求需带着这个参数
     * @param $account  账号
     * @param $is_uc    是否为UC用户
     * @param int $day 过期时间
     * @return string
     * author: xmy 280564871@qq.com
     */
    private function login($account, $is_uc, $day = 7)
    {
        $end_time = 60 * 60 * 24 * $day;
        $info['account'] = $account;
        $info['is_uc'] = $is_uc;
        $result = $token = think_encrypt(json_encode($info), UC_AUTH_KEY, $end_time);
        $data = M('User','tab_')->where(['account'=>$account])->find();
        $loginData = array(
            'user_id'=>$data['id'],
            'user_account'=>$account,
            'user_nickname'=>$data['nickname'],
            'promote_id'=>$data['promote_id'],
            'login_time'=>time(),
            'login_ip'=>get_client_ip(),
        );
        M('user_login_record', 'tab_')->add($loginData);
        return $result;
    }

    /**
     * 发送验证码
     * @param $phone    手机号
     * @param int $type 1:验证账号 2:不验证
     * author: xmy 280564871@qq.com
     */
    public function send_msg($phone, $type = 1)
    {
        if (empty($phone)) {
            $this->set_message(1029, "手机号不能为空");
        }
        $user = new UserLogic();
        if ($type == 2 || $user->checkUserExist($phone)) {

            $result = R('Common/Sms/send_sms_code',array($phone,10,false));

            if ($result['code']==200) {
                $this->set_message(200, "发送成功");
            } else {
                $this->set_message($result['code'], $result['msg']);
            }

        } else {
            $this->set_message(1017, "用户已存在");
        }
    }

    /**
     * @param $email
     * @param int $type
     * 发送邮箱验证码
     */
    public function send_email($email,$type=1){
        if(empty($email)){
            $this->set_message(1016,"邮箱不能为空");
        }
        $user=new UserLogic();
        if($type==2||$user->checkUserExist($email)){
            $result=$user::sendEmailMsg($email);
            if($result){
                $this->set_message(200,"发送成功");
            }else{
                $this->set_message(1018,"发送失败");
            }
        }else{
            $this->set_message(1017,"用户已存在");
        }
    }

    /**
     * @param $email
     * @param $v_code
     * 验证邮箱验证码
     */
    public function verify_email_code($email,$v_code){
        if(empty($email)){
            $this->set_message(1016,"邮箱不能为空");
        }elseif(empty($v_code)){
            $this->set_message(1019,"验证码不能为空");
        }
        $code_result = UserLogic::emailVerify($email, $v_code);
        if($code_result==UserLogic::RETURN_SUCCESS){
            $this->set_message(200,"验证成功");
        }else{
            if($code_result==2){
                $this->set_message(1020,"请先获取验证码");
            }elseif($code_result==-98){
                $this->set_message(1021,"验证码超时");
            }elseif ($code_result==-97){
                $this->set_message(1022,"验证码错误");
            }
        }
    }






    /**
     * 更新用户信息
     * @param $account
     * @param string $nickname
     * @param string $sex 0 男 1 女
     * author: xmy 280564871@qq.com
     */
    public function update_user($token, $nickname = "", $sex = "")
    {
        $this->auth($token);
        $result = D("User")->updateUserInfo(USER_ACCOUNT, $nickname, $sex);
        if ($result !== false) {
            $data = D("User")->getUserInfo(USER_ACCOUNT);
            $this->set_message(200, "更新成功", $data);
        } else {
            $this->set_message(1031, "更新失败");
        }
    }

    /**
     *添加绑定支付宝账号
     * lcj
     */

    public function update_alipay($token,$alipay,$alipay_real_name,$pwd){
        $this->auth($token);
        //验证登录密码
        $old_data = get_user_entity(USER_ACCOUNT,1);
        if(think_psw_md5($pwd, UC_AUTH_KEY) !== $old_data['password']){
            $this->set_message(1006, "登录密码输入不正确");
        }else{
            $savedata['alipay'] = $alipay;
            $savedata['alipay_real_name'] = $alipay_real_name;
            $result = M('user','tab_')->where(array('account'=>USER_ACCOUNT))->save($savedata);
            if ($result !== false) {
                $data = D("User")->getUserInfo(USER_ACCOUNT);
                $this->set_message(200, "绑定成功", $data);
            } else {
                $this->set_message(1031, "绑定失败");
            }
        }

    }

    /**
     * 获取用户消费记录
     * lcj
     */
    public function get_user_spend($token,$p=1){
        $this->auth($token);
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = 10;
        $user_data = D("User")->getUserInfo(USER_ACCOUNT);
        $map['user_id'] = $user_data['id'];
        $map['pay_status'] = 1;
        $map['pay_way'] = array('GT',0);
        $sdata = M('Spend','tab_')->field('1 as type,pay_amount,game_name,pay_time')->where($map)->select();
        $ddata =M('Deposit','tab_')->field('2 as type,pay_amount,pay_source as game_name,create_time as pay_time')->where($map)->select();
        $bdata = M('BindRecharge','tab_')->field('3 as type,real_amount as pay_amount, game_name,create_time as pay_time')->where($map)->select();
        $data = array_merge($sdata,$ddata,$bdata);
        foreach ($data as $key => $value) {
            $sort_data[$key] = $value['pay_time'];
        }
        array_multisort($sort_data,SORT_REGULAR,SORT_DESC,$data);
        $data = array_slice($data,($page-1)*$row,$row);
        $this->set_message(200,'成功',$data);


    }
    /**
     * 修改密码
     * @param $account
     * @param $old_pwd
     * @param $new_pwd
     * author: xmy 280564871@qq.com
     */
    public function change_pwd($token, $old_pwd, $new_pwd)
    {
        $this->auth($token);
        /*判断Ucenter是否打开*/
        if( C('UC_OPEN')==1 ){

            $username = USER_ACCOUNT;
            //修改uc密码
            $ucresult = uc_user_edit($username,$old_pwd,$new_pwd);
            if($ucresult == -1) {
                return $this->ajaxReturn(array('status'=>-2,'msg'=>'原密码错误'));
            }
        }
        $result = D('User')->changePwd(USER_ACCOUNT, $old_pwd, $new_pwd);
        if($result==2){
            $this->set_message(1006, "原密码不正确");
        }else if($result !== false){
            $u_uid['account']=USER_ACCOUNT;
            M('user_pwd')->where($u_uid)->setField('password',think_encrypt($new_pwd));
            $this->set_message(200, "更新成功");
        }else{
            $this->set_message(1031, "更新失败");

        }

    }

    /**
     * 忘记密码发送短信
     * @param $account
     * author: xmy 280564871@qq.com
     */
   public function forget_send_msg($account)
    {
        $data = D("User")->getUserInfo($account);
        if (empty($account)) {
            $this->set_message(1004, "账号不存在");
        } elseif (empty($data['phone'])) {
            $this->set_message(1039, "该用户未绑定手机号");
        }

        $result = R('Common/Sms/send_sms_code',array($data['phone'],10,false));

        if ($result['code']==200) {
            $this->set_message(200, "发送成功");
        } else {
            $this->set_message($result['code'], $result['msg']);
        }

    }

		/**
		 * 验证短信验证码
		 * @author 鹿文学
		 */
		public function forget_verify_msg($account, $v_code) {

			$data = D("User")->getUserInfo($account);
			if (empty($account)) {
					$this->set_message(1004, "账号不存在");
			} elseif (empty($data['phone'])) {
					$this->set_message(1039, "该用户未绑定手机号");
			}

			$result = R('Common/Sms/verify_sms_code',array($data['phone'],$v_code,false));

			if($result['code']==200) {

					$this->set_message(200,"验证码正确");

			} else {
					switch ($result['code']){
							case 1020:
									$this->set_message(1020,"请先获取验证码");
									break;
							case 1021:
									$this->set_message(1021,"验证码超时");
									break;
							case 1022:
									$this->set_message(1022,"验证码错误");
					}
			}


		}


    /**
     * 忘记密码
     * @param $phone    手机号
     * @param $v_code   验证码
     * @param $password 密码
     * @return bool
     * author: xmy 280564871@qq.com
     */
    public function forget_password($account, $password)
    {
				if(empty(trim($account))) {
					$this->set_message(1012, "修改失败");
				}
				if(empty(trim($password))) {
					$this->set_message(1012, "修改失败");
				}

        $data = D("User")->getUserInfo($account);

				$result = D('User')->forgetPwd($account, $password);
				if ($result !== false) {
						$u_uid['account']=$account;
						M('user_pwd')->where($u_uid)->setField('password',think_encrypt($password));
						$this->set_message(200, "修改成功");
				} else {
						$this->set_message(1012, "修改失败");
				}


    }

    /**
     * 获取用户信息
     * @param $token
     * author: xmy 280564871@qq.com
     */
    public function get_user_info($token)
    {
        $this->auth($token);
        $data = D("User")->getUserInfo(USER_ACCOUNT);
        $this->set_message(200, "成功", $data);
    }


    /**
     * 绑币记录
     * @param $token
     * @param int $p
     * author: xmy 280564871@qq.com
     */
    public function get_user_bind_coin($token, $p = 1)
    {
        $this->auth($token);
        $user_id = get_user_id(USER_ACCOUNT);
        $model = new UserModel();
        $data = $model->getUserBindCoin($user_id, $p);
        if (empty($data)) {
            $this->set_message(1033, "暂无数据");
        } else {
            $this->set_message(200, "成功", $data);
        }
    }


    /**
     * 实名认证信息   获得传递过来的UID,返回该玩家是否已经通过审核
     * @return mixed
     */
    public function return_age()
    {
        /*$request = json_decode(file_get_contents("php://input"),true);*/
        $request = $_GET;
        if (empty($request)) {
            $this->set_message(1001, "操作数据不能为空");
        }

        $this->auth($request['token']);

        $data = C('age_prevent');
        $data['on-off'] = $data['status'];
        unset($data['status']);
        $res['date'] = $data;
        $where['account'] = USER_ACCOUNT;
        $re = M('User', 'tab_')->field('age_status')->where($where)->find();
        if ($re) {
            $data['age_status'] = $re['age_status'];
            if ($data['age_status'] == 0 && !empty($data['idcard']) && !empty($data['real_name'])) {
                $data['age_status'] = 4;
            }
        } else {
            $data['age_status'] = -1;
        }
        //计算用户的游戏时间 和 休息时间
        $map['user_id'] = $request['user_id'];
        $map['login_time | down_time'] = period(0);
        $return = M('UserLoginRecord', 'tab_')->where($map)->order('id ASC')->select();
        $count = count($return);
        $play = 0;
        $down = 0;
        //游戏时间
        if ($count % 2 == 0) {
            for ($i = 0; $i < $count / 2; $i++) {
                $play += $return[$i * 2 + 1]['down_time'] - $return[$i * 2]['login_time'];
            }
        } else {
            for ($i = 0; $i < ceil($count / 2); $i++) {
                if (!empty($return[$i * 2 + 1]['down_time'])) {
                    $play += $return[$i * 2 + 1]['down_time'] - $return[$i * 2]['login_time'];
                } else {
                    $play += time() - $return[$i * 2]['login_time'];
                }
            }
        }
        if ($count <= 1) {
            $down = 0;
        } else if ($count == 2) {
            $down += time() - $return[1]['down_time'];
        } else {
            if ($count % 2 == 0) {
                for ($i = 0; $i < ($count / 2 - 1); $i++) {
                    $down += $return[$i * 2 + 2]['login_time'] - $return[$i * 2 + 1]['down_time'];
                }
                $down += time() - $return[$count - 1]['down_time'];
            } else {
                for ($i = 0; $i < (ceil($count / 2) - 1); $i++) {
                    $down += $return[$i * 2 + 2]['login_time'] - $return[$i * 2 + 1]['down_time'];
                }
            }
        }
        $data['play_time'] = floor($play / 60);
        $data['down_time'] = floor($down / 60);
        $this->set_message(200,"成功",$data);
    }

    /**
     * 更改身份证账户   获得传递过来的UID,idcard,name进行更改数据库
     * @return mixed
     */
    public function idcard_change($token,$idcard,$real_name)
    {
        if (empty($token) || empty($idcard) || empty($real_name)) {
            $this->set_message(1066, "用户数据异常" );
        }
        $this->auth($token);
        $map['account'] = USER_ACCOUNT;
        $data['idcard'] = $idcard;
        $data['real_name'] = $real_name;


        if(isset($data['idcard'])){
            $checkidcard = new \Think\Checkidcard();
            $invidcard=$checkidcard->checkIdentity($data['idcard']);
            if(!$invidcard){
                $this->set_message(1123, "身份证号码填写不正确!");
            }
            $cardd=M('User','tab_')->where(array('idcard'=>$data['idcard']))->find();
            if($cardd){
                $this->set_message(1087, "身份证号码已被使用!");
            }
        }

        //身份证认证
        if (C('tool_age.status') == 0){
            $data['age_status'] = 2;
        }else {
            $re = age_verify($data['idcard'], $data['real_name']);
            switch ($re) {
                case -1:
                    $this->set_message(1067, "短信数量已经使用完!");
                    break;
                case -2:
                    $this->set_message(1068,  "连接接口失败");
                    break;
                case 0:
                    $this->set_message(1069, "用户数据不匹配");
                    break;
                case 1://成年
                    $data['age_status'] = 2;
                    break;
                case 2://未成年
                    $data['age_status'] = 3;
                    break;
                default:
            }
        }
        $return = M('User', 'tab_')->where($map)->save($data);
        if (false!==$return) {
            $data['status'] = 1;
            $this->set_message(200,"实名认证成功",$data);
        }else{
            $this->set_message(1070, "fail", "用户数据更新失败");
        }

    }


    /**
     * 短信发送
     * @param  int user_id 用户ID
     * @param  string phone 手机号码
     * @param  string demand ???
     * @return base64加密的json格式
     * @author lyf
     */
     public function send_sms($phone,$type=1,$delay=10){
         //绑定手机时发送验证码   1
         //解绑手机时发送验证码   2

         if ($type == 1){
             $map['phone'] = $phone;
             $user = M('User','tab_')->where($map)->field('id,phone')->find();
             if (!empty($user)){
                 $this->set_message(1098,"该手机号已被绑定",0);
             }
         }elseif($type == 2){
             $map['phone'] = $phone;
             $user = M('User','tab_')->where($map)->field('id,phone')->find();
             if (empty($user)){
                 $this->set_message(1099,"该手机号不存在",0);
             }
         }

        /// 产生手机安全码并发送到手机且存到session
        $rand = rand(100000,999999);
        $param = $rand.",".$delay;
        if(get_tool_status("sms_set")){
            appchecksendcode($phone,C('sms_set.limit'),2);
            $xigu = new Xigu(C('sms_set.smtp'));
            $result = json_decode($xigu->sendSM(C('sms_set.smtp_account'),$phone,C('sms_set.smtp_port'),$param),true);
            if ($result['send_status'] != '000000') {
                $this->set_message(1010,"验证码发送失败,请重新获取",0);
            }
        }elseif(get_tool_status("alidayu")){
            appchecksendcode($phone,C('sms_set.limit'),2);
            $xigu = new Xigu('alidayu');
            $result = $xigu->alidayu_send($phone,$rand,$delay);
            $result['send_time'] = time();
            if($result == false){
                $this->set_message(1010,"验证码发送失败,请重新获取",0);
            }
        }elseif(get_tool_status('jiguang')){
            appchecksendcode($phone,C('sms_set.limit'),2);
            $xigu = new Xigu('jiguang');
            $result = $xigu->jiguang($phone,$rand,$delay);
            $result['send_time'] = time();
            if($result == false){
                $this->set_message(1010,"验证码发送失败,请重新获取",0);
            }
        }else{
            $this->set_message(1008,"没有配置短信发送",0);
        }

        // 存储短信发送记录信息
        $result['send_status'] = '000000';
        $result['phone'] = $phone;
        $result['create_time'] = time();
        $result['pid']=0;
        $result['create_ip']=get_client_ip();
        $r = M('Short_message')->add($result);

        session($phone,array('code'=>$rand,'create_time'=>NOW_TIME,'delay'=>$delay));

        $this->set_message(200,'success',$rand);
    }

        /**
     * 绑定手机号
     * @param $token
     * @param $phone
     * @param $vcode
     * author: xmy 280564871@qq.com
     */
    public function bind_phone($token,$phone,$vcode){
        $this->auth($token);
        $this->sms_verify($phone,$vcode);
        $model = new \App\Model\UserModel();
        $map['phone']=$phone;
        $find=M('user','tab_')->where($map)->find();
        if(null!==$find){
            $this->set_message(-1,"手机号已被绑定");
        }
        $res = $model->bindPhone(get_user_id(USER_ACCOUNT),$phone);
        $data = D("User")->getUserInfo(USER_ACCOUNT);
        $data['phone'] = $phone;
        if($res !== false){
            $this->set_message(200,"绑定成功",$data);
        }else{
            $this->set_message(1104,"绑定失败");
        }
    }

    /**
     * 解绑手机
     * @param $token
     * @param $phone
     * @param $vcode
     * author: xmy 280564871@qq.com
     */
    public function unbind_phone($token,$phone,$vcode){
        $this->auth($token);
        $this->sms_verify($phone,$vcode);
        $model = new \App\Model\UserModel();
        $res = $model->bindPhone(get_user_id(USER_ACCOUNT),"");
        $data = D("User")->getUserInfo(USER_ACCOUNT);
        $data['phone'] = '';
        if($res !== false){
            $this->set_message(200,"解绑成功",$data);
        }else{
            $this->set_message(1105,"解绑失败");
        }
    }
     public function sms_verify($phone,$v_code,$status=1){
        $telcode = session($phone);
        if(!$telcode){
            $this->set_message(1100,'验证码无效,请重新获取');
        }

        $time = (time() - $telcode['create_time'])/60;
        if ($time>$telcode['delay']) {
            session('telsvcode',null);unset($telcode);
            $this->set_message(1102,'时间超时,请重新获取验证码');
        }
        if ($telcode['code'] == $v_code) {
            if ($status==1){
                session('telsvcode',null);unset($telcode);
                return true;
            }else{
                $this->set_message(200,'success');
            }
        }else{
            $this->set_message(1103,'验证码不正确,请重新输入');
        }
    }

    /**
     * 验签
     * @param  [type] $token [description]
     * @return [type]        [description]
     */
    public function auth_token($token){
        $this->auth($token);
        $this->set_message(200,'success','');
    }
    /**
     * 开机动画
     */
    public function open_picture(){
        $url=get_cover(C('APP_SET_COVER'),'path');
        if(substr($url,0,1)=='h'){
            $data=$url;
        }else{
            $data="http://".$_SERVER['HTTP_HOST'].$url;
        }
        echo json_encode(array('status' => 1, 'data' => $data));
    }

    /**
     * 获取实名认证状态
     * @return [type] [description]
     */
    public function get_tool_age(){
        echo json_encode(array('status' => C('tool_age.status'), 'data' => (object)[]));

    }

    /**
     * [获取客服QQ的相关信息]
     * @author 幽灵[syt]
     */
    public function get_promote_site(){
        $info=M('site_base','tab_')->where(['promote_id'=>PROMOTE_ID])->find();
        if($info['site_qq']){
            $this->set_message(200,'成功',$info['site_qq']);
        }else{
            $this->set_message(200,'成功',C('APP_QQ'));
        }
    }

		/**
		 * 小号交易入口
		 * @author 鹿文学
		 */
		public function get_small_trade() {

			if(C('IS_OPEN_SMALL_ACCOUNT')==1) {

				$entrance = 1;

				$trade_url = U('Trade/index',array('mark'=>'app'),false);
				$trade_url = 'http://'.$_SERVER['HTTP_HOST'].''.str_replace('/app.php?','/mobile.php?',$trade_url);

			} else {

				$entrance = 0;

				$trade_url = '';

			}

			 echo json_encode(array('code' => 200, 'data' => ['small_switch'=>$entrance,'small_url'=>$trade_url]));

		}

		/**
		 * 第三方登录设置
		 * @author 鹿文学
		 */
		public function get_third_login_set() {

			$qq_switch = C('qq_login.status') == 1? 1 : 0;

			$wx_switch = C('weixin_login.status') == 1? 1 : 0;

			echo json_encode(array('code' => 200, 'data' => ['qq_switch'=>$qq_switch,'wx_switch'=>$wx_switch]));

		}




}