<?php

namespace App\Libs;

use Exception;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\QuerySmsTemplateListRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\QuerySmsTemplateListResponse;


class AliSMS
{

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Dysmsapi Client
     */
    public static function createClient(): Dysmsapi
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId"     => env('SMS_AccessKeyId'),
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => env('SMS_AccessKeySecret')
        ]);

        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 发送短信
     * https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms
     *
     * @param $phone
     * @param $templateCode
     * @param $param
     * @param $sign
     * @return SendSmsResponse|void
     */
    public static function sendSms($phone, $templateCode, $param, $sign)
    {
        $client = self::createClient();

        // 组装请求参数
        $sendSmsRequest                = new SendSmsRequest([]);
        $sendSmsRequest->phoneNumbers  = $phone;
        $sendSmsRequest->templateCode  = $templateCode;
        $sendSmsRequest->templateParam = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sendSmsRequest->signName      = $sign;

        $runtime = new RuntimeOptions([]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            return $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        } catch (Exception $error) {
            dLog('exception')->info('sendSms', [$error->getMessage(), $error->getCode()]);
        }
    }

    /**
     * 查询短信模板
     * https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/QuerySmsTemplateList
     *
     * @return QuerySmsTemplateListResponse|void
     */
    public static function querySmsTemplateList()
    {
        $client                      = self::createClient();
        $querySmsTemplateListRequest = new QuerySmsTemplateListRequest([]);
        $runtime                     = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            return $client->querySmsTemplateListWithOptions($querySmsTemplateListRequest, $runtime);
        } catch (Exception $error) {
            dLog('exception')->info('querySmsTemplateList', [$error->getMessage(), $error->getCode()]);
        }
    }
}
