package com.younike.common.utils.sms;


import com.alibaba.fastjson.JSONObject;
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.http.FormatType;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.younike.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

/**
 * 阿里短信API
 */
@Repository("smsUtil")
public class AliSmsUtil {

    public IAcsClient acsClient;
    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    @Value("${sms.product}")
    private String product = "Dysmsapi";
    /**
     * 产品域名,开发者无需替换
     */
    @Value("${sms.domain}")
    private String domain;
    @Value("${sms.aLiAppKey}")
    private String accessKeyId;
    @Value("${sms.aLiSecret}")
    private String accessKeySecret;
    @Value("${sms.sign}")
    private String sign;

    public IAcsClient getInstant() throws ClientException {
        if (acsClient == null) {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            return acsClient = new DefaultAcsClient(profile);
        }

        return acsClient;
    }

    public SendSmsResponse getSmsCodeClient(String mobile, String templateCode, JSONObject param) throws ClientException {

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //#修改数据提交方式
        request.setMethod(MethodType.POST);
        //#修改数据交互格式
        request.setAcceptFormat(FormatType.JSON);
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(sign);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(param.toString());

        return getInstant().getAcsResponse(request);

    }

    /**
     * @Description: 发送短信
     * @param: [mobile, code]
     * @return:
     */
    public SendSmsResponse sendSms(String mobile, JSONObject json, String templateCode) {
        SendSmsResponse smsResponse = null;
        try {
            smsResponse = getSmsCodeClient(mobile, templateCode, json);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        // 业务错误
        if ("isv.BUSINESS_LIMIT_CONTROL".equals(smsResponse.getCode())) {
            String message = smsResponse.getMessage();
            String limitNum = message.substring(message.length() - 1);
            if ("5".equals(limitNum)) {
                throw new ServiceException("获取次数已达上限，请过一小时再试",600);
            } else if (limitNum.equals("0")) {
                throw new ServiceException("今天获取次数已达上限，请明天再试",600);
            } else if (limitNum.equals("1")) {
                throw new ServiceException("请在1分钟后重新获取验证码",600);
            }
        }
        return smsResponse;
    }


}
