package com.cf.imes.module.system.mq.producer.sms;

import cn.hutool.core.lang.Pair;
import com.cf.imes.module.system.dal.dataobject.sms.SmsTemplateDO;
import com.cf.imes.module.system.mq.message.sms.SmsSendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * Sms 短信相关消息的 Producer
 *
 * @author zzf
 * @since 2021/3/9 16:35
 */
@Slf4j
@Component
public class SmsProducer {

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 发送 {@link SmsSendMessage} 消息
     *
     * @param logId          短信日志编号
     * @param mobile         手机号
     * @param template       模板信息
     * @param templateParams 短信模板参数
     */
    public void sendSmsSendMessage(Long logId, String mobile, SmsTemplateDO template, List<Pair<String, Object>> templateParams) {
        SmsSendMessage message = new SmsSendMessage().setLogId(logId).setMobile(mobile);
        message.setChannelId(template.getChannelId()).setApiTemplateId(template.getApiTemplateId()).setTemplateType(template.getType()).setTemplateParams(templateParams);
        // event异步发送短信，保证子线程内部request不为空
        RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
        applicationContext.publishEvent(message);
    }

}
