package com.fdkankan.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author Xiewj
 * @date 2023/6/14
 */
@Component
public class SmsServiceV2 {
    private static Logger log = LoggerFactory.getLogger("programLog");

    @Value("${sms.ali.sign}")
    private String sign;
    @Value("${sms.ali.accessKey}")
    private String accessKeyId;
    @Value("${sms.ali.accessKeySecret}")
    private String accessKeySecret;

    public String sendSms(String phoneNum, String templateParam, String templateCode) throws Exception {
        log.info("cnCode:" + templateCode);
        log.info("templateParam:" + templateParam);
        log.info("sign:" + sign);
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        String result = null;
        try {
            Client client = createClient();

            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();
            // 必填:待发送手机号
            sendSmsRequest.setPhoneNumbers(phoneNum);
            // 必填:短信签名-可在短信控制台中找到
            sendSmsRequest.setSignName(sign);
            // 必填:短信模板-可在短信控制台中找到
            sendSmsRequest.setTemplateCode(templateCode);

            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            sendSmsRequest.setTemplateParam(templateParam);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.dysmsapi20170525.models.SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            // 组装请求对象-具体描述见控制台-文档部分内容

            // hint 此处可能会抛出异常，注意catch
            if (sendSmsResponse != null
                    && !StringUtils.isEmpty(sendSmsResponse.getBody().getCode())){

                if("OK".equals(sendSmsResponse.getBody().getCode())){
                    log.debug("阿里云短信发送成功");
                }else {
                    log.debug("阿里云短信发送失败：" + sendSmsResponse.getStatusCode());
                    log.debug("阿里云短信发送失败原因：" + sendSmsResponse.getStatusCode());
                }
                result = sendSmsResponse.getBody().getCode();
            }else {
                log.debug("阿里云短信发送失败：" + sendSmsResponse.getStatusCode());
                log.debug("阿里云短信发送失败原因：" + sendSmsResponse.getStatusCode());
            }
        }catch (ClientException e){
            log.error("阿里云短信发送失败：" + e);
        }
        return result;
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     * @throws Exception
     */
    public  com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

}
