<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Sms as SmsModel;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     */
    public function send()
    {
        $smsModel = new SmsModel();
        $mobile = $this->request->request("mobile");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号不正确');
        }
        $last = $smsModel->where(['mobile'=>$mobile])->find();
        if ($last && time() - $last['createtime'] < 60) {
            $this->error('发送频繁');
        }
        $code = rand(100000,999999);
        $content = array(
            'content' => "【E-MP market】您的验证码是:" . $code . ",请于10分钟内使用,如非本人操作,可忽略此消息。",//短信内容
            'mobile' => $mobile,//手机号码
            'tKey' => time(),
        );

        $result = json_decode(send_sms($content),true);
        if ($result['code'] != 200) {
            $this->error('发送失败');
        }else{
            $data=[
                'code' => $code,//验证码
                'mobile' => $mobile,//手机号码
                'createtime' => time()
            ];
            $smsModel->save($data);
            $this->success('发送成功');
        }
    }

    /**
     * 检测验证码
     *
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function check()
    {
        $smsModel = new SmsModel();
        $mobile = $this->request->request("mobile");
        $code = $this->request->request("code");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        $last = $smsModel->where(['mobile'=>$mobile,'code'=>$code])->find();
        if ($last) {
            if ($last['createtime']+600 < time()) $this->error(验证码已失效);
            else $this->success('成功');
        } else {
            $this->error('验证码不正确');
        }
    }
}