package com.hys.app.mq.core.trigger;

import com.hys.app.framework.cache.Cache;
import com.hys.app.framework.context.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hys.app.framework.trigger.Interface.TimeTriggerExecuter;
import com.hys.app.framework.trigger.rabbitmq.TimeTriggerConfig;
import com.hys.app.framework.trigger.rabbitmq.model.TimeTriggerMsg;
import com.hys.app.framework.trigger.util.RabbitmqTriggerUtil;
import com.hys.app.framework.util.JsonUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 延时任务 消息消费者
 *
 * @author cs
 * @version v1.0
 * @Description:
 * @since v7.0
 * 2021/9/12 下午4:52
 */
@Component
public class TimeTriggerConsumer {


    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private Cache cache;

    /**
     * 接收消息，监听 CONSUMPTION_QUEUE 队列
     */
    @RabbitListener(queues = TimeTriggerConfig.CHAIN_QUEUE_XDELAY)
    public void consume(TimeTriggerMsg timeTriggerMsg) {

        try {
            String key = RabbitmqTriggerUtil.generate(timeTriggerMsg.getTriggerExecuter(), timeTriggerMsg.getTriggerTime(), timeTriggerMsg.getUniqueKey());

            //如果这个任务被标识不执行
            if (cache.get(key) == null) {

                logger.debug("执行器执行被取消：" + timeTriggerMsg.getTriggerExecuter() + "|任务标识：" + timeTriggerMsg.getUniqueKey());
                return;
            }
            logger.debug("执行器执行：" + timeTriggerMsg.getTriggerExecuter());
            logger.debug("执行器参数：" + JsonUtil.objectToJson(timeTriggerMsg.getParam()));

            //执行任务前 清除标识
            cache.remove(key);

            TimeTriggerExecuter timeTriggerExecuter = (TimeTriggerExecuter) ApplicationContextHolder.getBean(timeTriggerMsg.getTriggerExecuter());
            timeTriggerExecuter.execute(timeTriggerMsg.getParam());

        } catch (Exception e) {
            logger.error("延时任务异常：", e);
        }
    }

}
