<?php
namespace crmeb\services\sms\storage;

use crmeb\basic\BaseSms;
use think\facade\Config;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Aliyun extends BaseSms
{
    protected $server = 'dysmsapi.aliyuncs.com';
    protected $accessKey;
    protected $accessSecret;
    protected $client;
    protected $sign;

    protected function initialize(array $config)
    {
        parent::initialize($config); // TODO: Change the autogenerated stub
        $this->accessKey = Config::get($this->configFile . '.stores.' . $this->name . '.access_key', '');
        $this->accessSecret = Config::get($this->configFile . '.stores.' . $this->name . '.access_secret', '');
        $this->sign = Config::get($this->configFile . '.stores.' . $this->name . '.sign', '');
        $this->client = AlibabaCloud::accessKeyClient($this->accessKey, $this->accessSecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

    }

    public function send(string $phone, string $templateId, array $data = [])
    {
        if (!$this->accessKey || !$this->accessSecret || !$this->sign) {
            return $this->setError('aliyun 短信参数未设置');
        }
        if (!$phone) {
            return $this->setError('手机号为空');
        }
        $templateCode = $this->getTemplateCode($templateId);
        if (!$templateCode) {
            return $this->setError('找不到短信模板');
        }
        try {
            $res = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host($this->server)
                ->options([
                    'query' => [
                        'RegionId' => 'cn-hangzhou',
                        'PhoneNumbers' => $phone,
                        'SignName' => $this->sign,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => json_encode($data),
                    ],
                ])
                ->request();
            if (!$res) {
                return $this->setError('返回空值');
            }
            $res = $res->toArray();
            if (!isset($res['Code'])) {
                return $this->setError('异常返回值');
            }
            if ($res['Code'] != 'OK') {
                $err = isset($res['Message']) ? $res['Message'] : '';
                return $this->setError($err);
            }
            /*
             * res: ['Message':'OK','RequestId':'string36','BizId':'string20','Code':'OK']
             */
            return [
                'data' => [
                    'content' => $templateId,
                    'template' => $templateId,
                    'id' => intval(substr($res['BizId'],8)),
                ],
            ];
        } catch (ClientException $e) {
            return $this->setError($e->getErrorMessage());
        } catch (ServerException $e) {
            return $this->setError($e->getErrorMessage());
        } // try...catch...
    }
}