package com.tofly.gpsboot.handler.plan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tofly.gpsboot.common.system.IsPlanChildStateEnum;
import com.tofly.gpsboot.common.system.PlanStateEnum;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Planchild;
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.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

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

    @Autowired
    private PlanService planService;
    @Autowired
    private PlanchildService planchildService;

    @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));
        Set<Long> unfinishedPlanIdList = new HashSet<>();
        // 判断计划结束时间是否小于当前时间,若小于状态则改为 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());
                unfinishedPlanIdList.add(info.getId());
            }
        });

        // 修改子计划状态为 11
        if (unfinishedPlanIdList.size() > 0) {
            planchildService.update(new UpdateWrapper<Planchild>().lambda()
                    .in(Planchild::getPlanId, unfinishedPlanIdList)
                    .set(Planchild::getPlanState, IsPlanChildStateEnum.PLAN_STATE_PLAN_UNFINISHED.getCode()));
        }
        planService.updateBatchById(planList);

        // 处理任务是否已完成,完成则子任务也完成
        planchildService.updateStateOver();
        return ReturnT.SUCCESS;
    }

}
