package com.zcloud.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.gson.Gson;
import java.util.Date;
import java.util.Map;

public class AliyunSmsUtil {

    static final String accessKeyId = "LTAIDJTv7Z3iNLyp";//LTAI4G7hRf3LqVGvobYRFxW2
    static final String accessKeySecret = "LcupykSFftCHbRvzuJIv5YWY0tWKaV";//T43mhQvHiEPt9oBmWP3BLFuqtaYKhr
    private IAcsClient client;


    private AliyunSmsUtil() {
        init();
    }

    private void init() {
        client = new DefaultAcsClient(DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret));
    }

    public static AliyunSmsUtil getInstance() {
        return new AliyunSmsUtil();
    }

    /**
     * 发送国内短信
     *
     * @param phone   接收短信的手机号码
     * @param signName 短信签名名称
     * @param templateCode  短信模板CODE
     * @param templateParam 短信模板变量，Map格式
     * @return 发送结果
     */
    public SendSmsResponse sendSms(String phone, String templateCode, Map<String, Object> templateParam) {
        SendSmsRequest request = new SendSmsRequest();
        //必填-短信接收号码
        request.setPhoneNumbers(phone);
        //必填-短信签名
        request.setSignName("兔优到家");
        //必填-短信模板Code
        request.setTemplateCode(templateCode);

        // 必填-模板变量，JSON格式，替换模板中的变量，不需要替换的参数用空串代替
        request.setTemplateParam(new Gson().toJson(templateParam));
        try {
            return client.getAcsResponse(request);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送国际/港澳台短信
     *
     * @param phone   接收短信的手机号码
     * @param signName 短信签名名称
     * @param templateCode  短信模板CODE
     * @param templateParam 短信模板变量，JSON格式，例如：{\"code\":\"${code}\"}
     * @return 发送结果
     */
    public SendSmsResponse sendInternationalSms(String phone, String signName, String templateCode, Map<String, Object> templateParam) {
        SendSmsRequest request = new SendSmsRequest();
        // 必填-国际/港澳台手机号码
        request.setPhoneNumbers(phone);
        // 必填-短信签名
        request.setSignName(signName);
        // 必填-短信模板Code
        request.setTemplateCode(templateCode);

        // 选填-模板变量，JSON格式，替换模板中的变量，不需要替换的参数用空串代替
        request.setTemplateParam(new Gson().toJson(templateParam));
        try {
            return client.getAcsResponse(request);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}
