package com.sckw.stream.utils;

import com.alibaba.fastjson2.JSON;
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.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sckw.core.model.constant.Global;
import com.sckw.stream.enums.SmsCodeEnum;
import com.sckw.stream.model.SckwSms;
import java.util.HashMap;

public class SmsUtil {
    //替换成自己申请的accessKeySecret
    private static String accessKeyId = "LTAI5t7kgqELAKJ5bjJHjsFT";
    private static String accessKeySecret = "QCuFD7A4J8n15Pxw77KtS8IROX1wX7";
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";
    //{"accessKeyId":"LTAI5tEyvh6N9HhxDMkW2MqT","accessKeySecret":"ClQ2q9fxytnhDraX7axAOjlK0zGJAP","signName":"矿拉拉"}

    /**
     * 发送短信
     *
     * @param phoneNumbers 要发送短信到哪个手机号
     * @param signName     短信签名[必须使用前面申请的]
     * @param templateCode 短信短信模板ID[必须使用前面申请的]
     * @param param        模板中${code}位置传递的内容
     */
    public static void sendSms(String phoneNumbers, String signName, String templateCode, String param) {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phoneNumbers);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(param);
            request.setOutId("yourOutId");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (!"OK".equals(sendSmsResponse.getCode())) {
                throw new RuntimeException(sendSmsResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送短信失败");
        }
    }

    public static void main(String[] args) {
        SckwSms sckwSms = new SckwSms();
        sckwSms.setPhone("17358629955");
        sckwSms.setSignName("矿拉拉");
        sckwSms.setTemplateCode(SmsCodeEnum.VERIFICATION_CODE);
        sckwSms.setParams(new HashMap<>(Global.NUMERICAL_SIXTEEN){{put("code", "123456");}});
        try {
            //发送短信 {"code":"123456"}
            SmsUtil.sendSms(sckwSms.getPhone(), sckwSms.getSignName(), sckwSms.getTemplateCode().getName(), JSON.toJSONString(sckwSms.getParams()));
            System.out.println("短信发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

