package xiaoqu.home.open.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.biz.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import xiaoqu.home.open.entity.TaskCommandInfo;
import xiaoqu.home.open.entity.TaskPlanEntity;
import xiaoqu.home.open.model.db1.*;
import xiaoqu.home.open.model.db2.*;
import xiaoqu.home.open.publicBean.MessageNotification;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.*;
import xiaoqu.home.open.service.db2.*;
import xiaoqu.home.open.utils.DateToConverter;
import xiaoqu.home.open.utils.WrapperUtils;

import java.lang.Object;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j(topic = "task")
public class TaskCreateQueue {

    @Autowired
    private RedisService4 redisService4;

    @Autowired
    private RedisService5 redisService5;
    @Autowired
    private TaskStatusLogService taskStatusLogService;
    @Autowired
    private HolidayService holidayService;
    @Autowired
    private WageService wageService;
    @Autowired
    private HardwareService hardwareService;
    @Autowired
    private PlanService planService;
    @Autowired
    private UserService userService;
    @Autowired
    private PlanScenesService planScenesService;
    @Autowired
    private TaskScenesService taskScenesService;
    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private TaskTypeService taskTypeService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private PlanUserService planUserService;
    @Autowired
    private ToiletService toiletService;
    @Autowired
    private PositionsService positionsService;
    @Autowired
    private TaskDistrictParamService taskDistrictParamService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private ToiletAirqualityService toiletAirqualityService;

    /*************
     * 1 设备维护类任务生成
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskCommandHandle() {
        String taskCommandJson = redisService5.rightPop("taskCommand");
        while (taskCommandJson != null) {
            TaskCommandInfo taskCommandInfo = JSONObject.parseObject(taskCommandJson, new TypeReference<TaskCommandInfo>() {
            });
            log.info("【taskCommandHandle】" + taskCommandJson);

            //站点的设备维护类任务开关
            String devTaskFlag = redisService4.get("DevTaskFlag:" + taskCommandInfo.getDistrictId());

            TaskType taskType = taskTypeService.getById(taskCommandInfo.getTaskTypeId());


            if (taskType == null) {
                log.info("【taskCommandHandle】error:" + taskCommandJson);
                taskCommandJson = redisService5.rightPop("taskCommand");
                continue;
            } else {


            }

            boolean devOpsFlag = redisService5.isMember("OperateAssignmentTypes", taskCommandInfo.getTaskTypeId().toString());

            //20221012 虚拟设备
            {
                String virtualHardwareSncode = redisService5.get("VirtualHardware:" + taskCommandInfo.getSnCode());
                if (virtualHardwareSncode != null && !virtualHardwareSncode.trim().equals("")) {
                    taskCommandInfo.setSnCode(virtualHardwareSncode);
                }
            }
            Hardware hardware;
            if (taskCommandInfo.getTaskTypeId() == 23 || taskCommandInfo.getTaskTypeId() == 31 || taskCommandInfo.getTaskTypeId() == 32) {
                ToiletAirquality toiletAirqualityBySnCode = getToiletAirqualityBySnCode(taskCommandInfo.getSnCode());
                hardware= new Hardware();
                hardware.setAgentId(toiletAirqualityBySnCode.getAgentId());
                hardware.setToiletId(toiletAirqualityBySnCode.getToiletId());
                hardware.setPositionId(toiletAirqualityBySnCode.getPositionId());
                hardware.setPropertyId(toiletAirqualityBySnCode.getPropertyId());
                hardware.setDistrictId(toiletAirqualityBySnCode.getDistrictId());
                hardware.setSnCode(toiletAirqualityBySnCode.getAirmac());
            }else{
                hardware = getHardwareBySnCode(taskCommandInfo.getSnCode());

            }

            if (devOpsFlag) {
                QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
                wrapper.lt("status", 5);
                wrapper.eq("sn_code", taskCommandInfo.getSnCode());
                wrapper.eq("type_id", taskCommandInfo.getTaskTypeId());
                int count = taskInfoService.count(wrapper);
                if (count > 0) {
                    log.info("【taskCommandHandle】任务已存在:" + taskCommandJson + taskType.getName());
                    taskCommandJson = redisService5.rightPop("taskCommand");
                    continue;
                }
            }


            //区分任务类型
            //获取计划

            Plan plan = null;
            String workingTiming = "40";
            TaskScenes taskScenes = null;
            if (hardware != null) {
                TaskInfo taskInfo = new TaskInfo();

                if (hardware.getPositionId() != null && hardware.getPositionId() > 0) {
                    log.info("【taskCommandHandle】positions:" + hardware.getPositionId());

                    Positions positions = positionsService.getById(hardware.getPositionId());
                    StringBuffer stringBuilder = new StringBuffer();
                    stringBuilder.append(positions.getSuperiorGridName()).append(positions.getSuperiorScenesName()).append(positions.getName());
                    String taskPosition = stringBuilder.toString().replace("->", "");
                    taskInfo.setTaskPosition(taskPosition);

                    String scene2Flag = redisService4.get("Disable:p:" + hardware.getPositionId() + ":" + taskCommandInfo.getTaskTypeId());
                    if (scene2Flag != null && scene2Flag.equals("1")) {
                        if (taskCommandInfo.getTaskTypeId() == 8 || taskCommandInfo.getTaskTypeId() == 9) {
                            redisService4.lPush("RebuildTask:p:" + hardware.getPositionId() + ":" + taskCommandInfo.getTaskTypeId(), taskCommandJson);
                        }
                        taskCommandJson = redisService5.rightPop("taskCommand");
                        continue;
                    } else {
                        QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
                        pswrapper.eq("scenes_level", 2);
                        pswrapper.eq("scenes_id", hardware.getPositionId());
                        pswrapper.eq("task_type_id", taskType.getId());
//                        pswrapper.eq("is_cross", 1);
                        List<PlanScenes> list = planScenesService.list(pswrapper);
                        if (!list.isEmpty()) {
                            PlanScenes planScenes = list.get(0);
                            plan = planService.getById(planScenes.getPlanId());
                            log.info("【taskCommandHandle】positions:plan" + plan.getId());
                            workingTiming = redisService4.get("workingTimeing:p:" + planScenes.getScenesId() + ":" + planScenes.getTaskTypeId());
                            taskScenes = new TaskScenes();
                            BeanUtils.copyProperties(planScenes, taskScenes);
                            taskScenes.setId(null);
                        } else {
                            taskScenes = new TaskScenes();
                            taskScenes.setAgentId(positions.getAgentId());
                            taskScenes.setAgentName(positions.getAgentName());
                            taskScenes.setPropertyId(positions.getPropertyId());
                            taskScenes.setPropertyName(positions.getPropertyName());
                            taskScenes.setDistrictId(positions.getDistrictId());
                            taskScenes.setDistrictName(positions.getDistrictName());
                            taskScenes.setBuildingId(positions.getBuildingId());
                            taskScenes.setBuildingName(positions.getBuildingName());
                            taskScenes.setFloor(positions.getFloor());
                            taskScenes.setFloorId(positions.getFloorId());
                            taskScenes.setScenesId(positions.getId());
                            taskScenes.setScenesLevel(2);
                            taskScenes.setStatus(0);
                            taskScenes.setName(positions.getName());
                            taskScenes.setSuperiorGridName(positions.getSuperiorGridName());
                            taskScenes.setGridLevel(positions.getGridLevel());
                        }
                        //221115,app任务查询专用
                        taskScenes.setToiletId(positions.getToiletId());

                    }

                }


                if (hardware.getToiletId() != null && hardware.getToiletId() > 0 && plan == null) {
                    log.info("【taskCommandHandle】toilet:" + hardware.getToiletId());

                    Toilet toilet = toiletService.getById(hardware.getToiletId());
                    StringBuffer stringBuilder = new StringBuffer();
                    stringBuilder.append(toilet.getSuperiorGridName()).append(toilet.getName());
                    String taskPosition = stringBuilder.toString().replace("->", "");
                    if (taskInfo.getTaskPosition() == null) {
                        //有底层无上层
                        taskInfo.setTaskPosition(taskPosition);
                    }
                    String scene1Flag = redisService4.get("Disable:t:" + hardware.getToiletId() + ":" + taskCommandInfo.getTaskTypeId());
                    if (scene1Flag != null && scene1Flag.equals("1")) {
                        redisService4.lPush("RebuildTask:t:" + hardware.getToiletId() + ":" + taskCommandInfo.getTaskTypeId(), taskCommandJson);
                        taskCommandJson = redisService5.rightPop("taskCommand");

                        continue;
                    } else {

                        QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
                        pswrapper.eq("scenes_level", 1);
                        pswrapper.eq("scenes_id", hardware.getToiletId());
                        pswrapper.eq("task_type_id", taskType.getId());
//                        pswrapper.eq("is_cross", 1);

                        List<PlanScenes> list = planScenesService.list(pswrapper);
                        if (!list.isEmpty()) {
                            PlanScenes planScenes = list.get(0);
                            plan = planService.getById(planScenes.getPlanId());
                            log.info("【taskCommandHandle】toilet:plan" + plan.getId());
                            workingTiming = redisService4.get("workingTimeing:t:" + planScenes.getScenesId() + ":" + planScenes.getTaskTypeId());
                            taskScenes = new TaskScenes();
                            BeanUtils.copyProperties(planScenes, taskScenes);
                            taskScenes.setId(null);
                        } else {
                            if(taskScenes==null){
                                taskScenes = new TaskScenes();
                                taskScenes.setAgentId(toilet.getAgentId());
                                taskScenes.setAgentName(toilet.getAgentName());
                                taskScenes.setPropertyId(toilet.getPropertyId());
                                taskScenes.setPropertyName(toilet.getPropertyName());
                                taskScenes.setDistrictId(toilet.getDistrictId());
                                taskScenes.setDistrictName(toilet.getDistrictName());
                                taskScenes.setBuildingId(toilet.getBuildingId());
                                taskScenes.setBuildingName(toilet.getBuildingName());
                                taskScenes.setFloor(toilet.getFloor());
                                taskScenes.setFloorId(toilet.getFloorId());
                                taskScenes.setScenesId(toilet.getId());
                                taskScenes.setScenesLevel(1);
                                taskScenes.setStatus(0);
                                taskScenes.setName(toilet.getName());
                                taskScenes.setSuperiorGridName(toilet.getSuperiorGridName());
                                taskScenes.setGridLevel(toilet.getGridLevel());
                            }

                        }
                        taskScenes.setToiletId(toilet.getId());

                    }
                }


                String districtFlag = redisService4.get("Disable:d:" + hardware.getDistrictId() + ":" + taskCommandInfo.getTaskTypeId());
                if (plan == null) {
                    log.info("【taskCommandHandle】district:" + districtFlag);
                    //20221017


                    if (districtFlag != null && districtFlag.equals("1")) {
                        log.info("【taskCommandHandle】禁用不生成任务district:" + hardware.getDistrictId() + taskCommandJson);
                        redisService4.lPush("RebuildTask:d:" + hardware.getDistrictId() + ":" + taskCommandInfo.getTaskTypeId(), taskCommandJson);
                        taskCommandJson = redisService5.rightPop("taskCommand");

                        continue;
                    } else {
                        QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
                        wrapper.eq("type", 1);
                        wrapper.eq("task_type_id", taskType.getId());
                        wrapper.eq("district_id", hardware.getDistrictId());
                        wrapper.eq("is_cross", 0);

                        List<Plan> planlist = planService.list(wrapper);
                        if (!planlist.isEmpty()) {
                            plan = planlist.get(0);
                            log.info("【taskCommandHandle】district:plan" + plan.getId());

                            workingTiming = redisService4.get("workingTimeing:d:" + hardware.getDistrictId() + ":" + taskType.getId());
                        }
                    }
                    if(plan==null){
                        if ((taskType.getTaskFlag() != null && taskType.getTaskFlag() == 0) || (devTaskFlag != null && devTaskFlag.equals("0"))) {
                            if (taskType.getNoticeFlag() != null && taskType.getNoticeFlag() == 1) {
                                //通知
                                MessageNotification taskPushInfo = new MessageNotification();
                                taskPushInfo.setTaskId(hardware.getToiletId());
                                taskPushInfo.setStatus(-1);
                                taskPushInfo.setTaskName(taskType.getName());
                                taskPushInfo.setDistrictId(taskCommandInfo.getDistrictId());
                                redisService4.lPush("taskPushQueue", JSONObject.toJSONString(taskPushInfo));
                                setTaskStatusLogByNotice(new Date(), hardware, -2, "任务类型不生成任务仅通知,"+hardware.getSnCode()+",taskTypeId"+taskCommandInfo.getTaskTypeId(),null);

//                                log.info("【taskCommandHandle】任务类型不生成任务仅通知：" + taskCommandInfo.getDistrictId());

                            }
//                            log.info("【taskCommandHandle】任务类型不生成任务，站点id：" + taskCommandInfo.getDistrictId());
                            taskCommandJson = redisService5.rightPop("taskCommand");
                            continue;
                        }
                    }else{
                        if ((plan.getTaskFlag() != null && plan.getTaskFlag() == 0) || (devTaskFlag != null && devTaskFlag.equals("0"))) {
                            if (plan.getNoticeFlag() != null && plan.getNoticeFlag() == 1) {
                                //通知
                                MessageNotification taskPushInfo = new MessageNotification();
                                taskPushInfo.setTaskId(hardware.getToiletId());
                                taskPushInfo.setStatus(-1);
                                taskPushInfo.setTaskName(taskType.getName());
                                taskPushInfo.setDistrictId(taskCommandInfo.getDistrictId());
                                redisService4.lPush("taskPushQueue", JSONObject.toJSONString(taskPushInfo));
                                setTaskStatusLogByNotice(new Date(), hardware, -2, "站点计划存在，不生成任务仅通知,"+hardware.getSnCode()+",taskTypeId"+taskCommandInfo.getTaskTypeId(),null);

//                                log.info("【taskCommandHandle】站点计划存在，不生成任务仅通知：" + taskCommandInfo.getDistrictId());

                            }
//                            log.info("【taskCommandHandle】站点计划存在不生成任务，站点id：" + plan.getId());
                            taskCommandJson = redisService5.rightPop("taskCommand");
                            continue;
                        }
                    }


                } else {

                    if ((plan.getTaskFlag() != null && plan.getTaskFlag() == 0) || (devTaskFlag != null && devTaskFlag.equals("0"))) {
                        if (plan.getNoticeFlag() != null && plan.getNoticeFlag() == 1) {
                            //通知
                            MessageNotification taskPushInfo = new MessageNotification();
                            taskPushInfo.setTaskId(hardware.getToiletId());
                            taskPushInfo.setStatus(-1);
                            taskPushInfo.setTaskName(taskType.getName());
                            taskPushInfo.setDistrictId(taskCommandInfo.getDistrictId());
                            redisService4.lPush("taskPushQueue", JSONObject.toJSONString(taskPushInfo));
                            setTaskStatusLogByNotice(new Date(), hardware, -2, "场景计划存在，不生成任务仅通知,"+hardware.getSnCode()+",taskTypeId"+taskCommandInfo.getTaskTypeId(),null);

//                            log.info("【taskCommandHandle】场景计划存在，不生成任务仅通知：" + taskCommandInfo.getDistrictId());

                        }
//                        log.info("【taskCommandHandle】场景计划存在不生成任务，站点id：" + plan.getId());
                        taskCommandJson = redisService5.rightPop("taskCommand");
                        continue;
                    }

                }
                taskInfo.setAgentId(hardware.getAgentId());
                taskInfo.setPropertyId(hardware.getPropertyId());
                taskInfo.setDistrictId(hardware.getDistrictId());

                String agentName = redisService5.get("name:Agent:" + hardware.getAgentId());
                taskInfo.setAgentName(agentName != null ? agentName : "");
                String propertyname = redisService5.get("name:Properyt:" + hardware.getPropertyId());
                taskInfo.setPropertyName(propertyname != null ? propertyname : "");
                String districtName = redisService5.get("name:District:" + hardware.getDistrictId());
                taskInfo.setDistrictName(districtName != null ? districtName : "");


                taskInfo.setSnCode(taskCommandInfo.getSnCode());
                taskInfo.setName(taskType.getName());
                taskInfo.setNo(String.format("%06d", getDistrictTaskNo(hardware.getDistrictId())));
                taskInfo.setStandard(taskType.getTriggerDesc());
                taskInfo.setContent(taskType.getDetails());
                taskInfo.setTaskType(1);
                taskInfo.setTaskCreateType(2);
                taskInfo.setTypeId(taskType.getId());
                taskInfo.setStatus(0);
                taskInfo.setCreateTime(new Date());
                taskInfo.setPeriodOfValidityBeginTime(new Date());
                taskInfo.setExecutionPhaseBeginTime(new Date());
                taskInfo.setUserStatus(0);

                taskInfo.setPoolOrder(taskType.getPoolOrder());
                taskInfo.setGroupOrder(taskType.getGroupOrder());
                if(plan!=null){
                    taskInfo.setTaskOrder(plan.getTaskOrder());
                }else{
                    taskInfo.setTaskOrder(taskType.getTaskOrder());
                }
                //时薪
                {
                    if (plan != null) {
                        taskInfo.setWageHour(plan.getWageHour());
                        Wage wage = wageService.getById(plan.getWageId());
                        if (wage != null) {
                            taskInfo.setWageId(plan.getWageId());
                            taskInfo.setSalary(plan.getWageHour() * wage.getAmount());
                            taskInfo.setPoint(plan.getWageHour() * wage.getPoint());
                            taskInfo.setWageName(wage.getName());
                        }
                    }
                }


                //计划获取

                if (workingTiming != null) {
                    try {
                        taskInfo.setTiming(Integer.parseInt(workingTiming));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        taskInfo.setTiming(40);
                    }
                }
                log.info("【taskCommandHandle】plan:" + JSONObject.toJSONString(plan));
                if (plan != null) {
                    taskInfo.setUserType(plan.getUserType());
                    taskInfo.setExpireType(plan.getExpireType());
                    taskInfo.setPlanId(plan.getId());
                    taskInfo.setClockFlag(plan.getClockFlag());
                } else {
                    taskInfo.setUserType(0);
                    taskInfo.setExpireType(taskType.getExpireType());
                    taskInfo.setClockFlag(0);

                }

                taskInfo.setUploadManageUser("");
                taskInfoService.save(taskInfo);
                if (taskScenes != null) {
                    taskScenes.setTaskId(taskInfo.getId());
                    taskScenes.setModifyTime(null);
                    taskScenes.setModifyId(null);
                    taskScenes.setModifyName(null);
                    if(plan!=null){
                        taskScenes.setPlanId(plan.getId());
                    }
                    taskScenesService.save(taskScenes);
                }
                TaskPlanEntity taskPlanEntity = new TaskPlanEntity();
                taskPlanEntity.setTaskInfo(taskInfo);
                taskPlanEntity.setPlan(plan);
                redisService4.lPush("taskUserQueue", JSONObject.toJSONString(taskPlanEntity));
            }
            taskCommandJson = redisService5.rightPop("taskCommand");
        }
    }


//    /**
//     * 执行人员通用-推送任务
//     */
//    @Scheduled(cron = "* * * * * ?")
//    public void taskUserCreate() {
//        String taskCommandId = redisService4.rightPop("taskUserQueue");
//        while (taskCommandId != null) {
//            Date date = new Date();
//            TaskInfo taskInfo = taskInfoService.getById(taskCommandId);
////            taskInfo.setStatus(2);
////            taskInfo.setSendTime(date);
//
//            if (taskInfo != null) {
//                //不限人员
//                if (taskInfo.getUserType() == 0) {
//                    createTaskUser(date, taskInfo, null);
//                    //根据计划生成
//                } else {
//                    QueryWrapper<PlanUser> wrapper = WrapperUtils.getWrapper(false);
//                    wrapper.eq("district_id", taskInfo.getDistrictId());
//                    wrapper.eq("plan_id", taskInfo.getPlanId());
//                    List<PlanUser> list = planUserService.list(wrapper);
//                    if (!list.isEmpty()) {
//                        StringBuffer stringBuffer = new StringBuffer();
//                        for (PlanUser planUser : list) {
//                            createTaskUser(date, taskInfo, planUser);
//                            stringBuffer.append(planUser.getName()).append(",");
//                        }
//                        taskInfo.setTaskDistributiUser(stringBuffer.substring(0, stringBuffer.length() - 1));
//                    }
//
//                }
//            } else {
//                log.info("【taskUserCreate】taskId:" + taskCommandId);
//                taskCommandId = redisService4.rightPop("taskUserQueue");
//                continue;
//            }
//
//            //跳过已派单，直接进入待抢单
//            taskInfoService.updateById(taskInfo);
//            MessageNotification taskPushInfo = new MessageNotification();
//            taskPushInfo.setTaskId(taskInfo.getId());
//            taskPushInfo.setStatus(taskInfo.getStatus());
//            taskPushInfo.setTaskName(taskInfo.getName());
//            taskPushInfo.setDistrictId(taskInfo.getDistrictId());
//            redisService4.lPush("taskPushQueue", JSONObject.toJSONString(taskPushInfo));
//
//            taskCommandId = redisService4.rightPop("taskUserQueue");
//
//        }
//    }

    /**
     * 任务生成
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskCreateHandle() {
        String planId = redisService4.rightPop("PlanTaskQueue");
        while (planId != null) {
            Plan plan = planService.getById(planId);

            //
            String dateString = DateToConverter.getFormattedDate(new Date(), 0);
            QueryWrapper<Holiday> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("holiday_date", dateString);
            List<Holiday> holidaylist = holidayService.list(wrapper);
            if (!holidaylist.isEmpty()) {
                Holiday holiday = holidaylist.get(0);
                //跳过节假日
                if (plan.getEliminateType() == 1) {
                    if (holiday.getType() == 1 || holiday.getType() == 2) {
                        log.info("【taskCreateHandle】跳过节假日planid：" + planId);
                         planId = redisService4.rightPop("PlanTaskQueue");
                    }
                    //跳过工作日
                } else if (plan.getEliminateType() == 2) {
                    if (holiday.getType() == 0 || holiday.getType() == 3) {
                        log.info("【taskCreateHandle】跳过工作日planid：" + planId);
                        planId = redisService4.rightPop("PlanTaskQueue");
                    }
                }
            }


            if (plan == null) {
                log.info("【taskCreateHandle】planId：" + planId + "未找到");
                planId = redisService4.rightPop("PlanTaskQueue");
                continue;
            }
            Date date = new Date();
            if (plan.getEndTime() != null && date.getTime() > plan.getEndTime().getTime()) {
                if (plan.getActionTimeType() == 1) {
                    log.info("【taskCreateHandle】计划结束id：" + planId);
                    plan.setStatus(2);
                    plan.setModifyTime(date);
                    planService.updateById(plan);
                }
            }
            if(plan.getType()==0&&plan.getCircleStatus()==0){
                log.info("【taskCreateHandle】计划结束id：" + planId);
                plan.setStatus(2);
                plan.setModifyTime(date);
                planService.updateById(plan);
            }

            //非启用计划
//            if (plan.getStatus() != 0) {
            // 人次校验的计划结束
            if (plan.getTaskCreateType() == 1) {
                QueryWrapper<PlanScenes> planscenesWrapper = WrapperUtils.getWrapper(false);
                planscenesWrapper.eq("plan_id", plan.getId());
                List<PlanScenes> planSceneslist = planScenesService.list(planscenesWrapper);
                for (PlanScenes planScenes : planSceneslist) {
                    log.info("【taskCreateHandle】人次任务到期清除计次标记:" + planScenes.getScenesId() + ":" + planScenes.getScenesLevel());
                    if (planScenes.getScenesLevel() == 1) {
//                        redisService4.remove("UserCount:t:" + planScenes.getScenesId() + ":" + planId);
                    } else {
//                        redisService4.remove("UserCount:p:" + planScenes.getScenesId() + ":" + planId);
                    }
                }
            }
//                log.info("【taskCreateHandle】planId：" + planId + "当前计划非启用" + plan.getStatus());
//                planId = redisService4.rightPop("PlanTaskQueue");
//                continue;
//            }


            TaskInfo taskInfo = new TaskInfo();


            //基础信息
            {
                taskInfo.setAgentId(plan.getAgentId());
                taskInfo.setAgentName(plan.getAgentName());
                taskInfo.setPropertyId(plan.getPropertyId());
                taskInfo.setPropertyName(plan.getPropertyName());
                taskInfo.setDistrictId(plan.getDistrictId());
                taskInfo.setDistrictName(plan.getDistrictName());
                taskInfo.setName(plan.getTaskName());
                taskInfo.setStandard(plan.getTaskStandard());
                taskInfo.setContent(plan.getTaskContent());
                taskInfo.setTaskRequire(plan.getTaskRequire());
                taskInfo.setTaskType(plan.getType());
                taskInfo.setTaskCreateType(plan.getTaskCreateType());
                taskInfo.setTypeId(plan.getTaskTypeId());
                taskInfo.setCreateTime(date);
                taskInfo.setPeriodOfValidityBeginTime(new Date());
                taskInfo.setExecutionPhaseBeginTime(new Date());
                taskInfo.setPlanId(plan.getId());
                taskInfo.setNo(String.format("%06d", getDistrictTaskNo(plan.getDistrictId())));
                taskInfo.setStatus(0);
                taskInfo.setCreateName(plan.getCreateName());
                taskInfo.setCreateId(plan.getCreateId());
                taskInfo.setStartTime(plan.getStartTime());
                taskInfo.setEndTime(plan.getEndTime());
            }
            //时薪
            {
                if (plan != null) {
                    taskInfo.setWageHour(plan.getWageHour());
                    Wage wage = wageService.getById(plan.getWageId());
                    if (wage != null) {
                        taskInfo.setWageId(plan.getWageId());
                        taskInfo.setSalary(plan.getWageHour() * wage.getAmount());
                        taskInfo.setPoint(plan.getWageHour() * wage.getPoint());
                        taskInfo.setWageName(wage.getName());

                    } else {
                        taskInfo.setWageId(0L);
                        taskInfo.setSalary(0.0);
                        taskInfo.setPoint(0.0);
                    }
                }
            }
            //type区分
            {
                //指派任务
                if (plan.getType() == 2) {
//                    if(plan.getActionTimeType()==0){
//
//                    }
                    //要求完成时间
                    if (plan.getEndTime() != null) {
                        taskInfo.setPreFinishTime(plan.getEndTime());
                        taskInfo.setExpireType(2);
                        taskInfo.setExpireTime(plan.getEndTime());
                        taskInfo.setPeriodOfValidityEndTime(plan.getEndTime());
                    } else {
                        taskInfo.setPreFinishTime(null);
                        taskInfo.setExpireType(0);

                    }
                    taskInfo.setUserType(plan.getUserType());

                    if (plan.getUserType() == 0) {
                        taskInfo.setUserStatus(0);
                    } else {
                        taskInfo.setUserStatus(plan.getUserStatus());
                    }
                    taskInfo.setExpireType(0);
                    taskInfo.setTaskCreateType(0);

                    taskInfo.setPoolOrder(1);
                    taskInfo.setGroupOrder(1);
                    taskInfo.setTaskOrder(plan.getTaskOrder());
                    if (plan.getStatus() == 0) {
                        plan.setStatus(2);
                        plan.setModifyTime(date);
                        planService.updateById(plan);

                    }

                } else if (plan.getType() == 0) {
                    taskInfo.setUserStatus(plan.getUserStatus());
                    taskInfo.setUserType(plan.getUserType());
                    taskInfo.setTaskCreateType(plan.getTaskCreateType());
                    taskInfo.setExpireType(plan.getExpireType());
                    if (plan.getExpireType() == 1) {
                        taskInfo.setExpireTime(DateToConverter.getEndTime());
                        taskInfo.setPeriodOfValidityEndTime(DateToConverter.getEndTime());
                    } else if (plan.getExpireType() == 2) {
                        if (plan.getExpireTiming() != null && plan.getExpireTiming() > 0) {
                            Date endTime = DateToConverter.getEndTime();
                            Integer expireTiming = plan.getExpireTiming();
                            if (expireTiming == 1) {
                                if(plan.getActionStartTime()!=null&&!plan.getActionStartTime().trim().equals("")&&plan.getActionEndTime()!=null&&!plan.getActionEndTime().trim().equals("")){
                                    String aftertime = DateToConverter.compareHourMinter(plan.getActionStartTime(), plan.getActionEndTime());
                                    //跨天
                                    if(plan.getActionStartTime().equals(aftertime)){
                                        String dateAddOrSub = DateToConverter.getDateAddOrSub(5, expireTiming, endTime);
                                        Date expireDate = DateToConverter.parseDate(dateAddOrSub, 5);
                                        taskInfo.setExpireTime(expireDate);
                                        taskInfo.setPeriodOfValidityEndTime(expireDate);
                                        //不跨天
                                    }else{
                                        taskInfo.setExpireTime(endTime);
                                        taskInfo.setPeriodOfValidityEndTime(endTime);
                                    }
                                }else{
                                    taskInfo.setExpireTime(endTime);
                                    taskInfo.setPeriodOfValidityEndTime(endTime);
                                }


                            } else {
                                String dateAddOrSub = DateToConverter.getDateAddOrSub(5, expireTiming - 1, endTime);
                                Date expireDate = DateToConverter.parseDate(dateAddOrSub, 5);
                                taskInfo.setExpireTime(expireDate);
                                taskInfo.setPeriodOfValidityEndTime(expireDate);
                            }
                        }
                    }

                    if (plan.getActionEndTime() != null && !plan.getActionEndTime().trim().equals("")) {
//                        String actionEndTime = plan.getActionEndTime();
//                        String formattedDate = DateToConverter.getFormattedDate(date, 0);
//                        taskInfo.setPreFinishTime(DateToConverter.parseDate(formattedDate + " " + plan.getActionEndTime() + ":00", 5));
                        setPreFinishTimeByActionEnd(plan, date, taskInfo);

                    }
                    taskInfo.setPoolOrder(3);
                    taskInfo.setGroupOrder(1);
                    taskInfo.setTaskOrder(plan.getTaskOrder());
                    //巡检计划
                } else if (plan.getType() == 5) {
                    //单次巡检，任务结束时间为结束日期的结束书剑
                    if (plan.getCircleStatus() == 0) {
                        if (plan.getStartStatus() == 0) {
                            setPreFinishTimeByActionEnd(plan, date, taskInfo);
                        } else {
                            Date endTime = plan.getEndTime();
                            String endDate = DateToConverter.getFormattedDate(endTime, 0);
                            taskInfo.setPreFinishTime(DateToConverter.parseDate(endDate + " " + plan.getActionEndTime() + ":00", 5));
                        }

                    } else {
                        //循环任务，结束时间小于开始时间的 次日结束
                        setPreFinishTimeByActionEnd(plan, date, taskInfo);
                    }

                    taskInfo.setUserStatus(plan.getUserStatus());
                    taskInfo.setPoolOrder(2);
                    taskInfo.setGroupOrder(1);
                    taskInfo.setTaskOrder(plan.getTaskOrder());
                }
            }
            taskInfo.setUploadManageUser("");
            taskInfoService.save(taskInfo);


            //场景生成
            {
                QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
                pswrapper.eq("plan_id", planId);
                List<PlanScenes> planSceneslist = planScenesService.list(pswrapper);
                List<TaskScenes> addTaskSceneslist = new ArrayList<TaskScenes>();
                StringBuffer stringBuilder = new StringBuffer();

                for (PlanScenes planScenes : planSceneslist) {
                    TaskScenes taskScenes = new TaskScenes();
                    BeanUtils.copyProperties(planScenes, taskScenes, "modify_time", "modify_id", "modify_name");
                    taskScenes.setId(null);
                    taskScenes.setCreateTime(date);
                    taskScenes.setTaskId(taskInfo.getId());
                    taskScenes.setStatus(0);
                    taskScenes.setModifyTime(null);
                    taskScenes.setModifyId(null);
                    taskScenes.setModifyName(null);

                    if(taskScenes.getScenesLevel()==1){
                        taskScenes.setToiletId(taskScenes.getScenesId());
                    }else if(taskScenes.getScenesLevel()==2){
                        Positions positions = positionsService.getById(taskScenes.getScenesId());
                        if(positions!=null&&positions.getToiletId()!=null){
                            taskScenes.setToiletId(positions.getToiletId());
                        }

                    }
                    addTaskSceneslist.add(taskScenes);
                    if (planScenes.getScenesId() == 0) {
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(",");
                    } else {
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(planScenes.getName()).append(",");
                    }
                    //展会特殊处理
                    if(taskInfo.getName().contains("消毒任务")){
                        redisService5.set("disinfect:p:" + taskScenes.getScenesId(),"0");
                    }
                }
                taskScenesService.saveBatch(addTaskSceneslist);
                if (stringBuilder.length() > 0) {
                    String taskPosition = stringBuilder.toString().substring(0, stringBuilder.length() - 1).replace("->", "");
                    taskInfo.setTaskPosition(taskPosition);
                } else {
                    taskInfo.setTaskPosition("");
                }

                if (taskInfo.getTaskType() == 5) {
                    taskInfo.setShouldInspect(planSceneslist.size());
                    taskInfo.setNotInspect(planSceneslist.size());
                }

            }
            taskInfoService.updateById(taskInfo);
            //插入任务过期Zset
            {
                if (taskInfo.getExpireTime() != null) {
                    redisService5.zAdd("TaskExprieQueue", taskInfo.getId().toString(), taskInfo.getExpireTime().getTime());
                }
            }
            //指派计划人员
            {
                TaskPlanEntity taskPlanEntity = new TaskPlanEntity();
                taskPlanEntity.setTaskInfo(taskInfo);
                taskPlanEntity.setPlan(plan);
                if (plan.getType() <= 2) {

                    redisService4.lPush("taskUserQueue", JSONObject.toJSONString(taskPlanEntity));
                } else if (plan.getType() == 5) {
                    redisService4.lPush("inspectTaskUserQueue", JSONObject.toJSONString(taskPlanEntity));
                }

            }
            planId = redisService4.rightPop("PlanTaskQueue");
            log.info("【taskCreateHandle】" + planId);
        }

    }

    private void setPreFinishTimeByActionEnd(Plan plan, Date date, TaskInfo taskInfo) {
        String aftertime = DateToConverter.compareHourMinter(plan.getActionStartTime(), plan.getActionEndTime());
        if (plan.getActionEndTime().equals(aftertime)) {
            String actionEndTime = plan.getActionEndTime();
            String formattedDate = DateToConverter.getFormattedDate(date, 0);
            taskInfo.setPreFinishTime(DateToConverter.parseDate(formattedDate + " " + plan.getActionEndTime() + ":00", 5));
        } else {

            String nextDateTime = DateToConverter.getDateAddOrSub(5, 1, date);
            String nextDate = nextDateTime.substring(0, nextDateTime.indexOf(" "));
            taskInfo.setPreFinishTime(DateToConverter.parseDate(nextDate + " " + plan.getActionEndTime() + ":00", 5));
        }
    }


    /**
     * 5
     */
    @Scheduled(cron = "59 59 23 * * ?")
    public void overdueTaskStatusTask() {
        Date date = new Date();
        QueryWrapper<TaskInfo> taskwrapper = WrapperUtils.getWrapper(false);
        taskwrapper.lt("pre_finish_time", date);
        taskwrapper.eq("task_type", 5);
        taskwrapper.in("status", 3, 4);
        List<TaskInfo> list = taskInfoService.list(taskwrapper);
        List<Long> taskIds = new ArrayList<>();
        for (TaskInfo taskInfo : list) {
            taskInfo.setModifyTime(date);
            taskInfo.setStatus(9);
            taskInfoService.updateById(taskInfo);
            setTaskStatusLog(date, taskInfo, 9, "系统过期");
            taskIds.add(taskInfo.getId());
            //计划结束
            if (taskInfo.getPlanId() > 0) {
                Plan plan = planService.getById(taskInfo.getPlanId());
                if (plan.getEndTime() != null && plan.getEndTime().getTime() < date.getTime()) {
                    plan.setStatus(2);
                    plan.setModifyName("系统过期");
                    plan.setModifyTime(date);
                    planService.updateById(plan);
                    log.info("【overdueTaskStatusTask】计划过期" + plan.getId() + "-" + plan.getTaskName());
                }
            }
        }
        UpdateWrapper<TaskUser> taskUserwrapper = WrapperUtils.getUpdateWrapper(false);

//        QueryWrapper<TaskUser> taskUserwrapper = WrapperUtils.getWrapper(false);
        taskUserwrapper.in("task_id", taskIds);
        taskUserwrapper.eq("status", 4);
        taskUserwrapper.set("status", 9);
        taskUserwrapper.set("modify_time", date);
        taskUserService.update(taskUserwrapper);
        log.info("【overdueTaskStatusTask】修改" + list.size() + "条巡检任务状态为过期");
//        taskUserwrapper.eq("task_type",5);

    }


    /*************
     * 1 设备维护类任务完成
     * 220519，贾剑王恒通知取消自动完成
     */
//    @Scheduled(cron = "* * * * * ?")
//    public void taskFinishCommandHandle() {
//        String taskCommandJson = redisService5.rightPop("taskFinishCommand");
//        while (taskCommandJson != null) {
//            TaskCommandInfo taskCommandInfo = JSONObject.parseObject(taskCommandJson, new TypeReference<TaskCommandInfo>() {
//            });
//
//            log.info("【taskFinishCommandHandle】" + taskCommandJson);
//            TaskType taskType = taskTypeService.getById(taskCommandInfo.getTaskTypeId());
//            User user = null;
//            if (taskCommandInfo.getUserId() != null) {
//                user = userService.getById(taskCommandInfo.getUserId());
//            }
//            boolean devOpsFlag = redisService5.isMember("OperateAssignmentTypes", taskCommandInfo.getTaskTypeId().toString());
//            if (devOpsFlag) {
//                QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
//                wrapper.lt("status", 5);
//                wrapper.eq("sn_code", taskCommandInfo.getSnCode());
//                wrapper.eq("type_id", taskCommandInfo.getTaskTypeId());
//                wrapper.eq("task_type", 1);
//                List<TaskInfo> list = taskInfoService.list(wrapper);
//                Date curTime = new Date();
//                if (list.isEmpty()) {
//                    log.info("【taskFinishCommandHandle】任务未找到:" + taskCommandJson);
//                    taskCommandJson = redisService5.rightPop("taskFinishCommand");
//                    continue;
//                } else {
//                    for (TaskInfo taskInfo : list) {
//                        Date createTime = taskInfo.getCreateTime();
//                        String finishTimeStr = DateToConverter.getDateAddOrSub(12, taskInfo.getTiming(), createTime);
//                        Date date = DateToConverter.parseDate(finishTimeStr, 5);
//                        if (date.getTime() > curTime.getTime()) {
//                            taskInfo.setStatus(5);
//                        } else {
//                            taskInfo.setStatus(6);
//                        }
//                        taskInfo.setFinishTime(curTime);
//                        taskInfoService.updateById(taskInfo);
//
//                        QueryWrapper<TaskUser> updateWrapper = WrapperUtils.getWrapper(false);
//                        updateWrapper.eq("task_id", taskInfo.getId());
//                        List<TaskUser> taskUserList = taskUserService.list(updateWrapper);
//                        if (taskUserList.isEmpty()) {
//                            supplementTaskUser(user, taskInfo);
//                        } else {
//                            Boolean userFlag = false;
//                            for (TaskUser taskUser : taskUserList) {
//
//                                if (taskUser.getUserId() == taskCommandInfo.getUserId() || taskUser.getUserId() == 0) {
//                                    userFlag = true;
//                                    taskUser.setStatus(taskInfo.getStatus());
//                                    taskUser.setFinishTime(curTime);
//                                    taskUser.setUserId(taskCommandInfo.getUserId());
//                                    if (user != null) {
//                                        taskUser.setUserName(user.getName());
//                                        taskUser.setMobile(user.getMobile());
//                                    }
//                                } else if (taskInfo.getUserStatus() == 0) {
//                                    taskUser.setSoftDelete(1);
//                                } else {
//                                    taskUser.setStatus(taskInfo.getStatus());
//                                    taskUser.setFinishTime(curTime);
//                                }
//                                taskUser.setModifyTime(curTime);
//                                taskUserService.updateById(taskUser);
//                            }
//                            //计划外人员完成
//                            if (!userFlag) {
//                                supplementTaskUser(user, taskInfo);
//                            }
//                        }
//                    }
//                }
//            }
//            taskCommandJson = redisService5.rightPop("taskFinishCommand");
//        }
//    }

//    private void supplementTaskUser(User curUser, TaskInfo taskInfo) {
//        TaskUser taskUser = createTaskUser(new Date(), taskInfo, null);
//        taskUser.setStatus(taskInfo.getStatus());
//        if (curUser != null) {
//            taskUser.setUserId(curUser.getId());
//            taskUser.setUserName(curUser.getName());
//            taskUser.setMobile(curUser.getMobile());
//        }
//        taskUser.setModifyTime(new Date());
//        taskUserService.updateById(taskUser);
//    }
    private Hardware getHardwareBySnCode(String snCode) {
        Hardware hardware;
        String jsonObject = redisService5.get("entity:Hardware:" + snCode);
        if (jsonObject != null) {
            hardware = JSONObject.parseObject(jsonObject, Hardware.class);
        } else {
            QueryWrapper<Hardware> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("sn_code", snCode);
            List<Hardware> list = hardwareService.list(wrapper);
            if (list.isEmpty()) {
                return null;

            } else {
                hardware = list.get(0);
            }
        }
        return hardware;
    }

    private ToiletAirquality getToiletAirqualityBySnCode(String snCode) {
        ToiletAirquality toiletAirquality;
        String jsonObject = redisService5.get("entity:ToiletAirQualityAirMac:" + snCode);
        if (jsonObject != null) {
            toiletAirquality = JSONObject.parseObject(jsonObject, ToiletAirquality.class);
        } else {
            QueryWrapper<ToiletAirquality> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("airmac", snCode);
            List<ToiletAirquality> list = toiletAirqualityService.list(wrapper);
            if (list.isEmpty()) {
                return null;

            } else {
                toiletAirquality = list.get(0);
            }
        }
        return toiletAirquality;
    }

    //
//    private TaskUser createTaskUser(Date date, TaskInfo taskInfo, PlanUser planUser) {
//        TaskUser taskUser = new TaskUser();
//        BeanUtils.copyProperties(taskInfo, taskUser);
//        taskUser.setId(null);
//        taskUser.setTaskId(taskInfo.getId());
//        if (planUser == null) {
//            taskUser.setUserId(0L);
//            taskUser.setUserName("");
//            taskUser.setMobile("");
//        } else {
//            taskUser.setUserId(planUser.getUserId());
//            taskUser.setUserName(planUser.getName());
//            taskUser.setMobile(planUser.getMobile());
//        }
//        taskUser.setStatus(taskInfo.getStatus());
//        taskUser.setSendTime(date);
//        taskUser.setName(taskInfo.getName());
//        taskUser.setNo(taskInfo.getNo());
//        taskUser.setTaskType(taskInfo.getTaskType());
//        taskUser.setExpireType(taskInfo.getExpireType());
//        taskUser.setExpireTime(taskInfo.getExpireTime());
//        taskUser.setTiming(taskInfo.getTiming());
//        taskUser.setTaskPosition(taskInfo.getTaskPosition());
//        taskUser.setDistrictId(taskInfo.getDistrictId());
//        taskUserService.save(taskUser);
//        return taskUser;
//    }
    private void setTaskStatusLog(Date date, TaskInfo taskInfo, Integer status, String content) {
        TaskStatusLog taskStatusLog = new TaskStatusLog();
        taskStatusLog.setAgentId(taskInfo.getAgentId());
        taskStatusLog.setPropertyId(taskInfo.getPropertyId());
        taskStatusLog.setDistrictId(taskInfo.getDistrictId());
        taskStatusLog.setDistrictName(taskInfo.getDistrictName());
        taskStatusLog.setAgentName(taskInfo.getAgentName());
        taskStatusLog.setPropertyName(taskInfo.getPropertyName());
        taskStatusLog.setTaskId(taskInfo.getId());
        taskStatusLog.setPlanId(taskInfo.getPlanId());
        taskStatusLog.setTaskStatus(status);
        taskStatusLog.setContent(content);
        taskStatusLog.setCreateTime(date);
        taskStatusLogService.save(taskStatusLog);
    }
    private void setTaskStatusLogByNotice(Date date, Hardware hardware, Integer status, String content,Long planId ) {
        TaskStatusLog taskStatusLog = new TaskStatusLog();
        taskStatusLog.setAgentId(hardware.getAgentId());
        taskStatusLog.setPropertyId(hardware.getPropertyId());
        taskStatusLog.setDistrictId(hardware.getDistrictId());
        taskStatusLog.setPlanId(planId);
        taskStatusLog.setTaskStatus(status);
        taskStatusLog.setContent(content);
        taskStatusLog.setCreateTime(date);
        taskStatusLogService.save(taskStatusLog);
    }

    private Integer getDistrictTaskNo(Long districtId) {
        QueryWrapper<TaskDistrictParam> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("district_id", districtId);

        List<TaskDistrictParam> list = taskDistrictParamService.list(wrapper);
        if (!list.isEmpty()) {
            TaskDistrictParam taskDistrictParam = list.get(0);
            taskDistrictParam.setTaskNo(taskDistrictParam.getTaskNo() + 1);

            taskDistrictParamService.updateById(taskDistrictParam);
            redisService4.set("DevTaskFlag:" + districtId.toString(), taskDistrictParam.getDevTaskFlag().toString());
            return taskDistrictParam.getTaskNo().intValue();
//            Long taskNo = list.get(0)
//                    .getTaskNo();
        } else {
            District district = districtService.getById(districtId);
            if (district != null) {
                TaskDistrictParam taskDistrictParam = new TaskDistrictParam();
                taskDistrictParam.setAgentId(district.getAgentId());
                taskDistrictParam.setPropertyId(district.getPropertyId());
                taskDistrictParam.setDistrictId(district.getId());
                taskDistrictParam.setDistrictName(district.getDistrictName());
                taskDistrictParam.setUserRestDuration(60);
                taskDistrictParam.setTaskNo(1L);
                taskDistrictParam.setCommonLimit(5);
                taskDistrictParam.setSpecialLimit(99);
                taskDistrictParam.setUrgentLimit(99);
                taskDistrictParam.setBeaconNo(1);
                taskDistrictParam.setPoint(1.0);
                taskDistrictParam.setWageBase(1.0);
                taskDistrictParam.setDevTaskFlag(1);
                taskDistrictParamService.save(taskDistrictParam);
                redisService4.set("PoolOrderCount:1:" + districtId.toString(), "99");
                redisService4.set("PoolOrderCount:2:" + districtId.toString(), "99");
                redisService4.set("PoolOrderCount:3:" + districtId.toString(), "5");
                redisService4.set("DevTaskFlag:" + districtId.toString(), taskDistrictParam.getDevTaskFlag().toString());

            }
        }
        return 0;
    }

}
