<?php
namespace app\api\controller\v1;

use app\hander\HelpHander;
use think\Controller;
use think\Db;
use think\Exception;
use tools\Qxsms;

class Send extends Controller
{

    public function sms(){
        $mobile = input('mobile','','trim');
        if(!$mobile){
            HelpHander::error('请输入手机号');
        }
        if(!check_mobile($mobile)){
            HelpHander::error('手机号格式不正确');
        }

        $user = Db::name('user')->where('phone',$mobile)->find();
        if(!$user){
            HelpHander::error('该手机号未注册');
        }

        $max = config('app.max_send_sms')?config('app.max_send_sms'):0;
        $today = strtotime(date('Y-m-d'));
        $curTime = time();
        $nums = Db::name('sms_record')->where('phone',$mobile)->where('add_time','>=',$today)->count();
        if($nums > $max || $max == 0){
            HelpHander::error('短信发送次数已到限制条数');
        }

        // 60s内不能重复发送
        $eTime = $curTime - 60;
        $info = Db::name('sms_record')
            ->where('phone',$mobile)
            ->where('add_time','>=',$eTime)
            ->find();
        if($info){
            HelpHander::error('60秒内只能发送一次短信');
        }

        Db::startTrans();
        try{
            $code = model('SmsRecord')->add($mobile);
            if(!$code){
                \exception('短信发送失败');
            }

            $qxsms = new Qxsms(config('app.sms_config'));
            $content = "【基建中心】您的手机验证码为:".$code.",有限期10分钟。";
            $res = $qxsms->send($mobile,$content);
            if(!$res){
                \exception('短信发送失败');
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            HelpHander::error('短信发送失败');
        }
        HelpHander::success([],'短信发送成功');
    }
}