package net.northking.cctp.executePlan.consumer;

import cn.hutool.core.util.ObjectUtil;
import net.northking.cctp.executePlan.api.service.AtuPlanBatchApiService;
import net.northking.cctp.executePlan.constants.PlanConstant;
import net.northking.cctp.executePlan.constants.RabbitConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanTask;
import net.northking.cctp.executePlan.db.service.AtuPlanTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: TaskTimeoutDelayConsumer</p>
 * <p>Description: 任务超时延迟队列消费者</p>
 *
 * @Author chenjianfeng
 * @Version V1.0
 * @Date 2023/02/10
 * <p>Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.</p>
 */
@Component
public class TaskTimeoutDelayConsumer {

    private final static Logger logger = LoggerFactory.getLogger(TaskTimeoutDelayConsumer.class);

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private AtuPlanTaskService planTaskService;

    @Autowired
    private AtuPlanBatchApiService planBatchApiService;

    @PostConstruct
    public void init(){
        // 初始化交换机与队列
        // 创建交换机
        Map<String, Object> args = new HashMap<>(4);
        args.put("x-delayed-type", "direct");
        CustomExchange exchange = new CustomExchange(RabbitConstant.TASK_TIMEOUT_DELAY_EXCHANGE_NAME,
                "x-delayed-message", true, false, args);
        amqpAdmin.declareExchange(exchange);
        // 创建队列
        Queue queue = new Queue(RabbitConstant.TASK_TIMEOUT_DELAY_QUEUE_NAME);
        amqpAdmin.declareQueue(queue);
        // 交换机与队列绑定
        Binding binding = BindingBuilder.bind(queue).to(exchange)
                .with(RabbitConstant.TASK_TIMEOUT_DELAY_ROUTING_KEY).noargs();
        amqpAdmin.declareBinding(binding);
    }

    @RabbitListener(queues = RabbitConstant.TASK_TIMEOUT_DELAY_QUEUE_NAME)
    public void receive(Message message){
        logger.info("任务超时信息 ==> " + new String(message.getBody()));
        // 根据批次ID更新未完成的任务为超时
        String taskId = new String(message.getBody());

        // 判断任务是否完成
        AtuPlanTask task = planTaskService.findByPrimaryKey(taskId);
        if (ObjectUtil.isNull(task)){
            logger.error("超时任务[" + taskId + "]不存在");
            return;
        }
        // 任务执行完成
        if (!ObjectUtil.equal(PlanConstant.TASK_WAIT_EXECUTE_STATUS, task.getStatus())
                && !ObjectUtil.equals(PlanConstant.TASK_START_EXECUTE_STATUS, task.getStatus())){
            logger.info("超时任务[" + task.getId() + "]已执行完成");
            return;
        }
        if (ObjectUtil.isNull(task.getStartTime())){
            task.setStartTime(task.getCreatedTime().getTime());

            task.setStatus(PlanConstant.TASK_START_EXECUTE_STATUS);
            planBatchApiService.updateCacheBatchSumData(task);
        }
        task.setStatus(PlanConstant.TASK_TIMEOUT_STATUS);
        task.setEndTime(System.currentTimeMillis());
        task.setErrorMsg("设备离线超时");
        planTaskService.updateByPrimaryKey(task);

        planBatchApiService.updateCacheBatchSumData(task);
    }
}
