<?php
namespace app\common\library;
use think\Hook;
/**
 * 短信验证码类
 */
class Sms
{
    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 120;
    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;
    /**
     * 获取最后一次手机发送的数据
     *
     * @param int $mobile 手机号
     * @param string $event 事件
     * @return  Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        Hook::listen('sms_get', $sms, null, true);
        return $sms ? $sms : null;
    }
    /**
     * 发送验证码
     *
     * @param int $mobile 手机号
     * @param int $code 验证码,为空时将自动生成4位数字
     * @param string $event 事件
     * @return  boolean
     */
    public static function send($mobile, $code = null, $event = 'default')
    {
        $code = is_null($code) ? mt_rand(100000, 999999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
       // print_r($sms);
     //   $result = Hook::listen('sms_send', $sms, null, true);
       /*
         $postArr = array(
            'PhoneNumbers' => $mobile,
            'SignName' => '阡陌盒',
            'TemplateCode' => 'SMS_225120613',
            'TemplateParam' => '{"code":"'.$code.'"}',
            'OutId'=>time()
        );
        $options = [
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json; charset=utf-8'
            )
        ];
        $result = \fast\Http::sendRequest('https://dysmsapi.aliyuncs.com/?Action=SendSms', $postArr, 'GET', $options);
        if ($result['ret']) {
            if (isset($result['msg']) && $result['msg'] == '0')
                return TRUE;
         //   $this->error = isset($this->statusStr[$result['msg']]) ? $this->statusStr[$result['msg']] : 'InvalidResult';
        } else {
           // $this->error = $result['msg'];
        }
        */
         // $alisms = new \addons\alisms\Alisms('LTAI5tARQgwrjp5F9LCDEsVg','I1hpp7VB8E7vZEFEzDBT102vvkeVTb');
    // 阿里云短信     
    //      $alisms = new \addons\alisms\Alisms('LTAI5tFAbA9mowuM3jw7sM86','jk7xayyrXs0UlHH5uyCw7eavBpmvrP');
    //   $paramString = '{"code":"'.$code.'"}';
    //   $result = $alisms->smsend($mobile,'SMS_221830044',$paramString);
    // 阿里云短信
    
    // 短信宝
      $smsbao = new \addons\smsbao\Smsbao();
       $result = $smsbao->smsSend(['mobile' => $mobile,'code' => $code]);
       
       //畅天游
//         $ch = curl_init();
//  $un = 'ctut076';
// $pwd = '8c667b';
// $phone = $mobile;
// $msg = urlencode("[盲盒先生]你的短信验证码是：{$code}在1分钟内有效!");
//  $url  = "http://sms.800617.com:4400/sms/SendSMS.aspx?un={$un}&pwd={$pwd}&mobile={$phone}&msg={$msg}";
//  curl_setopt($ch,CURLOPT_URL,$url);
//  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//  curl_setopt($ch,CURLOPT_HEADER,0);
//  // 3. 执行并获取HTML文档内容
//  $output = curl_exec($ch);
//  // 4. 释放curl句柄
//  curl_close($ch);
//   if (!$output) {
//             $sms->delete();
//             return false;
//         }
//         return true;
 //畅天游
    // 短信宝
       // print_r($result);exit;
        if (!$result) {
            $sms->delete();
            return false;
        }
        return true;
    }
    /**
     * 发送通知
     *
     * @param mixed $mobile 手机号,多个以,分隔
     * @param string $msg 消息内容
     * @param string $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = null)
    {
        $params = [
            'mobile' => $mobile,
            'msg' => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params, null, true);
        return $result ? true : false;
    }
    /**
     * 校验验证码
     *
     * @param int $mobile 手机号
     * @param int $code 验证码
     * @param string $event 事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                }
                return true;
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 清空指定手机号验证码
     *
     * @param int $mobile 手机号
     * @param string $event 事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        Hook::listen('sms_flush');
        return true;
    }
}