package com.pj.utils;

import com.alibaba.fastjson.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 com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class SmsUtil {

    private static String accessKeyId = "LTAI5tHbXfyx584B99kqkRrZ";

    private static String accessKeySecret = "puoQbirs9PQFwijyWL0y8ByJMvXBIW";

    private static String sigName = "毕会松个人播客";

    private static String templateCode = "SMS_464500362";

    public static String getAccessKeyId() {
        return accessKeyId;
    }

    public static void setAccessKeyId(String accessKeyId) {
        SmsUtil.accessKeyId = accessKeyId;
    }

    public static String getAccessKeySecret() {
        return accessKeySecret;
    }

    public static void setAccessKeySecret(String accessKeySecret) {
        SmsUtil.accessKeySecret = accessKeySecret;
    }

    public static String getSigName() {
        return sigName;
    }

    public static void setSigName(String sigName) {
        SmsUtil.sigName = sigName;
    }

    public static String getTemplateCode() {
        return templateCode;
    }

    public static void setTemplateCode(String templateCode) {
        SmsUtil.templateCode = templateCode;
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        return new Client(config);
    }

    /**
     * 发送 验证码
     */
    public static SendSmsResponse send(String phone, String verifyCode) {
        JSONObject json = new JSONObject();
        json.put("code", verifyCode);
        String templateParam = JSONObject.toJSONString(json);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(sigName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam(templateParam);
        RuntimeOptions runtime = new RuntimeOptions();
        SendSmsResponse sr = null;
        try {
            Client client = createClient();
            sr = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception e) {
            log.error("阿里云短信服务发送失败：{}",new RuntimeException(e));
            throw new RuntimeException(e);
        }
        return sr;
    }
}
