<?php
namespace Extend\Alibaba;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use App\Model\LogSms;
use App\Utils\Log;
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config as OpenApiConfig;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;

/**
 * 阿里大鱼-短信
 */
class Dysms
{
    /**
     * 创建客户端
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return OpenApiClient Client
     */
    public static function createClient(string $accessKeyId, string $accessKeySecret): OpenApiClient
    {
        $config = new OpenApiConfig([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new OpenApiClient($config);
    }

    /**
     * API 相关
     * @return Params OpenApi.Params
     */
    public static function createApiInfo(): Params
    {
        $params = new Params([
            // 接口名称
            "action" => "SendSms",
            // 接口版本
            "version" => "2017-05-25",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "POST",
            "authType" => "AK",
            "style" => "RPC",
            // 接口 PATH
            "pathname" => "/",
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }

    /**
     * 发送短信
     * @param string $phone_numbers 手机号
     * @param array $template_param 参数
     * @param string $template_code 短信模版编码
     * @param string $scene_desc 场景
     */
    public static function sendSms(string $phone_numbers,array $template_param,string $template_code,string $scene_desc = ""): void
    {
        try {
            $config = config("alibaba.dysms");

            $client = self::createClient($config['accessKey'], $config['accessKeySecret']);
            $params = self::createApiInfo();

            // query params
            $queries = [];
            $queries["PhoneNumbers"] = $phone_numbers;
            $queries["SignName"] = "肝胆相照";
            $queries["TemplateCode"] = $template_code;
            $queries["TemplateParam"] = json_encode($template_param,JSON_UNESCAPED_UNICODE);
            // runtime options
            $runtime = new RuntimeOptions([]);
            $request = new OpenApiRequest([
                "query" => OpenApiUtilClient::query($queries)
            ]);
            // 复制代码运行请自行打印 API 的返回值
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode
            $result = $client->callApi($params, $request, $runtime);

            if (empty($result)){
                throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::CODE_FAIL));
            }

            if (empty($result['body'])){
                throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::CODE_FAIL));
            }

            Log::getInstance()->info("发送短信日志：" . json_encode($result['body'],JSON_UNESCAPED_UNICODE));

            if ($result['body']['Code'] != "OK"){
                if (isset($result['body']['MessageIm'])){
                    throw new BusinessException($result['body']['MessageIm'],HttpEnumCode::CODE_FAIL);
                }
                throw new BusinessException("短信发送失败",HttpEnumCode::CODE_FAIL);
            }

            if (empty($result['body']['RequestId'])){
                // 无唯一值
                if (isset($result['body']['MessageIm'])){
                    throw new BusinessException($result['body']['MessageIm'],HttpEnumCode::CODE_FAIL);
                }
                throw new BusinessException("短信发送失败",HttpEnumCode::CODE_FAIL);
            }

            // 记录log
            $data = array();
            $data['type'] = 1;
            $data['status'] = 1;
            $data['phone'] = $phone_numbers;
            $data['template_code'] = $template_code;
            $data['third_code'] = $result['body']['RequestId'];
            $data['scene_desc'] = $scene_desc ?: "";
            $data['remarks'] = json_encode($template_param,JSON_UNESCAPED_UNICODE);
            $res = LogSms::LogSms($data);
            if (empty($res)){
                // 发送成功，记录失败
                Log::getInstance()->info("发送短信成功，记录log失败" . json_encode($data,JSON_UNESCAPED_UNICODE));
            }

        }catch (\Exception $e) {
            Log::getInstance()->error("发送短信失败：" . $e->getMessage());

            // 记录log
            $data = array();
            $data['type'] = 1;
            $data['status'] = 2;
            $data['phone'] = $phone_numbers;
            $data['template_code'] = $template_code;
            $data['third_code'] = $result['body']['RequestId'];
            $data['scene_desc'] = $scene_desc ?: "";
            $data['remarks'] = json_encode($template_param,JSON_UNESCAPED_UNICODE);
            $res = LogSms::LogSms($data);
            if (empty($res)){
                // 发送成功，记录失败
                Log::getInstance()->info("发送短信失败，记录log失败" . json_encode($data,JSON_UNESCAPED_UNICODE));
            }

            throw new BusinessException($e->getMessage(),HttpEnumCode::CODE_FAIL);
        }
    }
}