<?php

namespace app\common\sms;


use app\exception\SmsException;
use app\model\SmsStyle;

class Sms {

    protected $content;
    protected static $smss = [];
    protected static $name;

    public static function init($className = '') {

        // 如果没有设置哪种短信根据配置自动选择
        if (empty($className)) {
            $configs = config('sms');
            $className = 'sms' . $configs['type'];
        }

        $className = ucfirst($className);
        if (!isset(self::$smss[$className])
            || is_null(self::$smss[$className])) {

            $class = 'app\common\sms\\' . $className;
            self::$smss[$className] = new $class;
        }
        self::$name = $className;
        return self::$smss[$className];
    }

    /**
     * 初始化参数
     * @param $params
     * 0 默认读取配置 1 手动设置参数
     * @param int $type
     * @return mixed
     * @throws SmsException
     */
    public static function initParams($params = []) {

        if (!self::$name) {
            throw new SmsException('实例不存在');
        }

        $index = substr(self::$name, -1);

        // 数组就不读取配置 一般测试用
        if (!empty($params)) {

            $configs = $params;

        } else {

            $smsConfigs = config('sms');

            if (!isset($smsConfigs['sms' . $index])) {
                throw new SmsException('短信配置错误');
            }

            $configs = $smsConfigs['sms' . $index];
        }

        /*$dataName = "app\common\sms\SmsData".$index;
        $data = new $dataName ;

        $data->setSid($configs['sid']);
        $data->setToId($configs['to']);
        $data->setToken($configs['token']);
        $data->setContent($content) ;*/

        return $configs;
    }

    // 防掉线
    public static function sendModel($t=0) {

        $config = config('sms');
        if( $config['type'] == 0 ){
            return false ;
        }

        $dropTime = cache('sms_drop_time') ;
        $currentTime = getCurrentTime();
        if( $t == 0 && !is_null($dropTime) && $dropTime > $currentTime){
            return false ;
        }

        $s = Sms::init();
        $p = Sms::initParams();
        $p['to'] = $config['test'] ;
        if ($config['type'] != 2) {
            $d = SmsStyle::where(['type' => $t])->findOrEmpty();;
            if (!$d->isEmpty()) {
                $p['content'] = $d->content;
            }
        }

        $s->send($p);

        if($t == 0){
            cache('sms_drop_time',$currentTime+180);
        }
    }

}
