package com.sckw.message.utils;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class SmsUtil {
    /**
     * 阿里云 accessKeyId
     */
    private static final String ACCESS_KEY_ID = "LTAI5t7kgqELAKJ5bjJHjsFT";

    /**
     * 阿里云 accessKeySecret
     */
    private static final String ACCESS_KEY_SECRET = "QCuFD7A4J8n15Pxw77KtS8IROX1wX7";

    /**
     * endpoint
     */
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    /**
     * 单例 Client
     */
    private static final Client CLIENT;

    static {

        try {

            Config config = new Config().setAccessKeyId(ACCESS_KEY_ID).setAccessKeySecret(ACCESS_KEY_SECRET);
            config.setEndpoint(ENDPOINT);
            config.setRegionId("cn-hangzhou");
            config.setMethod("POST");


            CLIENT = new Client(config);

            log.info("阿里云短信Client初始化成功");

        } catch (Exception e) {

            log.error("阿里云短信Client初始化失败", e);

            throw new RuntimeException("初始化短信Client失败");
        }
    }


    public static boolean sendSms(String phoneNumbers, String signName, String templateCode, Map<String, Object> params) {

        try {

            // 模板参数转json
            String templateParam = JSON.toJSONString(params);

            SendSmsRequest request = new SendSmsRequest().setPhoneNumbers(phoneNumbers).setSignName(signName).setTemplateCode(templateCode).setTemplateParam(templateParam);

            log.info("开始发送短信，手机号：{}，模板：{}，参数：{}", phoneNumbers, templateCode, templateParam);

            SendSmsResponse response = CLIENT.sendSms(request);
            log.info("短信发送响应：{}", JSONObject.toJSONString(response));

            String code = response.getBody().getCode();
            String message = response.getBody().getMessage();
            String bizId = response.getBody().getBizId();

            // 阿里云成功code为OK
            if ("OK".equals(code)) {

                log.info("短信发送成功，手机号：{}，bizId：{}", phoneNumbers, bizId);

                return true;
            }

            log.error("短信发送失败，手机号：{}，code：{}，message：{}", phoneNumbers, code, message);

            return false;

        } catch (Exception e) {

            log.error("短信发送异常", e);

            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        boolean result = SmsUtil.sendSms(
                "17076615563",
                "乐山沙湾盛昶矿石加工",
                "SMS_506110118",
                Map.of(
                        "code", "1234"
                )
        );

        System.out.println("发送结果：" + result);
    }

}

