package com.sckw.message.service;

import com.alibaba.fastjson2.JSON;
import com.sckw.core.common.enums.EnvConstant;
import com.sckw.core.exception.BusinessException;
import com.sckw.message.model.KwmSms;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.enums.SmsCodeEnum;
import com.sckw.stream.model.SckwSms;
import com.sckw.stream.utils.SmsUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author: yzc
 * @date: 2023-06-08 15:54
 * @description: 短信处理service
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SckwSmsHandlerService {

    private final KwmSmsService kwmSmsService;

    @Value("${spring.profiles.active}")
    private String env;


    /**
     * @param sckwSms
     * @return void
     * @desc: 短信处理
     * @author: yzc
     * @date: 2023-06-13 13:44
     */
    public void handler(SckwSms sckwSms) {
        log.info("接收到发送短信消息：{}，开始处理", JSON.toJSONString(sckwSms));
        String type = sckwSms.getType();
        String phone = sckwSms.getPhone();
        String lockKey = getKey(RedisConstant.MESSAGE_SMS_VERIFY_CODE_LOCK_KEY, type, phone);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            log.info("获取发送短信锁失败，不处理");
            return;
        }
        try {
            String requestKey = getKey(RedisConstant.MESSAGE_SMS_VERIFY_CODE_REQUEST_KEY, type, phone);
            if (Boolean.TRUE.equals(RedissonUtils.exists(requestKey))) {
                throw new BusinessException("请勿频繁获取短信验证码！");
            }
            RedissonUtils.putString(requestKey, String.valueOf(sckwSms.getParams().get("code")), RedisConstant.SMS_VERIFY_CODE_REQUEST_TIME);
            //发送短信 生产环境才发短信
            if (EnvConstant.PROD.equals(env)) {
                SmsUtil.sendSms(sckwSms.getPhone(), sckwSms.getSignName(), sckwSms.getTemplateCode().getName(), JSON.toJSONString(sckwSms.getParams()));
            }
            //放入缓存
            String valueKey = getKey(RedisConstant.MESSAGE_SMS_VERIFY_CODE_VALUE_KEY, type, phone);
            RedissonUtils.putString(valueKey, String.valueOf(sckwSms.getParams().get("code")), RedisConstant.SMS_VERIFY_CODE_VALID_TIME);
            //数据入库
            SmsCodeEnum smsCodeEnum = sckwSms.getTemplateCode();
            KwmSms kwmSms = KwmSms.builder().type(smsCodeEnum.getType()).code(smsCodeEnum.getName())
                    .phone(sckwSms.getPhone()).content(smsCodeEnum.getValue())
                    .params(JSON.toJSONString(sckwSms.getParams())).build();
            kwmSms.setCreateBy(sckwSms.getCreateBy());
            kwmSms.setUpdateBy(sckwSms.getCreateBy());
            kwmSmsService.add(kwmSms);
        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }

    private String getKey(String prefix, String args1, String args2) {
        return String.format(prefix, args1, args2);
    }
}
