package com.sckw.message.service;

import com.alibaba.fastjson2.JSON;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.message.model.KwmSms;
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.stereotype.Service;

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

    private final KwmSmsService kwmSmsService;

    /**
     * @param sckwSms
     * @return void
     * @desc: 短信处理
     * @author: yzc
     * @date: 2023-06-13 13:44
     */
    public void handler(SckwSms sckwSms) {
        log.info("接收到发送短信消息：{}，开始处理", JSON.toJSONString(sckwSms));
        String requestKey = getKey(RedisConstant.MESSAGE_SMS_VERIFY_CODE_REQUEST_KEY, sckwSms.getPhone());
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(requestKey, 10L, RedisConstant.SMS_VERIFY_CODE_VALID_TIME))) {
            log.info("重复发送短信消息，不处理");
            return;
        }
        String valueKey = getKey(RedisConstant.MESSAGE_SMS_VERIFY_CODE_VALUE_KEY, sckwSms.getPhone());
        //发送短信
        RedissonUtils.putString(valueKey, String.valueOf(sckwSms.getParams().get("code")), RedisConstant.SMS_VERIFY_CODE_VALID_TIME);
        //发送短信
        SmsUtil.sendSms(sckwSms.getPhone(), sckwSms.getSignName(), sckwSms.getTemplateCode().getName(), JSON.toJSONString(sckwSms.getParams()));
        //数据入库
        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);
    }

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