package com.sckw.message.service;

import com.alibaba.fastjson2.JSON;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.utils.NumberUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.message.model.vo.req.SendSmsVerifyCoderReqVO;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yzc
 * @date: 2023-06-08 11:08
 * @description:
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsService {

    private final StreamBridge streamBridge;

    /**
     * @param param
     * @return com.sckw.core.web.response.HttpResult
     * @desc: 发送验证码
     * @author: yzc
     * @date: 2023-06-13 13:43
     */
    public void sendVerifyCode(SendSmsVerifyCoderReqVO param) {
        String type = param.getType();
        if (Objects.isNull(DictEnum.getLabel(DictTypeEnum.SEND_SMS_TYPE.getType(), type))) {
            throw new BusinessException("非法短信类型！");
        }
        String phone = param.getPhone();
        String messageSmsVerifyCodeKey = getMessageSmsVerifyCodeKey(type, phone);
        if (Boolean.TRUE.equals(RedissonUtils.exists(messageSmsVerifyCodeKey))) {
            throw new BusinessException("请勿频繁获取短信验证码！");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("code", NumberUtils.createRandomVcode());
        SckwSms sckwSms = new SckwSms();
        sckwSms.setPhone(param.getPhone()).setType(type).setTemplateCode(SmsCodeEnum.VERIFICATION_CODE)
                .setParams(params).setCreateBy(LoginUserHolder.getUserId());
        streamBridge.send("sckw-sms", JSON.toJSONString(sckwSms));
    }

    private String getMessageSmsVerifyCodeKey(String type, String phone) {
        return String.format(RedisConstant.MESSAGE_SMS_VERIFY_CODE_VALUE_KEY, type, phone);
    }
}
