<?php
/**
 * Created by PhpStorm.
 * User: xiezhixian
 * Date: 2018/5/4
 * Time: 上午10:48
 */

namespace app\api\model;

use think\Model;
use Dysmsapi\Request\V20170525\SendSmsRequest;

require VENDOR_PATH . 'aliApiSdk/aliyun-php-sdk-core/Config.php';
require VENDOR_PATH . 'aliApiSdk/Dysmsapi/Request/V20170525/SendSmsRequest.php';

class Sms extends Model
{
    /**
     * 表名,
     */
    protected $table = 'sms';
    protected $dateFormat = false;

    /**
     * @return Sms
     */
    public static function build()
    {
        return new self();
    }

    /**
     * @author: Airon
     * @time:   2018年5月
     * description
     * @param array $dataMap
     * @return int|string
     * @throws \think\Exception
     */
    public static function whereCount($dataMap = [])
    {
        return static::build()->where($dataMap)->count();
    }

    /**
     * 发送短信
     * @param String $mobile
     * @param String $code
     * @param String $smsType 短信类型,enum:登录:login 绑定手机号: bind 修改支付密码:pay_password
     * @return bool
     */
    public static function sendSms($mobile, $code, $smsType)
    {
        // 调用sdk发送短信
        $aliConfig = config('alidayu');
        // 加载区域结点配置
        // 初始化用户Profile实例
        $profile = \DefaultProfile::getProfile("cn-hangzhou", $aliConfig['AccessKey'], $aliConfig['SecretKey']);
        // 增加服务结点
        \DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        // 初始化AcsClient用于发起请求
        $acsClient = new \DefaultAcsClient($profile);
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($mobile);
        // 必填，设置签名名称
        $request->setSignName($aliConfig['smsType'][$smsType]['signName']);
        // 必填，设置模板CODE
        $request->setTemplateCode($aliConfig['smsType'][$smsType]['templateCode']);
        $params = array(
            'code' => $code,
        );
        // 可选，设置模板参数
        $request->setTemplateParam(json_encode($params));
        $acsResponse = $acsClient->getAcsResponse($request);
        $send_result = $acsResponse->Code == 'OK' ? 'ok' : $acsResponse->Code . ":" . $acsResponse->Message;

        date_default_timezone_set("Asia/Shanghai");//短信SDK强行转换了时区导致PHP无法识别使用了默认时区，这里需要强制转换回上海时区

        //修改其它验证码的有效性
        self::build()->update(['is_effected' => 0], ['mobile' => $mobile, 'sms_type' => $smsType]);
        // 写入数据库
        $bool = self::build()->insert([
            'uuid' => uuid(),
            'mobile' => $mobile,
            'sms_type' => $smsType,
            'sms_code' => $code,
            'send_result' => $send_result,
            'create_time' => timeToDate(time()),
            'update_time' => timeToDate(time()),
        ]);
        return $bool;
    }


    /**
     * @author: Airon
     * @time:   2018年5月
     * description 验证短信验证码
     * @param $mobile
     * @param $code
     * @param $smsType
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function validateCode($mobile, $code, $smsType)
    {
        $smsModel = self::build()->where([
            'mobile' => $mobile,
            'sms_type' => $smsType,
            'is_effected' => '1',
        ])->order(['create_time' => 'desc'])->find();

        // 验证码不存在
        if (empty($smsModel)) {
            return false;
        }

        // 验证码已过期
        if ((strtotime($smsModel['create_time']) + 3600 ) < time()) {
            self::build()->where([ 'uuid' => $smsModel['uuid'] ])->update([ 'is_effected' => '0','update_time'=>timeToDate(time())]);
            return false;
        }

        // 验证码错误，
        if ($smsModel['sms_code'] != $code) {
            // 尝试次数+1, 尝试次数大于10次，销毁
            if ($smsModel['try_times'] >= 10) {
                self::build()->where([ 'uuid' => $smsModel['uuid'] ])->update([ 'is_effected' => '0' ]);
            } else {
                self::build()->where([ 'uuid' => $smsModel['uuid'] ])->inc('try_times')->update();
            }
            return false;
        }

        //验证成功后销毁
        self::build()->where([ 'uuid' => $smsModel['uuid'] ])->update([ 'is_effected' => '0' ]);
        return true;
    }
}
