package com.webchat.service.queue;

import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.service.lottery.LotteryOrderService;
import com.webchat.service.queue.dto.LotteryOrderQueueDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author 程序员七七
 * @webSite https://www.coderutil.com
 * @Date 2022/11/13 03:57
 * @description
 * 消息中心消息队列
 * 设置@Lazy为false，因为server这边默认bean懒加载，很有可能一开始就执行不了初始化方法
 */
@Component
@Lazy(value = false)
@Slf4j
public class LotteryOrderQueue extends AbstractRedisQueue<LotteryOrderQueueDTO> {

    @Autowired
    private LotteryOrderService lotteryOrderService;

    @PostConstruct
    public void initBean() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                LotteryOrderQueue.this.schedule();
            }
        }).start();
    }

    @Override
    protected int getPoolSize() {
        return 5;
    }

    /**
     * 从消息队列redis读取数据的超时时间
     * @return
     */
    @Override
    protected long getTimeout() {
        return 10000;
    }

    /**
     * 一个任务元素重试的次数
     * @return 默认不重试
     */
    @Override
    protected int getRetryTimes() {
        return 1;
    }

    /**
     * 一个任务最多被重返队列的次数
     * @return
     */
    @Override
    protected int getBackQueueTimes() {
        return 0;
    }

    @Override
    protected LotteryOrderQueueDTO convert(String s) {
        return JsonUtil.fromJson(s, LotteryOrderQueueDTO.class);
    }

    @Override
    protected String getQueueName() {
        return RedisKeyEnum.QUEUE_LOTTERY_ORDER_MESSAGE.getKey();
    }

    @Override
    protected void receive(LotteryOrderQueueDTO data) {
        if (data == null) {
            log.info("******QueueName:{}, 消费到了空消息******", getQueueName());
            return;
        }
        log.info("【幸运抽奖订单队列】开始处理消息, taskId:{}, message:{}", data.getTaskId(), data);
        lotteryOrderService.handleLotteryOrder(data);
        log.info("【幸运抽奖订单队列】消息处理成功. taskId:{}", data.getTaskId());
    }

    @Override
    protected void error(LotteryOrderQueueDTO data, Exception ex) {
        log.error("【幸运抽奖订单队列】消费出错 taskId:{}, ex:{}", data.getTaskId(), ex);
    }
}
