<?php

namespace app\common\library;

use fast\Random;
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')
    {
        $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 ?: null;
    }

    /**
     * 发送验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码,为空时将自动生成4位数字
     * @param   string $event  事件
     * @return  boolean
     */
    public static function send($mobile, $code = null, $event = 'default')
    {
        $event = 'default';
        $code = is_null($code) ? Random::numeric(config('captcha.length')) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
        //$result = Hook::listen('sms_send', $sms, null, true);

        //阿里短信
        $params['mobile'] = $mobile;
        $params['code'] = $code;

        $result = self::yidong_sms($mobile,$code);

        if (!$result) {
            $sms->delete();
            return false;
        }
        return true;
    }

    //移动云短信https://mas.10086.cn/login
    public static function yidong_sms($mobile,$code){

        $content = '您的短信验证码是'.$code.',本验证码五分钟内有效,请勿泄露';
        $url = 'https://112.35.10.201:28888/sms/submit';
        $data = [
            'ecName' => '江苏达富居家养老健康管理有限公司',
            'apId' => 'dafuhttps',
            'secretKey' => '&YY4vrJb',
            'mobiles' => $mobile,
            'content' => $content,
            'sign' => 'YV61594FE',
            'addSerial' => '',
        ];

        $mac = md5(join('',$data));
        $data['mac'] = $mac;
        unset($data['secretKey']);

        $header = ["Content-Type:application/json;charset=UTF-8"];
        $rs = curl_post($url,base64_encode(json_encode($data)),$header);

        $rs = json_decode($rs,true);
        if(isset($rs['success']) && $rs['success'] == true){
            return true;
        }

        return false;
    }

    /**
     * 短信发送行为
     * @param array $params 必须包含mobile,event,code
     * @return  boolean
     */
    public static function smsSend($params,$countrycode = 86)
    {
        $config = config('alisms');

        $template = $config['template_cn'];  //默认国内模板
        if($countrycode != 86){
            $params['mobile'] = $countrycode.$params['mobile'];
            $template = $config['template_guoji'];
        }

        $alisms = new Alisms();
        $result = $alisms->mobile($params['mobile'])
            ->template($template)
            ->param(['code' => $params['code']])
            ->send();
        return $result;
    }

    /**
     * 发送通知
     *
     * @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 (bool)$result;
    }

    /**
     * 校验验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $event  事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $event = 'default';
        if($code == 1212){
            return true;
        }
        $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;
                } else {
                    return true;
//                    $result = Hook::listen('sms_check', $sms, null, true);
//                    return $result;
                }
            } 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])
            ->delete();
        Hook::listen('sms_flush');
        return true;
    }
}
