package com.srs.framework.autoconfig.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.srs.framework.autoconfig.properties.SmsProperties;

import java.util.Objects;

public class SmsTemplate {
    private SmsProperties properties;
    public SmsTemplate(SmsProperties properties){
        this.properties=properties;
    }
    /**
     * 调用阿里云短信接口
     * @param mobile 手机号
     * @param code 短信内容
     * @param smsType 短信类型
     */
    public boolean sendSms(String mobile,String code,int smsType) throws Exception {
        //配置阿里云
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(properties.getAccessKey())
                // 您的AccessKey Secret
                .setAccessKeySecret(properties.getSecret());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";

        Client client =  new Client(config);

        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        if (smsType==1) {
            sendSmsRequest.setPhoneNumbers(mobile)
                    .setSignName(properties.getSignName())
                    .setTemplateCode(properties.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
        } else {
            sendSmsRequest.setPhoneNumbers(mobile)
                    .setSignName(properties.getNoticeSignName())
                    .setTemplateCode(properties.getNoticeTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
        }
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            return Objects.equals(sendSmsResponse.getBody().code, "OK");
        } catch (TeaException error) {
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            return false;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            return false;
        }
    }
}