<?php

namespace app\home\controller;

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

class Register extends HomeBaseController
{

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

    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.register.verify', $rand);
                session('home.register.verify_expire', time());
            } else {
                ajax_return(1, '发送失败，请联系管理员');
            }
        } else {
            ajax_return(1, '手机号格式不正确');
        }

        ajax_return();
    }

    public function doRegister()
    {
        $data     = input('post.');
        $validate = Validate::rule('mobile', 'require|mobile');
        if (!$validate->check($data)) {
            ajax_return(1, '手机号错误');
        }
        empty($data['verify']) && ajax_return(1, '请输入验证码');
        empty($data['password']) && ajax_return(1, '请输入密码');
        empty($data['re_password']) && ajax_return(1, '请输入确认密码');

        if (strlen($data['password']) < 6) {
            ajax_return(1, '密码需要至少6位');
        }
        if ($data['password'] != $data['re_password']) {
            ajax_return(1, '密码和确认密码不同');
        }

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

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

        $add             = [];
        $add['salt']     = rand_str();
        $add['password'] = md5(md5($add['salt']) . $data['password']);
        $add['mobile']   = $add['account'] = $add['nickname'] = $add['realname'] = $data['mobile'];
        $add['status']   = UserModel::STATUS_PASS;
        UserModel::create($add);

        session('home.register.verify', null);
        session('home.register.verify_expire', null);

        ajax_return();
    }
}
