package com.slodon.b2b2c.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.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.slodon.b2b2c.core.constant.SMSConst;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.random.RandomUtil;
import com.slodon.b2b2c.core.sms.SmsRequest;
import com.slodon.b2b2c.core.sms.SmsResponse;
import com.slodon.b2b2c.sms.base.SmsSender;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 阿里云短信发送
 */
@Slf4j
public class DySmsSender extends SmsSender {

    private final static Logger logger= LoggerFactory.getLogger(DySmsSender.class);

    public DySmsSender(StringRedisTemplate stringRedisTemplate) {
        super(stringRedisTemplate);
    }

    /**
     * 阿里云发送短信方法
     *
     * @param smsRequest 发送短信
     * @return 响应
     */
    @Override
    public SmsResponse sendSms(SmsRequest smsRequest) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //获取阿里云配置信息
        String secretId = stringRedisTemplate.opsForValue().get("notification_sms_ali_secret");
        String secretKey = stringRedisTemplate.opsForValue().get("notification_sms_ali_secret_key");
        String signName = stringRedisTemplate.opsForValue().get("notification_sms_ali_signature");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", secretKey, secretId);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        } catch (ClientException e) {
            e.printStackTrace();
        }

        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(smsRequest.getMobile());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(smsRequest.getTemplateId());

        String verifyCode = null;
        //验证码类短信
        if (smsRequest.getSmsType() == SMSConst.VERIFY_SMS) {
            verifyCode = RandomUtil.randomNumber(6);
            JSONObject obj = new JSONObject();
            obj.put("code", verifyCode);
            request.setTemplateParam(obj.toJSONString());
        }

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("短信接口返回的数据----------------");
            logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}");
            if (!"OK".equals(sendSmsResponse.getCode())) {
                log.error("[DySmsSender][sendSms]短信发送错误[code]:" + sendSmsResponse.getCode() + "[msg]:" + sendSmsResponse.getMessage());
                throw new MallException("短信发送异常，请稍后重试");
            }
            return new SmsResponse(sendSmsResponse.getCode(), sendSmsResponse.getMessage(), verifyCode);
        } catch (ClientException e) {
            e.printStackTrace();
            log.error("[DySmsSender][sendSms]:", e);
            throw new MallException("发送短信失败：" + e.getMessage());
        }
    }

}
