<?php
namespace Mobile\Controller;
use Org\Ipa365SDK\Ipa365;
use User\Api\MemberApi;
use Think\Log;
use Base\Service\ApplyService;

class CommonController extends BaseController {
    const USER_NOT_ILLEGAL = -1;        //用户名不合法
    const USER_HAVE_SENSITIVE_STR = -2; //包含敏感字符
    const USER_HAS_REGISTERED = -3;     //用户已存在
    const USER_PROMOTE_NATURAL = 0;     //自然注册
    const EMPTY_DATA = -100;            //数据为空
    const SIGN_ERROR = -99;             //验签失败
    const USER_NOT_EXIST = -1000;       //用户不存在
    const USER_FORBIDDEN = -1001;       //被禁用
    const USER_PWD_ERROR = -10021;      //密码错误
    const UNKNOWN_ERROR = -1100;        //未知错误
    const CODE_TIMEOUT = -98;           //验证码超时
    const CODE_ERROR = -97;             //验证码错误
    const RETURN_SUCCESS = 1;
    const RETURN_FALSE = 2;

    //用户登录
    public function login()
    {
        $account = I('account');
        $password =  I('password');
        $verifyCode = I('verify_code', '');
        $promoteId =  I('promote_id', 0);

        if (!$promoteId) {
            $this->respondError('参数非法');
        }
        
        $verify = new \Think\Verify();
        if (!$verify->check($verifyCode)) {
            $this->respondError('验证码错误');
        }
        $promote = M('promote', 'tab_')->where(['id' => $promoteId])->find();

        $userApi = new MemberApi();
        $userId = $userApi->login($account, $password, 1); //调用登录
        $resMsg = "登录成功";
        if ($userId <= 0) {
            switch ($userId) {
                case -1000 :
                    $resMsg = "用户不存在";
                    break;
                case -10021 :
                    $resMsg = "登录密码错误";
                    break;
                default :
                    $resMsg = "未知错误";
            }
            $this->respondError($resMsg);
        }

        $_SESSION['user_id'] = $userId;
        $user = M('user', 'tab_')->where(['id' => $userId])->find();
        if (!$user['promote_id'] && $promote) {
            M('user', 'tab_')->where(['id' => $userId])->save([
                'promote_id' => $promoteId,
                'promote_account' => $promote['account']
            ]);
        }
        $this->respondSuccess($resMsg);
    }

    //验证码
    public function verify($vid = '')
    {
        $config = array(
            'seKey' => 'ThinkPHP.CN',   //验证码加密密钥
            'fontSize' => 16,           // 验证码字体大小(px)
            'imageH' => 42,             // 验证码图片高度
            'imageW' => 107,            // 验证码图片宽度
            'length' => 4,              // 验证码位数
            'fontttf' => '4.ttf',       // 验证码字体,不设置随机获取
            'useCurve'  =>  false,      // 是否画混淆曲线
            'useNoise'  =>  false,      // 是否添加杂点	
            'useCurve' => false,
        );

        ob_clean();
        $verify = new \Think\Verify($config);
        $verify->codeSet = '0123456789';
        $verify->entry($vid);
    }

    //注册
    public function phoneRegister()
    {
        //添加用户
        C(api('Config/lists'));

        $params = $_POST;

        #判断数据是否为空
        if (empty($params)) {
            $this->respondError('注册数据不能为空');
        }
        
        $promoteId = $params['promote_id'] ?? 0;
        $gameId = $params['game_id'] ?? 0;

        #验证短信验证码
        $this->smsVerify($params['account'], $params['verify_code']);

        $res = $this->doRegister($params['account'], $params['password'], $params['account'], $promoteId, 4, 2, $gameId);
        if(empty($res)){
            $this->respondError('添加失败');
        }

        //添加自动登录
        $userApi = new MemberApi();
        $userId = $userApi->login($params['account'], $params['password'], 1);
        $_SESSION['user_id'] = $userId;
        $this->respondSuccess('添加成功');
    }

    //忘记密码
    public function forgetPassword()
    {
        $params = $_POST;
        if (empty($params)) {
            $this->respondError('基础信息不能为空');
        }
        $this->smsVerify($params['account'], $params['verify_code']);
        //更新密码
        $userApi = new MemberApi();
        $userInfo = M("user", "tab_")->where("account = '".$params['account']."'")->find();
        if(empty($userInfo)){
            $this->respondError('用户不存在');
        }
        //更新用户
        $upres = $userApi->updatePassword($userInfo['id'], $params['password']);
        if($upres){
            //自动登陆
            // $userId = $userApi->login($params['account'], $params['password'], 1);
            $this->respondSuccess('修改成功');

        }else{
            $this->respondError('密码更新错误,请刷新后再次尝试');
        }
    }

    //普通注册
    public function userRegister()
    {
        $account = I('account');
        $password = I('password');
        $promoteId = I('promote_id', 0);
        $res = $this->doRegister($account, $password, '', $promoteId, 4, 1);
        if(empty($res)){
            $this->respondError('注册失败');
        }

        //添加自动登录
        $userApi = new MemberApi();
        $userId = $userApi->login($account, $password, 1);
        $_SESSION['user_id'] = $userId;
        $this->respondSuccess('注册成功');
    }

    //真正注册代码
    public function doRegister($account, $password ,$phone, $promote_id, $register_way, $register_type, $game_id = 0)
    {
        //验证账号
        $user = M('user', 'tab_')->where(['account' => $account])->find();
        if (!empty($user)) {
            $this->respondError('用户名已存在');
        }
        //2.验证其他平台是否存在账号
        $domain = C('UC_OTHER_WEB_URL');
        if (!empty($domain)) {
            $url = "http://{$domain}/Api/user/checkUserName?account={$account}";
            $check_res = json_decode(file_get_contents($url), true);
            if ($check_res['status'] == 0) {
                $this->respondError('用户名已存在');
            }
        }

        $data = [
            'account' => $account,
            'password' => think_ucenter_md5($password, UC_AUTH_KEY),
            'phone' => $phone,
            'head_img' => '',
            'promote_id' => $promote_id,
            'promote_account' => get_promote_account($promote_id),
            'register_way' => $register_way,
            'register_type' => $register_type,
            'register_ip' => get_client_ip(),
            'parent_id' => get_fu_id($promote_id),
            'parent_name' => get_parent_name($promote_id),
            'register_time' => time(),
            'check_time' => time(),

        ];
        if ($game_id) {//关联游戏
            $game = M('game', 'tab_')->where(['id' => $game_id])->find();
            if ($game) {
                $data['fgame_id'] = $game_id;
                $data['fgame_name'] = $game['game_name'];
            }
        }

        /* 添加用户 */
        $res = M('user', 'tab_') ->add($data);
        return $res;
    }

    //发送验证码
    public function sendPhoneCode()
    {
        $phone = I("phone");
        $result = R('Common/Sms/send_sms_code', [$phone, 10, false]);

        if ($result['code'] == 200) {
            $this->setData($result['data'])->respondSuccess('发送成功');
        } else {
            $this->respondError('发送失败');
        }
    }

    public function smsVerify($phone="" , $code="", $type=2){

        $result = R('Common/Sms/verify_sms_code', [$phone, $code, false]);
        if($result['code'] == 200) {
            if($type==1){
                $this->respondSuccess('正确');
            }else{
                return true;
            }
        } else {
            switch ($result['code']) {
                case 1021:{
                    $this->respondError('验证码已失效,请重新获取');
                };break;
                case 1022:{
                    $this->respondError('验证码不正确,请重新输入');
                };break;
                default:
                    $this->respondError($result['msg']);
            }
        }
    }
}