package com.slodon.b2b2c.sms;

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.core.util.StringUtil;
import com.slodon.b2b2c.sms.base.SmsSender;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

/**
 * 短信发送
 */
@Slf4j
public class YunPianSmsSender extends SmsSender {

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

    /**
     * 云片发送短信方法
     *
     * @param smsRequest
     * @return
     */
    public SmsResponse sendSms(SmsRequest smsRequest) {
        //获取云片key
        String apikey = stringRedisTemplate.opsForValue().get("notification_sms_key");

        //验证码
        String verifyCode = null;
        //验证码类短信
        if (smsRequest.getSmsType() == SMSConst.VERIFY_SMS) {
            //获取短信模板内容
            String tplContent = stringRedisTemplate.opsForValue().get("notification_sms_tpl_content_vc");
            //获取站点名称
            String siteName = stringRedisTemplate.opsForValue().get("basic_site_name");
            verifyCode = RandomUtil.randomNumber(6);
            smsRequest.setTemplateContent(tplContent.replace("#verifyCode#", verifyCode).replace("#app#", siteName));
        }

        if (StringUtil.isEmpty(smsRequest.getTemplateContent())) {
            throw new MallException("请指定短信参数");
        }

        //初始化client
        YunpianClient client = new YunpianClient(apikey).init();
        //发送短信API
        Map<String, String> param = client.newParam(2);
        param.put(YunpianClient.MOBILE, smsRequest.getMobile());
        param.put(YunpianClient.TEXT, smsRequest.getTemplateContent());
        Result<SmsSingleSend> result = client.sms().single_send(param);
        client.close();
        if (result.getCode() != 0) {
            log.error("[YunPianSmsSender][sendSms]短信发送错误[code]:" + result.getCode() + "[msg]:" + result.getMsg());
            switch (result.getCode()) {
                case 22:
                    throw new MallException("每小时获取验证码次数已达上限，请稍后再试");
                case 33:
                    throw new MallException("操作频繁，请稍后再试");
                case 17:
                    throw new MallException("今日获取验证码次数过多,请明日再试");
                default:
                    throw new MallException("短信发送异常，请稍后重试");
            }
        }
        return new SmsResponse(result.getCode().toString(), result.getMsg(), verifyCode);
    }

}
