<?php

namespace app\app\controller;

use think\Controller;
use think\Db;
use think\Cache;
use think\Log;
use \think\Validate;
use PHPMailer\PHPMailer\PHPMailer;

class Login extends Base{
    protected $code_time = 3600;
    ################################################################接口################################################################
    ################################################################接口################################################################
    ################################################################接口################################################################

    // 注册
    public function register_action($data = ['data'=>18530934717,'password'=>'ceshi','code'=>'746119']){
        
        // dump('123');
        // phpinfo();  
        // die;
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        $verify_result = $this->verify_parameters($data,'register');
        if(!is_array($verify_result)){
            return $this->msg(10001,$verify_result);
        }
        // dump($verify_result);
        // die;
        // 记录
        $result = Db::table('app_account_number')->insertGetId($verify_result);
        if($result){
            cache($verify_result['token'], time());
            return $this->msg(['token'=>$verify_result['token'],'aan_id'=>$result]);
        }else{
            return $this->msg(10002);
        }
    }
    // 重置密码
    public function reset_password($data = ['data'=>'18530934717','password'=>'ceshi1','c_password'=>'ceshi1','code'=>'491661']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('data', $data) || !array_key_exists('password', $data) || !array_key_exists('c_password', $data) || !array_key_exists('code', $data)){
            return $this->msg(10001);
        }
        
        if($data['password'] != $data['c_password']){
            return $this->msg(10003,'两次密码不一致');
        }
        $code_result = $this->check_code($data['data'],$data['code']);
        if($code_result !== true){
            return $this->msg(10003,$code_result);
        }
        $t_y = $this->is_tel_email($data['data']);
        if($t_y === false){
            return $this->msg(10003,'账号格式错误');
        }
        $find_data = Db::table('app_account_number')->where([$t_y=>$data['data']])->field('id,token')->find();
        if(!$find_data){
            return $this->msg(10003);
        }
        $result = Db::table('app_account_number')->where([$t_y=>$data['data']])->update(['password'=>$data['password']]);
        if($result){
            cache($find_data['token'], time());
            return $this->msg(['token'=>$find_data['token'],'aan_id'=>$find_data['id']]);
        }else{
            return $this->msg(10002);
        }
    }

    // 登录
    public function login_action($data = ['data'=>'18530934717','validate_data'=>'746119','type'=>'login','validate_type'=>'code']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('data', $data) || !array_key_exists('validate_data', $data) || !array_key_exists('validate_type', $data)){
            return $this->msg(10001);
        }
        // 检测是否为手机
        if (preg_match('/^\d{11}$/', $data['data'])) {  
            $verify_result['tel'] = $data['data'];
            $road = 'tel';
        }else{
            $verify_result['email'] = $data['data'];
            $road = 'email';
        }
        // dump($verify_result);
        // die;
        // $find_token = Db::table('app_account_number')->where([$t_y=>$data['data']])->field('id,token')->find();
        // 检测校验途径
        if($data['validate_type'] == 'code'){
            $code_name = $data['data'];
            // dump(cache($code_name));
            // die;
            // if(cache($code_name) == $data['validate_data']){
            if($this->check_code($code_name,$data['validate_data']) === true){
                $result = Db::table('app_account_number')->where($verify_result)->field('id,token')->find();
                if($result){
                    cache($result['token'], time());
                    return $this->msg(['token'=>$result['token'],'aan_id'=>$result['id']]);
                }else{
                    return $this->msg(10003);
                }
            }else{
                return $this->msg(10003,'登录失败，验证码错误或失效');
            }
        }else if($data['validate_type'] == 'password'){
            $verify_result['password'] = $data['validate_data'];
            $result = Db::table('app_account_number')->where($verify_result)->field('id,token')->find();
            if($result){
                cache($result['token'], time());
                return $this->msg(['token'=>$result['token'],'aan_id'=>$result['id']]);
            }else{
                return $this->msg(10003,'登录失败，账号/密码错误');
            }
        }else{
            return $this->msg(10003,'校验参数错误');
        }
        
    }
    // 退出登录操作
    public function user_quit_account($data=['token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('token', $data)){ 
            return $this->msg(10001);
        }
        if($this->token_time_validate($data['token']) === false){
            return $this->msg(20001);
        }
        cache($data['token'], NULL);
        return $this->msg([]);
    }

    ################################################################接口################################################################
    ################################################################接口################################################################
    ################################################################接口################################################################



    // 发送验证码 手机/邮箱
    /* 接口说明（发邮件）
    * $data（手机或者邮箱信息） 字符串
    * $type（验证类型，是注册用，还是其他用途） 字符串  默认register（注册）（register、login、reset_password）
    * $road（是手机还是邮箱还是其他） 字符串 默认tel或email
    */
    public function send_phone_email_code($data = ['data'=>'18530934717','type'=>'login']){
        // $data = input('post.');
        if(count(input('post.')) > 0){
            $data = input('post.');
        }
        if(!array_key_exists('data', $data) || !array_key_exists('type', $data)){
            return $this->msg(10001);
        }
        $num = $this->rand_int();
        if (preg_match('/^\d{11}$/', $data['data'])) {  
            $result = $this->send_tel_code($data['data'],$num);
            $road = 'tel';
        }else{
            $result = $this->send_email_code($data['data'],['title'=>'体测APP验证码','from_user_name'=>'体测APP','content'=>$num]);
            $road = 'email';
        }
        if(is_array($result) && $result['code'] == 0){
            cache($data['data'], $num, $this->code_time);
            // dump($data['data']."_".$data['road']."_".$data['type']);
            return $this->msg(['code'=>$num]);
            // return true;
        }else{
            return $this->msg(10002);
            // return false;
        }
    }

    ################################内部调用################################
    /* 接口说明（发邮件）
    * $address（收件人的邮箱地址） 数组 格式： ['460834639@qq.com','460834639@qq.com'.......]
    * $content（邮件的主题数据信息） 数组 格式：['title'=>'123','from_user_name'=>'123','content'=>'123']
    * $annex（附件路径信息） 字符串
    */
    public function send_email_code($address,$content,$annex=''){
        // $ad = '460834639@qq.com';
        $ad1 = '295155911@qq.com';
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host = "smtp.126.com"; //SMTP服务器 163邮箱例子
        $mail->Port = 465;  //邮件发送端口
        $mail->SMTPAuth   = true;  //启用SMTP认证
        $mail->SMTPSecure = 'ssl';
        $mail->CharSet  = "UTF-8"; //字符集
        $mail->Encoding = "base64"; //编码方式
        $mail->Username = "tsf3920322@126.com";  //你的邮箱
        $mail->Password = "HLWXNRPUCTHJFIIX";  //你的密码（邮箱后台的授权密码）
        $mail->From = "tsf3920322@126.com";  //发件人地址（也就是你的邮箱）

        // $mail->Subject = "微盟测试邮件"; //邮件标题
        $mail->Subject = $content['title']; //邮件标题

        // $mail->FromName = "微盟体测中心";   //发件人姓名
        $mail->FromName = $content['from_user_name'];   //发件人姓名

        for ($i=0; $i < count($address); $i++) { 
            $mail->AddAddress($address[$i], "");    //添加收件人（地址，昵称）
        }
        if($annex != ''){
            // $url = ROOT_PATH. 'public' . DS . 'tsf' . DS .'demoooo.jpg';
            $mail->AddAttachment($annex,''); // 添加附件,并指定名称
        }
        
        $mail->IsHTML(true); //支持html格式内容
        
        $mail->Body = $content['content']; //邮件主体内容
        
        //发送
        if (!$mail->Send()) {
            return $this->msg(10003,$mail->ErrorInfo);
            // return $mail->ErrorInfo;
        } else {
            return $this->msg([]);
            // return 'success';
        }
    }

    public function send_tel_code($tel,$code){
        // 初始化cURL会话  
        $ch = curl_init();  
        $headers = [
            'Accept: application/json',
            'Content-Type: application/json',
        ];
        // 设置头部信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // 设置请求的URL  
        $url = "http://sms.ybhdmob.com/Message/Send?token=ybhdmob";  
        curl_setopt($ch, CURLOPT_URL, $url);  
        // 设置为POST请求  
        curl_setopt($ch, CURLOPT_POST, 1);  
        // 设置POST数据  
        $postData = array(  
            'phone' => $tel,
            'content' => '【xxxx】您好，欢迎使用xxx,,您的手机验证码是:'.$code.'，验证码一分钟内有效,若非本人操作，请忽略！'
        );  
        $postData = json_encode($postData);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);  
        // 设置返回结果不直接输出，而是返回到变量中  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        // 发送请求并获取响应  
        $response = curl_exec($ch);  
        // 检查是否有错误发生  
        if (curl_errno($ch)) {  
            $error_message = curl_error($ch);  
            return "请求错误: " . $error_message;  
        }  
        // 关闭cURL会话  
        curl_close($ch);  
        // 处理响应  
        if ($response) {
            return json_decode($response,true);
        } else {  
            echo "未收到响应";  
        }  
    }

    public function check_code($data = 18530934717 , $code = 123456){
        return true;
        // dump($data);
        // dump(cache($data));
        // die;
        if(cache($data) == false){
            return '验证码过期';
        }else{
            if($code != cache($data)){
                return '验证码错误';
            }
        }
        return true;
    }
    ################################################################other################################################################
    ################################################################other################################################################
    ################################################################other################################################################

    public function test(){
        dump($this->send_tel_code('18530934717',$this->rand_int()));
        // dump(['code']);
        
    }

    public function rand_int(){
        return mt_rand(100000,999999);
    }

    public function verify_parameters($data,$type){
        // 设置验证
        $rule = [
            'data'  => 'require',
            'password'   => 'require',
            'code' => 'require|number',
        ];
        $msg = [
            'password.require' => '密码必须',
            'data.require'   => '手机或邮箱必须',
            'code.number'   => '验证码必须是数字',
            'code.number'   => '验证码必须',
        ];
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return $validate->getError();
        }
        // dump('3211');
        // 判断参数
        if(preg_match('/^\d{11}$/', $data['data'])){
            $parameter['tel'] = $data['data'];
            $montage_data = 'tel';
        }else{
            $parameter['email'] = $data['data'];
            $montage_data = 'email';
        }
        $parameter['password'] = $data['password'];

        // dump($montage_data);
        // dump( $parameter);
        // 检验是否注册过
        // if($montage_data == 'tel'){
        //     $inspect_repeat = Db::table('app_account_number')->where(['tel'=>$parameter['tel']])->count();
        //     // $inspect_repeat = Db::query("select count(*) from app_account_number where tel='".$parameter['tel']."'and password='".$parameter['password']);
        // }else{
        //     $inspect_repeat = Db::table('app_account_number')->where(['email'=>$parameter['email']])->count();
        // }
        $inspect_repeat = Db::table('app_account_number')->where([$montage_data=>$data['data']])->count();
        // dump( $inspect_repeat);
        // die;
        // dump($inspect_repeat);
        // dump('3212');
        if($inspect_repeat>0){
            return '注册失败，账号已存在';
        }
        

        if($type == 'register'){
            if(array_key_exists('code', $data)){
                $code_result = $this->check_code($parameter[$montage_data],$data['code']);
                if($code_result !== true){
                    return $code_result;
                }
            }else{
                return '验证码必须';
            }
            $parameter['create_time'] = date('Y-m-d H:i:s');
            $parameter['token'] = md5($data['data'].$this->create_random_string(12).time());
        }
        
        return $parameter;
    }

    public function create_random_string($length = 12)
    {
        //创建随机字符
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function demo_db(){
        dump('开始测试');
        $this->ceshiyong();
    }

}