<?php

namespace app\app\controller;

use think\Controller;
use think\Db;
use think\Cache;
use app\bj\controller\Common;
use think\Log;
use \think\Validate;
use PHPMailer\PHPMailer\PHPMailer;

class Login extends Controller{
    

    ################################################################个人资料卡################################################################
    ################################################################个人资料卡################################################################
    ################################################################个人资料卡################################################################

    // 注册
    public function register_action(){
        $data = input();
        
        $verify_result = $this->verify_parameters($data,'register');
        
        if(!is_array($verify_result)){
            return $this->msg(10001,$verify_result);
        }
        // 记录
        $result = Db::table('app_account_number')->insert($verify_result);
        if($result){
            return $this->msg(0,'success');
        }else{
            return $this->msg(10003,'注册失败');
        }
    }

    // 登录
    public function login_action(){
        $data = input();
        $verify_result = $this->verify_parameters($data,'login');
        if(!is_array($verify_result)){
            return $this->msg(10001,$verify_result);
        }
        $result = Db::table('app_register')->where($verify_result)->field('id')->find();
        // dump($result);
        // die;
        if($result){
            $user_data = Db::table('app_user_data')->where(['aan_id'=>$result['id']])->field('id,nickname')->select();
            return $this->msg(0,'success');
        }else{
            return $this->msg(10001,'未找到账户');
        }
    }

    // 手机/邮箱验证
    /* 接口说明（发邮件）
    * $data（手机或者邮箱信息） 字符串
    * $type（验证类型，是注册用，还是其他用途） 字符串  默认register（注册）
    * $road（是手机还是邮箱还是其他） 字符串 默认tel或email
    */
    public function phone_email_code(){
        $data = input();
        if(!array_key_exists('data', $data) || !array_key_exists('type', $data) || !array_key_exists('road', $data)){
            return $this->msg(10001,'数据&场景&通道必须');
        }
        $num = $this->rand_int();
        if($data['road'] == 'tel'){
            $result = $this->send_tel_code($data['data'],$num);
        }else if($data['road'] == 'email'){
            $result = $this->send_email_code($data['data'],['title'=>'体测APP验证码','from_user_name'=>'体测APP','content'=>$num]);
        }
        
        if(is_array($result) && $result['code'] == 0){
            cache($data['data']."_".$data['road']."_".$data['type'], $num, 60);
            // dump($data['data']."_".$data['road']."_".$data['type']);
            return $this->msg(0,'success');
        }else{
            return $this->msg(10001,'error');
        }
    }



    /* 接口说明（发邮件）
    * $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(10001,$mail->ErrorInfo);
            // return $mail->ErrorInfo;
        } else {
            return $this->msg(0,'success');
            // 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 "未收到响应";  
        }  
    }


    ################################################################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 = [
            'tel'  => 'number|length:11',
            'password'   => 'require',
            'email' => 'email',
            'code' => 'number',
        ];
        $msg = [
            'password.require' => '密码必须',
            'tel.number'   => '手机必须是数字',
            'code.number'   => '验证码必须是数字',
            'tel.length'  => '手机必须是11位',
            'email'        => '邮箱格式错误',
        ];
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return $validate->getError();
        }

        // 判断参数
        if(array_key_exists('tel', $data)){
            $parameter['tel'] = $data['tel'];
            $parameter['password'] = $data['password'];
            $montage_data = 'tel';
        }else if(array_key_exists('email', $data)){
            $parameter['email'] = $data['email'];
            $parameter['password'] = $data['password'];
            $montage_data = 'email';
        }else{
            return '手机/邮箱必须';
        }

        // 检验是否注册过
        if($montage_data == 'tel'){
            $inspect_repeat = Db::table('app_account_number')->where(['tel'=>$parameter['tel'],'password'=>$parameter['password']])->count();
        }else{
            $inspect_repeat = Db::table('app_account_number')->where(['email'=>$parameter['email'],'password'=>$parameter['password']])->count();
        }

        if($inspect_repeat){
            return '注册失败，账号已存在';
        }
        

        if($type == 'register'){
            if(array_key_exists('code', $data)){
                // dump($parameter[$montage_data]."_".$montage_data."_register".'='.cache($parameter[$montage_data]."_".$montage_data."_register"));
                if(cache($parameter[$montage_data]."_".$montage_data."_register") == false){
                    return '验证码过期';
                }else{
                    if($data['code'] != cache($parameter[$montage_data]."_".$montage_data."_register")){
                        return '验证码错误';
                    }
                }
            }else{
                return '验证码必须';
            }
            $parameter['create_time'] = date('Y-m-d H:i:s');
            $parameter['token'] = md5($parameter['tel'].$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 msg($code,$msg='',$data=[]){
        return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
    }

}