<?php

namespace app\common\service;

use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use support\exception\BusinessException;

class SmsService
{

    public  $config;


    public function __construct()
    {
        $config = [
            // HTTP 请求的超时时间(秒)
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略,默认:顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'yunpian', 'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => runtime_path() . '/logs/' . date('Ymd') . '/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => 'LTAI5t7mhH3ij2cNWs1zhPmv',
                    'access_key_secret' => 'gqo2wMpvi8h5bDBmCpMje6BaiXvcPu',
                    'sign_name' => '里海科技',
                ],
                //...
            ],
        ];
        $this->config=$config;

    }

    public function client($phone,$template,$code,$type = 0)
    {
        try{
            $easySms = new EasySms($this->config);

            if($type){//预留发送到货短信
                $res = $easySms->send($phone, [
                    'content'  => '您的验证码为: '.$code,
                    'template' => $template,
                    'data' => [
                        'code' => $code
                    ],
                ]);

            }else{
                $res = $easySms->send($phone, [
                    'content'  => '您的验证码为: '.$code,
                    'template' => $template,
                    'data' => [
                        'code' => $code
                    ],
                ]);
            }

            if($res && $res['aliyun']['status'] == 'success'){
                return  true;
            }else{
                return  false;
            }
        }catch(NoGatewayAvailableException $e){

            throw new BusinessException($e->getExceptions());
        }

    }
}