package com.ai.da.common.RabbitMQ;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class MQPublisher {

    @Autowired
    private RabbitMQProperties rabbitMQProperties;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void sendGenerateMessage(String mm) {
        log.info("send generate message: {}", mm);
        amqpTemplate.convertAndSend(rabbitMQProperties.getQueues().getGenerate(), mm);
    }

    public void sendSRMessage(String mm) {
        log.info("send message: {}", mm);
        amqpTemplate.convertAndSend(rabbitMQProperties.getQueues().getSr(), mm);
    }

    /**
     *
     * @param mailParams 含有的字段
     *                   {"dto": basicEmailParamDTO, "filename": fileName, "source": inputStreamSource,
     *                   "templateParams": jsonObject, "templatePath": path}
     *                   邮件发送参数，附件文件名，附件数据
     * @param retryTimes 重试次数（初始为0）
     */
    public void sendEmailMsg(Map<String, String> mailParams, int retryTimes){
        log.info("send email MQ message: {} ", mailParams);
        // // 重新入队（指数退避） 时间单位：毫秒
        long newDelay = (long) (5000 * Math.pow(2, retryTimes + 1));
        log.info("send email MQ delay: {} ms, retry attempt: {}", newDelay, retryTimes + 1);
        amqpTemplate.convertAndSend(
                rabbitMQProperties.getQueues().getEmailRetry(),
                mailParams,
                m -> {
                    m.getMessageProperties().setExpiration(String.valueOf(newDelay));
                    m.getMessageProperties().setHeader("x-retry-attempt", retryTimes + 1);
                    return m;
                }
        );
    }


}
