<?php
namespace App\Com;

use EasySwoole\EasySwoole\Config;
use Mrgoon\AliSms\AliSms;
use App\Models\SmsSet;
use App\Models\OperatorsUser;

class Sms
{
	private static $instance;

    protected $uniacid = 17;    //默认固定
    protected $config = Array();  //阿里云接口调用设置

    protected $operators_id;    //运营商ID
    protected $aliSms;  //阿里短信接口对象
    protected $operators_name;  //小程序名称,没有则默认为"前台优选"


    function __construct($operators_id)
    {
        //获取运营商短信设置
        $this->operators_id = $operators_id;
        $smsSet = $this->sms_set();
        // 配置信息
        $this->config['access_key'] = $smsSet['dayu_key'];
        $this->config['access_secret'] = $smsSet['dayu_secret'];
        //小程序名称
        $operators_res = OperatorsUser::create()->where('id',$operators_id)->get()->toArray();
        $this->operators_name = $operators_res['key']?$operators_res['operators_name']:'前台优选';
        $sign_arr = [
            '津辉优选',
            '小富源选',
            '国基乐购',
            '喜相悦',
            '方盒优选',
        ];
        $this->config['sign_name'] = in_array($this->operators_name, $sign_arr) ? $this->operators_name : '前台优选';
        $this->aliSms = new AliSms();
    }


    /**
     * 发送短信
     * @param $mobile 手机号码
     * @param $plate_code 短信模板CODE
     * @param $param 数据参数
     */
    public function send($mobile,$plate_code,$param){
        $response = $this->aliSms->sendSms($mobile, $plate_code, $param, $this->config);
        $response = json_decode(json_encode($response),true);
        $result['request'] = [
            'mobile' => $mobile,
            'plate_code' => $plate_code,
            'param' => $param,
            'operators_name' => $this->operators_name,
        ];
        $result['response'] = $response;
        return $result;
    }


    protected function sms_set()
    {
        //如果存在运营商sms设置则使用该设置
        if($this->operators_id){
            $operators_set = SmsSet::create()->get([
                'uniacid'    => $this->uniacid,
                'operators_id' => $this->operators_id,
                'dayu' => 1,
            ]);
            if($operators_set){
                return $operators_set;
            }
        }
        return $operators_set = SmsSet::create()->where('uniacid',$this->uniacid)->
        where('dayu',1)->where(' (operators_id is null or operators_id=0) ')->get()->toArray();
    }

}