package com.tofly.gpsboot.handler.plan;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tofly.api.UserTaskClient;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.gpsboot.common.system.IsPlanChildStateEnum;
import com.tofly.gpsboot.common.system.MessageTopicEnum;
import com.tofly.gpsboot.common.system.PlanStateEnum;
import com.tofly.gpsboot.common.system.UserTaskStateEnumEnum;
import com.tofly.gpsboot.service.car.CarBaseinfoService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.paln.PlanchildtypeService;
import com.tofly.gpsboot.service.paln.PlantypeService;
import com.tofly.gpsboot.service.paln.TfYwpnPlanCartouserService;
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.car.CarBaseinfo;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Planchild;
import com.tofly.pojo.plan.Plantype;
import com.tofly.pojo.plan.TfYwpnPlanCartouser;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import jdk.nashorn.internal.ir.ContinueNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

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

    @Autowired
    private PlanService planService;
    @Autowired
    private PlanchildService planchildService;
    @Autowired
    private PlantypeService plantypeService;
    @Autowired
    private UserTaskClient userTaskClient;
    @Autowired
    private TfYwpnPlanCartouserService planCartouserService;
    @Autowired
    private CarBaseinfoService carBaseinfoService;

    @Transactional(rollbackFor = Exception.class)
    public void 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();
        List<Long> planchildIds = new ArrayList<>();
        List<TfYwpnPlanCartouser> cartouserList = new ArrayList<>();
        List<CarBaseinfo> updateCarIdList = new ArrayList<>();
        planList.forEach(info -> {
            LocalDateTime dateTime = DateTimeUtil.fromLong2LocalDateTime(info.getPlanEnddate().getTime());
            if (!now.isBefore(dateTime)) {
                // 判断当前计划对应的类型计划是否达到对应的计划完成率
                List<Plantype> plantypes = plantypeService.list(new QueryWrapper<Plantype>().lambda().eq(Plantype::getPlanId, info.getId()));
                if (null != plantypes && plantypes.size() > 0) {
                    int size = plantypes.size();
                    AtomicInteger overNum = new AtomicInteger();
                    // 计算完成个数
                    plantypes.forEach(planType -> {
                        float completionRate = planType.getCompletionRate()==null?0:planType.getCompletionRate();
                        float percent = planType.getPercentRate()==null?0:planType.getPercentRate();
                        if (completionRate <= percent) {
                            overNum.set(overNum.get() + 1);
                        }
                    });
                    // 完成率达标
                    if (size == overNum.get()) {
                        // 待办事项处理
                        Usertask usertask = new Usertask();
                        usertask.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
                        usertask.setTableId(info.getId());
                        List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                        // 待办置为已完成
                        if (null != result && result.size() > 0) {
                            result.forEach(task -> {
                                task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                                task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                                userTaskClient.updateById(task);
                            });
                        }
                        info.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode());
                        planchildIds.add(info.getId());
                        List<TfYwpnPlanCartouser> planCartouserList = planCartouserService.list(new QueryWrapper<TfYwpnPlanCartouser>().lambda()
                                .eq(TfYwpnPlanCartouser::getPlanId,info.getId()));
                        if(planCartouserList != null) {
                            String endDate;
                            for (TfYwpnPlanCartouser planCartouser : planCartouserList) {
                                endDate = planCartouser.getEndDate();
                                String nowDate = DateUtil.getDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
                                if (StringUtils.isNotBlank(endDate)) {
                                    planCartouser.setEndDate(endDate + "," + nowDate);
                                } else {
                                    planCartouser.setEndDate(nowDate);
                                }
                                cartouserList.add(planCartouser);
                                CarBaseinfo carBaseinfo = new CarBaseinfo();
                                carBaseinfo.setId(planCartouser.getCarId());
                                carBaseinfo.setIsBind("0");
                                updateCarIdList.add(carBaseinfo);
                            }
                        }
                    } else {
                        info.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_UNFINISHED.getCode());
                    }
                } else {
                    info.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_UNFINISHED.getCode());
                }
            }
        });
        planService.updateBatchById(planList);
        planchildService.update(new UpdateWrapper<Planchild>().lambda()
                .in(CollUtil.isNotEmpty(planchildIds), Planchild::getPlanId, planchildIds)
                .set(Planchild::getPlanState, IsPlanChildStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
        planCartouserService.updateBatchById(cartouserList);
        carBaseinfoService.updateBatchById(updateCarIdList);
    }

}
