package com.tofly.gpsboot.handler.plan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 计划时间在执行时间,修改状态为未开始
 * @author BZ-DJJ
 */
@Component
public class PlanExecuteStateHandler {

    @Autowired
    private PlanService planService;

    @Transactional(rollbackFor = Exception.class)
    public void planExecuteStateHandler(String param) {
        List<String> stateList = new ArrayList<>();
        // 获取当前巡检计划状态为  12 未到开始时间,不可执行的数据  8 计划已暂停
        stateList.add(PlanStateEnum.PLAN_STATE_UNENFORCEABLE.getCode());
        stateList.add(PlanStateEnum.PLAN_STATE_PROJECT_SUSPENDED.getCode());
        List<Plan> planList = planService.list(new QueryWrapper<Plan>().lambda().in(Plan::getPlanState, stateList));
        LocalDateTime now = LocalDateTime.now();
        List<Plan> updatePlanList = new ArrayList<>();
        planList.forEach(info ->{
            // 判断当前计划 是否在今日执行范围时间 若是则修改状态为 2未开始
            Date planBegindate = info.getPlanBegindate();
            Date planEnddate = info.getPlanEnddate();
            if(now.isAfter(DateTimeUtil.fromLong2LocalDateTime(planBegindate.getTime())) && now.isBefore(DateTimeUtil.fromLong2LocalDateTime(planEnddate.getTime()))){
                info.setPlanState(PlanStateEnum.PLAN_STATE_NOT_START.getCode());
                updatePlanList.add(info);
            }
        });
        if(updatePlanList.size()>0){
            planService.updateBatchById(planList);
        }
    }

}
