package org.springblade.common.notify.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springblade.common.cache.CachesService;
import com.wn.common.exception.BusinessException;
import org.springblade.common.notify.constant.NotifyErrorConstants;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信发送API
 *
 * @author caiyihua
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "ali.sms.support.flag", havingValue = "true", matchIfMissing = false)
public class AliSmsMsgNotify {

    /**
     * 产品名称:云通信短信API产品
     */
    static final String PRODUCT = "Dysmsapi";
    /**
     * 产品域名
     */
    static final String DOMAIN = "dysmsapi.aliyuncs.com";
    /**
     * 区域标识
     */
    static final String REGION_ID = "cn-hangzhou";
    /**
     * 终端名
     */
    static final String ENDPOINT_NAME = "cn-hangzhou";

    static final String DEFAULT_READ_TIMEOUT = "10000";
    static final String DEFAULT_CONNECT_TIMEOUT = "10000";

    public static final String SMS_CACHE_TYPE = "sms";
    private static final String SUCCESS_CODE = "OK";

    @Value("${ali.sms.access.key.id}")
    @Setter
    private String accessKeyId;
    @Value("${ali.sms.access.key.secret}")
    @Setter
    private String accessKeySecret;
    @Value("${ali.sms.sign.name}")
    @Setter
    private String signName;

    @Autowired
    @Setter
    private CachesService cacheService;

    /**
     * 生成短信验证码，默认失效时间为5分钟
     *
     * @param codeCacheKey 表示验证码缓存的key，建议key包含手机号码信息,如biz1:telephone
     * @return 返回6位短信验证码
     */
    public String generateSmsCode(String codeCacheKey) {
        return generateSmsCode(codeCacheKey, 300);
    }

    /**
     * 生成短信验证码
     *
     * @param codeCacheKey     表示验证码缓存的key，建议key包含手机号码信息,如biz1:telephone
     * @param expiredInseconds 表示失效时间
     * @return 返回6位短信验证码
     */
    public String generateSmsCode(String codeCacheKey, int expiredInseconds) {
        int verCode = (int) ((Math.random() * 9 + 1) * 100000);
        String code = String.valueOf(verCode);
        cacheService.putInCache(SMS_CACHE_TYPE, codeCacheKey, code, expiredInseconds);
        return code;
    }

    /***
     * 校验短信验证码是否正确
     * @param codeCacheKey 表示验证码缓存的key
     * @param inputCode 表示用户输入的短信验证码
     * @return
     */
    public boolean verifySmsCode(String codeCacheKey, String inputCode) {
        if (StringUtils.isBlank(inputCode)) {
            return false;
        }
        String code = cacheService.getFromCache(SMS_CACHE_TYPE, codeCacheKey);
        return inputCode.equals(code);

    }

    public SendSmsResponse sendSms(String telephone, String code, String templateCode, Map<String, Object> params) {
        String json;
        if (params != null) {
            params.put("code", code);
            json = JSON.toJSONString(params);
        } else {
            json = "{code:'" + code + "'}";
        }
        log.info("AliSmsMsgNotify sendSms, json = {}", json);

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(telephone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(json);

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

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

        try {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile(REGION_ID, accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint(ENDPOINT_NAME, REGION_ID, PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse != null && !SUCCESS_CODE.equals(sendSmsResponse.getCode())) {
                log.warn("Send sms msg failure, errCode = {}, errorMsg = {}", sendSmsResponse.getCode(),
                        sendSmsResponse.getMessage());
                throw new BusinessException(NotifyErrorConstants.SMS_SEND_ERROR.getCode(),
                        sendSmsResponse.getMessage());
            }
            log.info("Send sms msg successfully, telephone = {}, RequestId = {}, BizId = {}", telephone,
                    sendSmsResponse.getRequestId(), sendSmsResponse.getBizId());
            return sendSmsResponse;
        } catch (ClientException ce) {
            log.error("Send sms msg error ", ce);
            throw new BusinessException(NotifyErrorConstants.SMS_SEND_FIALED);
        }

    }

    public QuerySendDetailsResponse querySendDetails(String telephone, String bizId) {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(telephone);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        try {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile(REGION_ID, accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint(ENDPOINT_NAME, REGION_ID, PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //hint 此处可能会抛出异常，注意catch
            QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

            return querySendDetailsResponse;
        } catch (ClientException ce) {
            log.error("Send query sms details error ", ce);
            throw new BusinessException(NotifyErrorConstants.SMS_SEND_ERROR);
        }
    }
}
