<?php

namespace app\mobile\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称:register=注册,resetpwd=忘记密码,changemobile1=修改手机号第一步,changemobile2=修改手机号第二步,changepwd=修改密码
     */
    public function send()
    {
        $mobile = $this->request->get("mobile");
        $event = $this->request->get("event");
        $event = $event ? $event : 'register';
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        // if ($last && time() - $last['createtime'] < 60) {
        //     $this->error(__('发送频繁'));
        // }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 500) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile2']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd', 'changemobile1']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = $this->getCode($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'),['code'=>$ret]);
        } else {
            $this->error($ret['msg']);
        }
    }

    private function getCode($mobile, $code = null, $event = 'default'){
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $sms = \app\common\model\Sms::create([
            'event' => $event, 
            'mobile' => $mobile, 
            'code' => $code, 
            'ip' => request()->ip(), 
            'createtime' => $time
        ]);
        // $ret = send_sms2([
        //     'content' => "【帛芮定制】您的验证码是:" . $code . ",请尽快返回完成验证,请勿转载或泄露,谨防被骗。",//短信内容
        //     'mobile' => $mobile,//手机号码
        //     'tKey' => time(),
        // ]);
        // $ret = json_decode($ret,true);
        // if($ret['code'] == 200){
        //     return true;
        // }
        // $this->error($ret['msg']);
        return $code;
    }

    /**
     * 校验验证码
     * @ApiInternal
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - 120;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['createtime'] > $time && $sms['times'] <= 10) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                } else {
                    return true;
                }
            } else {
                // 过期则清空该手机验证码
                Smslib::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }
}