<?php

namespace app\home\controller;

use app\common\model\UserModel;
use app\common\service\SmsService;
use app\home\HomeBaseController;
use think\facade\Validate;

class Login extends HomeBaseController
{

    public function index()
    {
        return view();
    }

    public function logout()
    {
        session('home.user.id',null);
        return redirect('/');
    }

    public function sendSms()
    {
        $mobile = trim(input('post.mobile'));

        $validate = Validate::rule('mobile', 'require|mobile');
        if (!$validate->check(['mobile'=>$mobile])) {
            ajax_return(1, '手机号错误');
        }

        //手机号验证
        $user = UserModel::where('mobile', $mobile)->find();
        empty($user) && ajax_return(1, '该手机号未注册');

        $rand       = rand(100000, 999999);
        $preg_phone = '/^1[34578]\d{9}$/ims';
        if (preg_match($preg_phone, $mobile)) {
            $sms = new SmsService();
            $res = $sms->send($mobile, 'verification', [$rand]);

            if ($res['code'] == 0) {
                session('home.login.verify', $rand);
                session('home.login.verify_expire', time());
            } else {
                ajax_return(1, '发送失败，请联系管理员');
            }
        } else {
            ajax_return(1, '手机号格式不正确');
        }

        ajax_return();
    }

    public function doLogin()
    {
        $data = input('post.');
        empty($data['mobile']) && ajax_return(1, '请输入手机号');

        //手机号验证
        $user = UserModel::where('mobile', $data['mobile'])->find();
        empty($user) && ajax_return(1, '该手机号未注册');

        if ($data['type'] == 'password') {
            //密码登录
            empty($data['password']) && ajax_return(1, '请输入密码');

            //密码验证
            if (md5(md5($user['salt']) . $data['password']) != $user['password'] ) {
                ajax_return(1, '密码错误');
            }
        } elseif ($data['type'] == 'verify') {
            //验证码登录
            empty($data['verify']) && ajax_return(1, '请输入验证码');

            //验证码校验
            if (config('home.sms_verify_expire') > 0) {
                $verify_expire = session('home.login.verify_expire');
                if ($verify_expire + config('home.sms_verify_expire') < time()) {
                    session('home.login.verify', null);
                    session('home.login.verify_expire', null);
                    ajax_return(1, '验证码已过期');
                }
            }
            $verify = session('home.login.verify');
            if ($verify != $data['verify']) {
                ajax_return(1, '验证码不正确');
            }
        }

        //登录
        $user->last_login_time = time();
        $user->last_login_ip   = request()->ip();
        $user->save();
        session('home.user.id', $user['id']);

        $url = session('back_url') ?? url('/home/my/index')->build();
        session('back_url', null);
        ajax_success(['url' => $url]);
    }
}
