package jnpf.attendance.event;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.attendance.service.AttendanceDayStatisticsService;
import jnpf.constants.MessageTopicConstants;
import jnpf.model.attendance.event.StatisticsBatchClearDto;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.stereotype.Component;

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

/**
 * 批量清除日统计消息监听，监听批量清除日统计消息
 * @author 石头
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = MessageTopicConstants.ATTENDANCE_STATISTICS_BATCH_CLEAR_TOPIC,
        consumerGroup = MessageTopicConstants.ATTENDANCE_STATISTICS_BATCH_CLEAR_CONSUMER_GROUP,
        consumeMode = ConsumeMode.CONCURRENTLY,
        maxReconsumeTimes = 10)
public class StatisticsBatchClearMQListener implements RocketMQListener<StatisticsBatchClearDto>, RocketMQPushConsumerLifecycleListener {
    @Resource
    private AttendanceDayStatisticsService attendanceDayStatisticsService;

    @Override
    public void onMessage(StatisticsBatchClearDto batchClearDto) {
        if (Objects.isNull(batchClearDto)) {
            log.warn("接收到空消息，忽略处理");
            return;
        }
        log.info("接受到一条批量清除日统计消息，{}", JSONObject.toJSONString(batchClearDto));
        if (CollUtil.isEmpty(batchClearDto.getUserIdList()) || StringUtil.isEmpty(batchClearDto.getTenantId()) ||
                StringUtil.isEmpty(batchClearDto.getGroupId()) || (Objects.isNull(batchClearDto.getDay()) && Objects.isNull(batchClearDto.getStartDay()))){
            log.error("消费批量清除日统计消息失败：消息格式无效，内容: {}", JSONObject.toJSONString(batchClearDto));
            return;
        }
        try {
            attendanceDayStatisticsService.batchStatisticDataClear(batchClearDto);
        } catch (Exception ex) {
            log.error("消费批量清除日统计消息消费失败，触发重试,消息 {}, 错误:{} ", JSONObject.toJSONString(batchClearDto), ExceptionUtil.stacktraceToString(ex));
            throw new RuntimeException("消费批量清除日统计消息消费失败，触发重试", ex);
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 优化消费参数 每次拉取的消息数量
        consumer.setPullBatchSize(32);
        // 设置消费间隔，避免过于频繁拉取
        consumer.setPullInterval(200);
        // 设置消费超时时间（分钟）
        consumer.setConsumeTimeout(10);
        // 设置消费起始位置（从上次消费的位置继续）
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // 调整消费线程池最小线程数
        consumer.setConsumeThreadMin(10);
        // 调整消费线程池最大线程数
        consumer.setConsumeThreadMax(20);
    }
}
