package com.tofly.gpsboot.handler.plan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.gpsboot.common.system.AuditSateEnum;
import com.tofly.gpsboot.common.system.PlanStateEnum;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.PlanMt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 计划超时处理
 *
 * @author BZ-DJJ
 */
@Component
public class PlanTimeoutHandler {

    @Autowired
    private PlanService planService;

    @XxlJob("planTimeoutHandler")
    public ReturnT<String> planTimeoutHandler(String param) {
        // 获取当前巡检计划状态为5已开始未执行 3 正在执行的数据 2未开始
        List<String> planStateList = new ArrayList<>();
        planStateList.add(PlanStateEnum.PLAN_STATE_BEING_PERFORMED.getCode());
        planStateList.add(PlanStateEnum.PLAN_STATE_EXECUTION_NOT_STARTED.getCode());
        planStateList.add(PlanStateEnum.PLAN_STATE_NOT_START.getCode());

        List<Plan> planList = planService.list(new QueryWrapper<Plan>().lambda()
                .in(Plan::getPlanState, planStateList));
        // 判断计划结束时间是否小于当前时间,若小于状态则改为 11 计划未完成,已超时
        LocalDateTime now = LocalDateTime.now();
        planList.forEach(info -> {
            LocalDateTime dateTime = DateTimeUtil.fromLong2LocalDateTime(info.getPlanEnddate().getTime());
            if (!now.isBefore(dateTime)) {
                info.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_UNFINISHED.getCode());
            }
        });
        planService.updateBatchById(planList);
        return ReturnT.SUCCESS;
    }

}
