<?php

namespace app\service\ali;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Tea;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendBatchSmsRequest;
use think\facade\Log;

class Sms
{
    public const SMS_SIGN = '佩丽商城';

    // 会员注册模版
    public const TEMPLATE_REGISTER_CODE = 'SMS_187934108';
    // 会员通知模版
    public const TEMPLATE_USER_NOTICE = 'SMS_231451587';
    // 活动通知
    public const TEMPLATE_USER_NEW_ACTIVITY = 'SMS_231436568';
    // 员工通知
    public const TEMPLATE_STAFF_NOTICE = 'SMS_231436569';

    public const STATUS_SUCCESS = 'success';
    public const STATUS_FAIL    = 'fail';

    /**
     * 使用AK&SK初始化账号Client
     * @param  string  $accessKeyId
     * @param  string  $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient(string $accessKeyId = '', string $accessKeySecret = ''): Dysmsapi
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId"     => $accessKeyId ?: 'LTAI4GExL5cc8uHnKJjyqH4h',
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret ?: 'TNUc1DcQSUOBGmFpKKjT2ImXbg99hO'
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";

        return new Dysmsapi($config);
    }

    /**
     * 批量发送[api自带 看场景使用]
     *
     * @param  array  $args
     * args = [
     * 'phoneNumberJson' => '["135411****","1xxxx"]',
     * 'signNameJson' => '["佩丽商城","恒美会"]',
     * 'templateCode'    => 'SMS_187934108',
     * 'templateParamJson' => '[{"code":"12345"},{"code":"3333"}]'
     * ]
     *
     * 文档参照:https://next.api.aliyun.com/document/Dysmsapi/2017-05-25/SendBatchSms
     * 注意:参数名 小驼峰 非文档中的大驼峰
     */
    public static function batchSendByApi(array $args): bool
    {
        //注意格式
        //        $args = [
        //            'phoneNumberJson'   => '["13541194069"]',
        //            'signNameJson'      => '["佩丽商城"]',
        //            'templateCode'      => 'SMS_187934108',
        //            'templateParamJson' => '[{"code":"12345"}]'
        //        ];

        try {
            $client              = self::createClient();
            $sendBatchSmsRequest = new SendBatchSmsRequest($args);
            $resp                = $client->sendBatchSms($sendBatchSmsRequest);
            Utils::toArray(Tea::merge($resp));
            return true;
        } catch (\Exception $e) {
            // code: 400, PhoneNumberJson is mandatory for this action. request id: BED81831-C32E-5589-99C6-D1D05555230A
            Log::error('【短信批量发送失败】'.$e->getMessage());
            return false;
        }
    }

    /**
     * 短信发送
     *
     * @param  string  $phone  手机号
     * @param  array  $args  参数 如['code' => '3333', 'other' => 'other value'];
     * @param  string  $templateId  模版  默认注册验证码模版
     * @param  string  $signName  标签 默认 佩丽商城
     * @return bool|string
     */
    public static function send(string $phone, array $args, string $templateId = self::TEMPLATE_REGISTER_CODE, string $signName = self::SMS_SIGN)
    {
        //        $args = [
        //            'phoneNumbers'  => '13541194069',
        //            'signName'      => '佩丽商城',
        //            'templateCode'  => 'SMS_187934108',
        //            'templateParam' => '{"code":"66666","other":"other value"}'
        //        ];

        $templateParam = !empty($args) ? json_encode($args, JSON_UNESCAPED_UNICODE) : '';
        $args = [
            'phoneNumbers'  => $phone,
            'signName'      => $signName,
            'templateCode'  => $templateId,
            'templateParam' => $templateParam
        ];

        try {
            $client         = self::createClient();
            $sendSmsRequest = new SendSmsRequest($args);
            $resp           = $client->sendSms($sendSmsRequest);
            $res            = Utils::toArray(Tea::merge($resp));
            if (!isset($res['body']) || !isset($res['body']['Code'])) {
                return '返回结果异常';
            }

            if ($res['body']['Code'] != 'OK') {
                return sprintf("【短信发送失败】:code %s, msg:%s", $res['body']['Code'], $res['body']['Message']);
            }
            return true;
        } catch (\Exception $e) {
            Log::error('【短信发送失败】'.$e->getMessage());
            return '【短信发送失败】'.$e->getMessage();
        }
    }

    // 短信模版
    public static function templateList(): array
    {
        return [
            ['name' => '会员通知', 'value' => self::TEMPLATE_USER_NOTICE],
//            ['name' => '会员注册验证码', 'value' => self::TEMPLATE_REGISTER_CODE],
            ['name' => '员工通知', 'value' => self::TEMPLATE_STAFF_NOTICE],
            ['name' => '活动通知', 'value' => self::TEMPLATE_USER_NEW_ACTIVITY],
        ];
    }

    // 短信模版参数列表
    public static function templateParams(): array
    {
        return [
            self::TEMPLATE_REGISTER_CODE     => [
                [
                    'name'  => '验证码',
                    'type'  => 'string',
                    'value' => 'code',
                ],
            ],
            self::TEMPLATE_USER_NOTICE       => [
                []
            ],
            self::TEMPLATE_STAFF_NOTICE      => [
                []
            ],
            self::TEMPLATE_USER_NEW_ACTIVITY => [
                []
            ],
        ];
    }
}