package com.fdkanfang.common.sms;

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.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Log4j2
@Component
public class SmsService {

    //初始化ascClient需要的几个参数
    private static final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
    private static final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
    private static final String accessKeyId = "LTAIUrvuHqj8pvry";//你的accessKeyId,参考本文档步骤2
    private static final String accessKeySecret = "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4";//你的accessKeySecret，参考本文档步骤2
    private static final String signName = "四维看房";

    public static boolean sendSms(String phoneNum, String templateParam, String templateCode) {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        boolean result = false;
        try {
            // 初始化acsClient,暂不支持region化
            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(phoneNum);
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            // 必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);

            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam(templateParam);

            // 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            // request.setSmsUpExtendCode("90997");

            // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            // request.setOutId("yourOutId");

            // hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse != null
                    && !StringUtils.isEmpty(sendSmsResponse.getCode())
                    && "OK".equals(sendSmsResponse.getCode())){
                log.debug("阿里云短信发送成功");
                result = true;
            }
        }catch (ClientException e){
            log.error("阿里云短信发送成功：" + e);
        }
        return result;
    }

    public  boolean sendSms(String yzmStr,String userPhone){

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK
        final String accessKeyId = "LTAIUrvuHqj8pvry";//你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4";//你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumbers(userPhone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("四维看房");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_126461520");
        request.setTemplateParam("{\"code\":"+yzmStr+"}");

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //System.out.println("向阿里请求发短信失败");
            log.error("sendSms:向阿里请求发短信失败");
        }
        if(sendSmsResponse == null)
        {
            log.error("sendSms:向阿里请求发短信失败");
        }
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            //System.out.println("向阿里请求发短信成功");
            log.info("sendSms:向阿里请求发短信成功");
            return true;

        }
        return false;
    }

    public static void main(String[] args) {
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        System.out.println(code);

        /**
         * 四维看看：SMS_126461520
         * 四维看房：SMS_184616399
         */
        sendSms("15015980188","{\"code\":\"" + code + "\"}", "SMS_184616399");
    }
}
