<?php
namespace app\controller;

use app\model\Sms;
use think\facade\Request;
use app\model\User;
use PHPMailer\PHPMailer\PHPMailer;
use app\model\EmailCode;
use think\response\Json;

class Login extends CommonController
{

    /**
     * 登录类型
     */
    protected $loginType = ['pass_login' , 'code_login'];


	/**
	 * 用户注册
     */
	public function register():Json
	{
		$data = Request::only(
            [
                'company_name' ,
                'department',
                'username' ,
                'phone' ,
                'email' ,
                'password',
                'code',
                'user_tag'
            ]
        );

		if(! $this->checkPhone($data['phone'] ?? '')) {
            return $this->_json_error('手机号格式有误！');
        }

        if(! $data['password']) {
            return $this->_json_error('密码不能为空！');
        }

        if(isset($data['username']) && $data['username']) {
            $checkUsername = User::where(['username' => $data['username']])->find();
            if($checkUsername) {
                return $this->_json_error('用户名已注册！');
            }
        }

        if(isset($data['email']) && $data['email']) {
            $checkEmail = User::where(['email' => $data['email']])->find();
            if($checkEmail) {
                return $this->_json_error('邮箱已注册！');
            }
        }

		$user = User::where(['phone' => $data['phone']])->find();
		if($user) {
            return $this->_json_error('该手机号已注册！');
        }

        /**
         * 检测短信验证码
         */
        $checkSms = Sms::checkSmsCode($data['phone'] , $data['code']);
        if('code-error' === $checkSms) {
            return $this->_json_error('验证码错误！');
        }

        if('code-timeout' === $checkSms) {
            return $this->_json_error('验证码超时！');
        }

		$data['password'] = md5(sha1($data['password']));
		$data['status']   = User::NORMALSTATUS;
        //$data['privilege_menu'] ='["6"]';
        unset($data['code']);

		User::create($data);
		return $this->_json_succ();
	}


	/**
	 * 用户登录
     */
	public function index():Json
	{
        $type = Request::param('type') ?? 'pass_login';
        if(! in_array($type , $this->loginType)) {
            return $this->_json_error('登录错误！');
        }

        $phone = Request::param('phone');
        if(!$this->checkPhone($phone)) {
            return $this->_json_error('手机号格式有误！');
        }


        /**
         * 密码登录
         */
        if('pass_login' === $type) {
            $password = md5(sha1(Request::param('password')));
            $where = ['phone' => $phone, 'password' => $password];
            $user  = User::where($where)->find();
            if(!$user) {
                return $this->_json_error('用户名或密码有误！');
            }
        }


        /**
         * 验证码登录
         */
        if('code_login' === $type) {
            $code = Request::param('code');
            $checkResult = Sms::checkSmsCode($phone , $code , 2);
            if('code-error' === $checkResult) {
                return $this->_json_error('验证码有误！');
            } elseif('code-timeout' === $checkResult) {
                return $this->_json_error('验证码已失效！');
            }
            $user  = User::where(['phone' => $phone])->find();
        }

        /**
         * 账号状态检测
         */
		if(User::NORMALSTATUS != $user['status']) {
            return $this->_json_error('该账号暂时无法登录！');
        }

		return $this->_json_succ(
            [
                'uid'   => $user['uid'] ,
                'phone' => $user['phone'] ,
                'token' => signToken($user['phone'])
            ]
        );
	}



    /**
     * 邮箱发送邮件
     */
    public function sendEmail()
    {
        $toEmail = Request::param('email');
        $user = User::where('email' , $toEmail)->find();
        if(!$user) {
            return $this->_json_error('邮箱不存在！');
        }

        $code    = random_int(1000 , 9999);
        $mail    = new PHPMailer();
        $mail->isSMTP();                                    // 使用smtp鉴权方式发送邮件
        $mail->CharSet    = 'utf8';                         // 设置编码
        $mail->Host       = 'smtp.163.com';
        $mail->SMTPAuth   = true;                           // 是否需要认证身份
        $mail->Username   = "Nkchenzhongwei@163.com";       // 发送方邮箱
        $mail->Password   = "XXUBASDZOLRYRVWL";             // 发送方smtp密码
        $mail->SMTPSecure = 'ssl';                          // 使用的协议
        $mail->Port       = 465;                                                     // qq邮箱接收的端口号
        $mail->setFrom('Nkchenzhongwei@163.com', '验证码发送');           // 定义邮件及标题（不同邮件标题显示不一致）
        $mail->addAddress($toEmail, '您好！');                                   // 发送的地址和设置地址的昵称
        $mail->addReplyTo('Nkchenzhongwei@163.com', 'Replay');           // 回复地址
        $mail->Subject  = "您有新的验证码!";                                              // 添加该邮件的主题
        $mail->Body     = "您的验证码是" . $code . "，验证码的有效期为600秒，本邮件请勿回复！";  // 该邮件内容
        if(!$mail->send()) {
            return $this->_json_error($mail->ErrorInfo);
        } else {
            $emailCode = EmailCode::where('email' , $toEmail)->find();
            if($emailCode) {
                $emailCode->where('email', $toEmail)->update(['code' => $code , 'email' => $toEmail]);
            } else {
                $emailCode = new EmailCode();
                $emailCode->email       = $toEmail;
                $emailCode->code        = $code;
                $emailCode->create_time = time();
                $emailCode->save();
            }
            return $this->_json_succ();
        }
    }


    /**
     * 验证邮箱验证码 以及更新密码
     */
    public function forgetPassword()
    {
        $params = Request::only(['email' , 'code' , 'password']);
        $where  = $params;
        unset($where['password']);
        $checkEmailCode = EmailCode::where($where)->find();
        if(!$checkEmailCode) {
            return $this->_json_error('验证码错误！');
        }

//        $createTime = strtotime($checkEmailCode->create_time);
//        if(time() - $createTime > 600) {
//            return $this->_json_error('验证码超时！');
//        }

        $result = User::where('email' , $params['email'])->update(['password' => md5(sha1($params['password']))] );
        if(!$result) {
            return $this->_json_error('重置失败！');
        }
        return $this->_json_succ();
    }


    /**
     * 发送短信
     *
     * $phone int  手机号
     * $type  int  类型  1.注册 2.登录
     * @return Json
     */
    public function smsSend():Json
    {
        $phone = Request::param('phone');
        if(!$this->checkPhone($phone)) {
            return $this->_json_error('手机号格式有误！');
        }

        $type   = Request::param('type') ?? 1;
        $code   = mt_rand(1000 , 9999);

        /**
         * 手机号有无注册
         */
        $user = User::where(['phone' => $phone])->find();
        if(!$user && 2 == $type) {
            return $this->_json_error('请选择注册后登录！');
        }

        /**
         * 是否刚获取过
         */
        $sms = Sms::where(['phone' => $phone , 'type' => $type])->find();
        if(time() - $sms['createtime'] <= 60) {
            return $this->_json_error('请求频繁，稍后再试！');
        }


        /**
         * 发送短信
         */
        $result = $this->curlSmsSend($phone , $code);
        $smsResponse = json_decode($result , true);
        if(0 != $smsResponse['error']) {
            return $this->_json_error('发送失败');
        }

        /**
         * 记录验证码
         */
        Sms::create(
            [
                'phone' => $phone ,
                'code'  => $code ,
                'type'  => $type ,
                'createtime' => time()
            ]
        );
        return $this->_json_succ();
    }


    /**
     * 个人信息
     */
    public function profile()
    {
        $uid = Request::param('uid') ?? '';
        return $this->_json_succ(
            User::find($uid) ?? []
        );
    }

}
