<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\Member;
use app\apicom\model\Money;
use app\apicom\model\Invite;
use app\apicom\model\JWT;
use think\facade\Db;
use util\RedisUtil;
use util\SmsCodeRedis;
use sms\SmsUtil;
use think\facade\Session;

class User extends BaseController
{
    /**
     * 初始化方法
     * @author 路人甲乙
     */
    protected function _initialize()
    {
        parent::__construct();
        // 系统开关
        if (!sysConfig('web_site_status')) {
            return ajaxmsg('站点已经关闭，请稍后访问',0);
        }
    }
    /*
    * 用户登录请求
    */
    public function login()
    {
        if (!sysConfig("web_site_status")) return ajaxmsg('站点已经关闭',0);
        // 用户参数
        $data['mobile']   = input('mobile', '');
        $data['password'] = input('password', '');
        $data['sms_code'] = input('sms_code', '');
        $data['smsstat']  = input('smsstat', false);
        // 验证数据
        $result = $data['smsstat'] ? $this->validate($data, 'Member.captcha') : $this->validate($data, 'Member.signin');
        if(!$result) return ajaxmsg($result,0);
        // 查询用户
        $user = Member::where('mobile', $data['mobile'])->find();
        // 是否被禁止登录
        if($user) {
            if($user['status'] !== 1) return ajaxmsg('禁止登陆',0);
            if($data['smsstat']==='1'){
                //验证短信
                if(sysConfig('web_reg_code') != 1) return ajaxmsg('系统已关闭短信功能',0);
                $check = SmsCodeRedis::isSmsCodeExist($data['mobile'], $data['sms_code']);
                if(!$check) return ajaxmsg('验证码不正确',0);
            }else{
                if(!password_verify($data['password'], $user['passwd'])) return ajaxmsg('密码错误',0);
            }
            $datas = self::doLogin($user);
            if(!$datas) return ajaxmsg('登录失败',0);
            return ajaxmsg('登录成功',1,$datas);
        }
        return ajaxmsg('手机号或密码错误',0);
    }
    public function doLogin($user)
    {
        $ret = Member::where('id',$user['id'])->update(['last_login_time'=>date('Y-m-d H:i:s'),'last_login_ip'=>getClientIp()]);
        if($ret){
            $token = array(
                "uid"    => $user['id'],
                "name"   => $user['name'],
                'doHost' => WS_SERVER_IP,
                'doTime' => time(),
                "mobile" => $user['mobile'],
            );
            $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
            RedisUtil::cacheToken($jwt, $token);
            $datas['token']  = $jwt;
            $datas['mobile'] = $user['mobile'];
            $datas['uid']    = $user['id'];
            return $datas;
        }
        return false;
    }
    /*
    * 退出登录
    */
    public function signout()
    {
        if ($this->token != '') {
            RedisUtil::deleteToken($this->token);
        }
        return ajaxmsg('退出登录成功',1);
    }
    /**
     * 注册获取短信 返回 短信信息token
     * 注册
     */
    public function register()
    {
        if(sysConfig('is_reg') == 0) return ajaxmsg('暂不开放注册',0);
        $tid              = input('code', '');
		// 用户参数
        $data['mobile']   = $mobile = input('mobile', '');
        $data['passwd']   = input('password', '');
        $data['sms_code'] = input('sms_code', '');

		if (empty($data['mobile'])) 
		    return ajaxmsg('请输入您的手机号！',0);
		$userExist = Member::where('mobile|name', '=', $data['mobile'])->column('mobile', 'id');
        if ($userExist) 
            return ajaxmsg('该手机号已经注册',0);
		if (!in_array(strlen($data['mobile']), [8, 9, 11])) 
		    return ajaxmsg('您输入的手机号码有误!',0);
		if(sysConfig('is_recommend') == 1 && $tid){
            //if(!$tid) return ajaxmsg('请正确填写邀请码',0);
            if(strlen($tid)==11) {
                $tid_data = Member::where('mobile', intval($tid))->find()->toArray();
                if(empty($tid_data)) return ajaxmsg('代理不存在',0);
            }elseif(strlen($tid)<11){
                $tid=substr($tid,2,-3);
                $tid_data = Member::where('id', intval($tid))->find()->toArray();
                if($tid_data['mobile']){
                    if($tid_data['mobile'] == $data['mobile']) return ajaxmsg('邀请人不能是自己',0);
                }
            }
            //print_r($tid_data);exit;
            $data['agent_far'] = $tid_data['id'] ?: 0;
        }
        
        // 验证数据
        $result = $this->validate($data, 'Member.create');
        if ($result !== true) return ajaxmsg($result,0);
        //验证短信
        if(sysConfig('web_reg_code') == 1){
            $check = SmsCodeRedis::isSmsCodeExist($data['mobile'], $data['sms_code']);
            if(!$check) return ajaxmsg('验证码不正确',0);
        }
        try{
            $res = Member::saveData($data);
            //插入邀请码
    		$redata['id']      = $res['data']['id'];
    		$redata['recomed'] = $res['data']['id'] + 100000;
    		Member::update($redata); 
    		if($tid){
                $data_r['id']  = $res['data']['id'];//被邀请人id
                $data_r['mid'] = $data['agent_far'];//邀请人id
                $Inv_res       = Invite::saveData($data_r);//保存推荐关系数据
            }
        }catch (\Exception $e) {
            DB::rollback();
            return ajaxmsg('注册失败',0);
        }
		if($res['status'] === 1){
		    // 检测是否满足注册赠送管理费活动
            if(sysConfig('give_open') == 1) Money::setGiveFee($res['data']['id'], 'give_reg', 0);
            
            $token = array(
                "uid"    => $res['data']['id'],
                'doHost' => WS_SERVER_IP,
                'doTime' => time(),
                "mobile" => $res['data']['mobile'],
            );
            $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
            RedisUtil::cacheToken($jwt, $token);
            $datas['token']  = $jwt;
            $datas['mobile'] = $res['data']['mobile'];
            $datas['uid']    = $res['data']['id'];
            return ajaxmsg($res['message'],1,$datas);
        }else{
            return ajaxmsg($res['message'],0);
        }
    }
    /**
     * 是否已登陆
     * -- 该方法不用做任何处理，BaseController 里面 initialize 方法会自动判断返回
     * -- 调用该方法前必须检测是否已登录，检测会自动进行
     */
    public function checkLogin()
    {
        $ret = Member::where(['id'=> $this->userId,'status'=>1])->find();
        if ($this->token != '' && !$ret) {
            RedisUtil::deleteToken($this->token);
        }
        return $ret ? ajaxmsg('已登录',1) : ajaxmsg('未登录',500);
    }
    /***
     ** 发送短信验证码
     ***/
    public function sendsms()
    {
        if (Session::has('sms_code')) {
            $resetFlag = Session::get('sms_code');
            if ((time() - $resetFlag['time']) < 60) {
                return ajaxmsg('操作太频繁，请一分钟之后再试',0);
            }
        }
        // 验证码类型
        $type   = input('type', '');
        $mobile = input('mobile');
        $type   = in_array($type, [SmsUtil::CAPTCHA_REGISTER, SmsUtil::CAPTCHA_RESET, SmsUtil::CAPTCHA_WITHDRAW,SmsUtil::CAPTCHA_LOGIN]) ? $type : '';
        if (SmsUtil::CAPTCHA_REGISTER == $type) {
            $user = Member::getMemberInfoByMobile($mobile);
            if(!empty($user)) return ajaxmsg('该手机已经注册会员,请更换手机!',0);
        }
        $result  = $this->validate(['mobile'=>$mobile], 'Member.captcha');
        if(!$result) return ajaxmsg($result,0);
        $res = SmsUtil::sendCaptcha($mobile, $type);
        if(!$res) return ajaxmsg('发送失败',0);
        //演示状态用
        return ajaxmsg($res,1);
        return ajaxmsg('发送成功',1);
    }
    /**
     * 密码找回验证码发送
     * @return array
     */
    public function sendPassSms()
    {
        $data   = input('post', '');
        $mobile = $data['mobile'];
        $tp     = 'code';
        //验证该手机号是否存在
        $isExists = Member::where('mobile',$mobile)->value('id');
        //如果找回密码所填写的手机号不存在
        if(is_null($isExists)){
            return ajaxmsg('该手机号不存在',0);
        }
        $res = sendsms_mandao($mobile,$content,$tp);
        if($res!==true){
            return ajaxmsg('发送失败',0);
        }else{
            return ajaxmsg('发送成功',1);
        }
    }
    /**
     * 设置新密码
     */
    public function newpass()
    {
        $data   = input('post', '');
        $mobile =$data['mobile'];
        if($mobile ==''){
            return ajaxmsg('请求参数错误', 0);
        }
        $pwd = $data['password'];
        if($pwd ==''){
            return ajaxmsg('请求参数错误', 0);
        }
        $where['mobile'] = $mobile;
        $result = Member::update(['passwd' => $pwd],$where);
        if($result!==false){
            return ajaxmsg('密码重置成功！',1);
        }else{
            return ajaxmsg('密码重置失败！请重试',0);
        }
    }
    /**
     * 忘记登录密码 重置--下一步
     */
    public function next()
    {
        $data       = input('post', '');
        $mobile     = $data['mobile'];
        $sms_code   = $data['sms_code'];
        $check_code = check_sms_code($mobile, $sms_code);
        //验证短信
        if(!$check_code) return ajaxmsg('短信验证码错误或失效',0);
        $_SESSION['sms_code'] = $sms_code;
        $_SESSION['mobile']   = $mobile;

        return ajaxmsg('通过进入下一步',1);
    }
    /*
     * 修改支付密码
     */
    public function paypass()
    {
        $data = input();
        if(!isset($data['oldpwd'])){
            return ajaxmsg('参数有误，请重试',0); 
        } 
        if($data['subpwd'] !== $data['newpwd']){
			return ajaxmsg('两次输入密码不一致',0);
        }
        if($data['oldpwd'] === $data['newpwd']){
			return ajaxmsg('不能与旧密码相同',0);
        }
        $user = Db::name('member')->where(["id"=>$this->userId])->find();
        if(!password_verify($data['oldpwd'], $user['paywd'])){
            return ajaxmsg('旧支付密码错误，请重试',0);
        }
        $newpwd = password_hash($data['newpwd'], PASSWORD_DEFAULT);
        $res = Db::name('member')->where(["id"=>$this->userId])->update(['paywd'=>$newpwd]);
        if(!$res) return ajaxmsg('设置失败，请重试',0);
        return ajaxmsg('设置成功',200);
    }
}