package xiaoqu.home.open.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.config.XxlJobInfo;
import xiaoqu.home.open.controller.export.plan.PlanAppointExport;
import xiaoqu.home.open.controller.export.plan.PlanDevOpsExport;
import xiaoqu.home.open.controller.export.plan.PlanInspectExport;
import xiaoqu.home.open.controller.input.plan.*;
import xiaoqu.home.open.controller.input.sceneObject.Scene;
import xiaoqu.home.open.controller.input.task.GridAndSceneInput;
import xiaoqu.home.open.controller.input.task.TaskInfoInspectPageInput;
import xiaoqu.home.open.controller.output.plan.*;
import xiaoqu.home.open.controller.output.scenes.SceneTreeOutput;
import xiaoqu.home.open.model.db1.*;
import xiaoqu.home.open.model.db2.*;
import xiaoqu.home.open.model.db2.Object;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
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.*;
import xiaoqu.home.open.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * http://192.168.1.186:7080/xxl-job-admin/
 */
@Api(value = "计划相关")
@Controller
@RequestMapping("/plan")
@Slf4j
public class PlanController {
    @Autowired
    PlanService planService;
    @Autowired
    WageService wageService;
    @Autowired
    TaskUserService taskUserService;
    @Autowired
    RedisService4 redisService4;
    @Autowired
    RedisService5 redisService5;
    @Autowired
    PlanObjectService planObjectService;
    @Autowired
    PlanOperationService planOperationService;
    @Autowired
UserDistrictAttendanceService userDistrictAttendanceService;
    @Autowired
    ObjectService objectService;
    @Autowired
    PlanScenesService planScenesService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    DistrictService districtService;
    @Autowired
    TaskTypeService taskTypeService;

    @Autowired
    UserProperService userProperService;

    @Autowired
    OperationService operationService;

    @Autowired
    UserService userService;
    @Autowired
    PlanUserService planUserService;
    @Autowired
    ToiletService toiletService;
    @Autowired
    PositionsService positionsService;
    @Autowired
    BuildingService buildingService;
    @Autowired
    FloorService floorService;
    @Autowired
    LabelManageService labelManageService;
    @Autowired
    PlanLogicLabelService planLogicLabelService;
    @Autowired
    MultistageGridService multistageGridService;
    @Autowired
    SceneObjectService sceneObjectService;
    @Autowired
    PlanWorkGroupService planWorkGroupService;
    @Autowired
    WorkGroupService workGroupService;
    @Autowired
    TaskInfoService taskInfoService;
    @Autowired
    WorkGroupToPrincipalService workGroupToPrincipalService;
    @Autowired
    XxlJobUtil XxlJobUtil;


    @ApiOperation(value = "计划分页查询")
    @ResponseBody
    @RequestMapping(value = "/planPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<PlanPageOutput>> planPageList(HttpServletRequest request, @RequestBody PlanPageInput input) {
        User user = UserUtils.getUser(request);
        log.info("【planPageList】input" + JSONObject.toJSONString(input));
        if (input.getDistrictId() == null) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        PageOutput<PlanPageOutput> output = new PageOutput<PlanPageOutput>();

        if (input.getType() == null) {
            return ResultResponseBeanUtil.success(output);
        }
        QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
        List<Long> planids = null;
        Boolean planidFlag = false;
        if (input.getScenes() != null && !input.getScenes().isEmpty()) {
            List<Scene> scenes = input.getScenes();
            QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
            pswrapper.eq("district_id", input.getDistrictId());
            HashSet<Long> firstIds = new HashSet<>();
            HashSet<Long> secondIds = new HashSet<>();
            HashSet<Long> buildids = new HashSet<>();
            HashSet<Long> floorids = new HashSet<>();
            HashSet<Long> mulitids = new HashSet<>();

            for (Scene scene : scenes) {
                if (scene.getIsscene() == 1) {
                    if (scene.getLevel() == 1) {
                        firstIds.add(scene.getId());
                    } else if (scene.getLevel() == 2) {
                        secondIds.add(scene.getId());
                    }
                } else {
                    if (scene.getLevel() == 1) {
                        buildids.add(scene.getId());
                    } else if (scene.getLevel() == 2) {
                        floorids.add(scene.getId());
                    } else if (scene.getLevel() >= 2) {
                        mulitids.add(scene.getId());
                    }
                }

            }
            if (!firstIds.isEmpty() && !secondIds.isEmpty()) {
                pswrapper.and(wrapperq -> wrapperq.in("scenes_id", firstIds).eq("scenes_level", 1)).or().and(wrapperq -> wrapperq.in("scenes_id", secondIds).eq("scenes_level", 2));
            } else if (!firstIds.isEmpty()) {
                pswrapper.in("scenes_id", firstIds).eq("scenes_level", 1);
            } else if (!secondIds.isEmpty()) {
                pswrapper.in("scenes_id", secondIds).eq("scenes_level", 2);
            }

            if (!buildids.isEmpty()) {
                pswrapper.and(wrapperq -> wrapperq.in("building_id", buildids));
            }
            if (!floorids.isEmpty()) {
                pswrapper.in("floor_id", floorids);
            }
            if (!mulitids.isEmpty()) {
                pswrapper.in("multistage_grid_id", mulitids);
            }

            pswrapper.groupBy("plan_id");
            List<PlanScenes> list = planScenesService.list(pswrapper);
            planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
            input.setScenes(null);
            planidFlag = true;
        }
        if (input.getSceneString() != null) {
            QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
            pswrapper.eq("district_id", input.getDistrictId());
            pswrapper.like("name", input.getSceneString());
            List<PlanScenes> list = planScenesService.list(pswrapper);
            if (planids == null) {
                planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

            } else {
                List<Long> userPlan = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
                planids.addAll(userPlan);
            }

            input.setSceneString(null);
            planidFlag = true;

        }


        if (input.getUserName() != null) {
            QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
            userwrapper.eq("district_id", input.getDistrictId());
            userwrapper.like("name", input.getUserName());
            List<PlanUser> list = planUserService.list(userwrapper);
            if (planids == null) {
                planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

            } else {
                List<Long> userPlan = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
                planids.addAll(userPlan);
            }
            input.setUserName(null);
            planidFlag = true;

        }
        if (input.getUserIds() != null && !input.getUserIds().isEmpty()) {
            QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
            userwrapper.eq("district_id", input.getDistrictId());
            userwrapper.eq("user_id", input.getUserIds());
            List<PlanUser> list = planUserService.list(userwrapper);
            if (planids == null) {
                planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

            } else {
                List<Long> userPlan = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
                planids.addAll(userPlan);
            }
            input.setUserIds(null);
            planidFlag = true;

        }

        if (planids != null) {
            if (planids.isEmpty() && planidFlag) {
                return ResultResponseBeanUtil.success(output);
            }
            wrapper.in("id", planids);
        }
        QueryWrapper<Wage> wagewrapper = WrapperUtils.getWrapper(false);
        wagewrapper.eq("district_id", input.getDistrictId());
        List<Wage> wagelist = wageService.list(wagewrapper);
        Map<Long, Wage> wagemaps = wagelist.stream().collect(Collectors.toMap(Wage::getId, Function.identity(), (key1, key2) -> key2));


        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        Page<Plan> pageList = new Page<Plan>(input.getPage(), input.getRows());
        List<Plan> planList = planService.page(pageList, wrapper).getRecords();
        List<PlanPageOutput> planOutputList = new ArrayList<PlanPageOutput>();

        for (Plan plan : planList) {
            PlanPageOutput planPageOutput = new PlanPageOutput();
            BeanUtils.copyProperties(plan, planPageOutput);
            QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
            pswrapper.eq("district_id", input.getDistrictId());
            pswrapper.eq("plan_id", plan.getId());
            List<PlanScenes> pslist = planScenesService.list(pswrapper);
            if (pslist.isEmpty()) {
                planPageOutput.setScenesName("");
            } else {
                StringBuilder stringBuilder = new StringBuilder();
                List<SceneTreeOutput> objects = new ArrayList<>();
                for (PlanScenes planScenes : pslist) {
                    SceneTreeOutput sceneTreeOutput = new SceneTreeOutput();
                    if (planScenes.getScenesId() > 0) {
                        if (planScenes.getScenesLevel() == 1) {
                            sceneTreeOutput.setId(planScenes.getScenesId() + "_s1");
                        } else if (planScenes.getScenesLevel() == 2) {
                            sceneTreeOutput.setId(planScenes.getScenesId() + "_s2");
                        }
                        sceneTreeOutput.setSceneId(planScenes.getScenesId());
                        sceneTreeOutput.setName(planScenes.getName());
                        sceneTreeOutput.setIsscene(1);
                        sceneTreeOutput.setDisable(false);
                        sceneTreeOutput.setLevel(planScenes.getScenesLevel());
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(planScenes.getName()).append(",");

                    } else if (planScenes.getScenesId() == 0) {
                        if (planScenes.getGridLevel() == 1) {
                            sceneTreeOutput.setId(planScenes.getBuildingId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getBuildingId());
                            sceneTreeOutput.setName(planScenes.getBuildingName());
                        } else if (planScenes.getGridLevel() == 2) {
                            sceneTreeOutput.setId(planScenes.getFloorId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getFloorId());
                            sceneTreeOutput.setName(planScenes.getFloor());
                        } else if (planScenes.getGridLevel() >= 3) {
                            sceneTreeOutput.setId(planScenes.getMultistageGridId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getMultistageGridId());
                            sceneTreeOutput.setName(planScenes.getMultistageGridName());
                        }
                        sceneTreeOutput.setLevel(planScenes.getGridLevel());
                        sceneTreeOutput.setIsscene(0);
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(",");
                    }
                    objects.add(sceneTreeOutput);
                }
                planPageOutput.setScenesName(stringBuilder.substring(0, stringBuilder.length() - 1).replace("->", ""));

                planPageOutput.setScenesList(objects);
            }

            if (planPageOutput.getUserType() == 1) {

                QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
                userwrapper.eq("district_id", input.getDistrictId());
                userwrapper.eq("plan_id", planPageOutput.getId());
                List<PlanUser> list = planUserService.list(userwrapper);
                StringBuffer stringBuffer = new StringBuffer();
                for (PlanUser planUser : list) {
                    stringBuffer.append(planUser.getName()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    planPageOutput.setUserName(stringBuffer.substring(0, stringBuffer.length() - 1));
                } else {
                    planPageOutput.setUserName("");
                }

            } else if (planPageOutput.getUserType() == 2) {
                QueryWrapper<PlanWorkGroup> pwgwrapper = WrapperUtils.getWrapper(false);
                pwgwrapper.eq("plan_id", plan.getId());
                List<PlanWorkGroup> pwglist = planWorkGroupService.list(pwgwrapper);
                StringBuilder stringBuilder = new StringBuilder();
                for (PlanWorkGroup planWorkGroup : pwglist) {
                    stringBuilder.append(planWorkGroup.getWorkGroupName()).append(",");
                }
                if (stringBuilder.length() > 0) {
                    planPageOutput.setUserName(stringBuilder.substring(0, stringBuilder.length() - 1));
                }
            } else {
                planPageOutput.setUserName("不限人员");

            }
            if (planPageOutput.getModifyId() == null || planPageOutput.getModifyId() == 0) {
                planPageOutput.setModifyTime(null);
            }
            if (planPageOutput.getCircleStatus() == 0) {
                planPageOutput.setCircleType(null);
                planPageOutput.setCircleNo("");
            }
            if (planPageOutput.getCircleNo() != null && planPageOutput.getCircleNo().contains("99")) {
                planPageOutput.setCircleNoString(planPageOutput.getCircleNo().replace("99", "月末"));
            } else {
                planPageOutput.setCircleNoString(planPageOutput.getCircleNo());
            }
            if (plan.getWageId() != null && plan.getWageId() > 0) {
                Wage curWage = wagemaps.get(plan.getWageId());
                if (curWage != null) {
                    planPageOutput.setWageName(curWage.getName());
                }
            } else {
                planPageOutput.setWageName("");
                planPageOutput.setWageId(null);

            }

            planPageOutput.setActionTimeString(plan.getActionStartTime() + "-" + plan.getActionEndTime());
            planOutputList.add(planPageOutput);
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(planOutputList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "设备维护计划分页查询")
    @ResponseBody
    @RequestMapping(value = "/planDevOpsPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<PlanDevOpsPageOutput>> planDevOpsPageList(HttpServletRequest request, @RequestBody PlanDevOpsPageInput input) {
        User user = UserUtils.getUser(request);
        log.info("【planPageList】input" + JSONObject.toJSONString(input));
        if (input.getDistrictId() == null) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        wrapper.eq("type", 1);

        Page<Plan> pageList = new Page<Plan>(input.getPage(), input.getRows());

        Page<Plan> page = planService.page(pageList, wrapper);
        List<Plan> planList = page.getRecords();

        List<PlanDevOpsPageOutput> planOutputList = new ArrayList<PlanDevOpsPageOutput>();
        QueryWrapper<Wage> wagewrapper = WrapperUtils.getWrapper(false);
        wagewrapper.eq("district_id", input.getDistrictId());
        List<Wage> wagelist = wageService.list(wagewrapper);
        Map<Long, Wage> wagemaps = wagelist.stream().collect(Collectors.toMap(Wage::getId, Function.identity(), (key1, key2) -> key2));


        for (Plan plan : planList) {
            PlanDevOpsPageOutput planDevOpsPageOutput = new PlanDevOpsPageOutput();
            BeanUtils.copyProperties(plan, planDevOpsPageOutput);
            if (plan.getPackageStatus() == 1) {
                QueryWrapper<PlanScenes> sceneswrapper = WrapperUtils.getWrapper(false);
                sceneswrapper.eq("plan_id", plan.getId());
                List<PlanScenes> sceneslist = planScenesService.list(sceneswrapper);
                if (!sceneslist.isEmpty()) {
                    PlanScenes planScenes = sceneslist.get(0);
//                    if(planScenes.getScenesLevel()==1){
                    planDevOpsPageOutput.setSceneString(planScenes.getSuperiorGridName() + "->" + planScenes.getName());
//                    }else {
//                        planDevOpsPageOutput.setSceneString(planScenes.getSuperiorGridName()+"->"+planScenes.gets()+"->"+planScenes.getName());
//
//                    }
                }
            } else {
                planDevOpsPageOutput.setSceneString("-");

            }
            if (plan.getUserType() == 1) {
                QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
                userwrapper.eq("plan_id", plan.getId());
                List<PlanUser> userlist = planUserService.list(userwrapper);
//                ArrayList<Long> longs = new ArrayList<>();
                StringBuilder stringBuilder = new StringBuilder();
                for (PlanUser planUser : userlist) {
                    stringBuilder.append(planUser.getName()).append(",");
                }
                if (stringBuilder.length() > 0) {
                    planDevOpsPageOutput.setUserNames(stringBuilder.substring(0, stringBuilder.length() - 1));
                }

            } else if (plan.getUserType() == 2) {
                QueryWrapper<PlanWorkGroup> pwgwrapper = WrapperUtils.getWrapper(false);
                pwgwrapper.eq("plan_id", plan.getId());
                List<PlanWorkGroup> pwglist = planWorkGroupService.list(pwgwrapper);
//                ArrayList<Long> longs = new ArrayList<>();
                StringBuilder stringBuilder = new StringBuilder();
                for (PlanWorkGroup planWorkGroup : pwglist) {
                    stringBuilder.append(planWorkGroup.getWorkGroupName()).append(",");
                }
                if (stringBuilder.length() > 0) {
                    planDevOpsPageOutput.setUserNames(stringBuilder.substring(0, stringBuilder.length() - 1));
                }

            } else {
                planDevOpsPageOutput.setUserNames("不限人员");
            }
            if (planDevOpsPageOutput.getModifyId() == 0) {
                planDevOpsPageOutput.setModifyTime(null);
                planDevOpsPageOutput.setModifyName("");
            }
            if (plan.getWageId() != null && plan.getWageId() > 0) {
                Wage curWage = wagemaps.get(plan.getWageId());
                if (curWage != null) {
                    planDevOpsPageOutput.setWageName(curWage.getName());
                }
            } else {
                planDevOpsPageOutput.setWageName("");
                planDevOpsPageOutput.setWageId(null);

            }
            planOutputList.add(planDevOpsPageOutput);
        }


        PageOutput<PlanDevOpsPageOutput> output = new PageOutput<PlanDevOpsPageOutput>();
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(planOutputList);
        return ResultResponseBeanUtil.success(output);
    }

    @ApiOperation(value = "添加/修改例行计划")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addOrUpdateRoutinePlan", method = RequestMethod.POST)
    public BaseOutput<String> addOrUpdateRoutinePlan(HttpServletRequest request, @RequestBody PlanInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【addRoutinePlan】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择所属站点");
        }
        District district = districtService.getById(input.getDistrictId());
        if (district == null) {
            return ResultResponseBeanUtil.fail("站点异常，请刷新页面");
        }

        if (input.getType() == 0 && (input.getScenes() == null || input.getScenes().isEmpty())) {
            return ResultResponseBeanUtil.fail("请选择场景");
        }
        if (input.getTaskName() == null || input.getTaskName().trim().equals("")) {
            return ResultResponseBeanUtil.fail("请输入任务名称");
        }

        if (input.getUserType() == 1 && (input.getUserIds() == null || input.getUserIds().isEmpty())) {
            return ResultResponseBeanUtil.fail("请选择任务人员");

        }
        if (input.getUserType() == 2 && (input.getWorkGroupIds() == null || input.getWorkGroupIds().isEmpty())) {
            return ResultResponseBeanUtil.fail("请选择任务班组");
        }
//          0623有创建限制条件
        if (input.getActionTimeType() != null && input.getActionTimeType() == 1) {
            if (input.getActionStartTime() != null && input.getActionEndTime() != null) {
                try {
                    Integer curtime = DateToConverter.getTime(input.getActionEndTime(), input.getActionStartTime());
                    if ((curtime - input.getWorkingTiming() - input.getTransitionTiming() - input.getReadyTiming() - input.getRedundanceTiming()) < 0) {
                        return ResultResponseBeanUtil.fail("要求执行时长应大于人效管理总时长");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    return ResultResponseBeanUtil.fail("要求执行时段异常");
                }
            }
        }
        if (input.getTaskCreateType() == 0 && input.getActionTimeType() == null) {
            return ResultResponseBeanUtil.fail("请选择要求执行时段方式");

        }


        //任务名称验重
        {
            QueryWrapper<Plan> checkwrapper = WrapperUtils.getWrapper(false);
            checkwrapper.eq("task_name", input.getTaskName());
            checkwrapper.lt("status", 2);
            List<Plan> checklist = planService.list(checkwrapper);
            List<Long> checkids = checklist.stream().map(p -> p.getId()).collect(Collectors.toList());
            if (!checkids.isEmpty()) {

                QueryWrapper<PlanScenes> checkScenewrapper = WrapperUtils.getWrapper(false);
                checkScenewrapper.in("plan_id", checkids);
                List<PlanScenes> scenesChecklist = planScenesService.list(checkScenewrapper);
                HashSet<String> psstrings = new HashSet<>();
                for (PlanScenes planScenes : scenesChecklist) {
                    psstrings.add(planScenes.getScenesLevel() + "_" + planScenes.getScenesId());
                }
                if (input.getScenes() != null && input.getScenes().size() > 0) {
                    for (Scene scene : input.getScenes()) {
                        if (scene.getIsscene() == 1) {
                            if (psstrings.contains(scene.getLevel() + "_" + scene.getId())) {
                                if (input.getId() == null) {
                                    return ResultResponseBeanUtil.fail("计划任务已存在，请修改后提交");
                                } else {
                                    if (!checkids.contains(input.getId())) {
                                        return ResultResponseBeanUtil.fail("计划任务已存在，请修改后提交");
                                    }
                                }

                            }

                        }
                    }
                }
            }

        }
        if (input.getTaskCreateType() == null) {
            return ResultResponseBeanUtil.fail("请选择任务生成类型");
        }
        if (input.getType() == null) {
            return ResultResponseBeanUtil.fail("计划类型异常，请刷新页面");
        }
        if (input.getTaskCreateType() == 1 && (input.getActionCount() == null || input.getActionCount() == 0)) {
            return ResultResponseBeanUtil.fail("请设置触发人流量");
        }


        Date curdate = new Date();
        String finishTimeStr = DateToConverter.getDateAddOrSub(12, 2, curdate);
        curdate = DateToConverter.parseDate(finishTimeStr, 5);
        Plan plan;
        //在哪做
        if (input.getId() == null) {
            plan = new Plan();
            plan.setDistrictId(district.getId());
            plan.setDistrictName(district.getDistrictName());
            plan.setAgentId(district.getAgentId());
            plan.setPropertyId(district.getPropertyId());
            String agentName = redisService5.get("name:Agent:" + district.getAgentId());
            plan.setAgentName(agentName);
            String propertyname = redisService5.get("name:Properyt:" + district.getPropertyId());
            plan.setPropertyName(propertyname);
            plan.setTaskOrder(99);
        } else {
            plan = planService.getById(input.getId());
            if (plan == null) {
                return ResultResponseBeanUtil.fail("记录异常");
            }
        }
        //做什么，怎么做
        {
            plan.setType(input.getType());
            if (input.getType() == 0) {
                //自定义
                plan.setTaskTypeId(18L);
            } else if (input.getType() == 2) {
                //其他
                plan.setTaskTypeId(17L);
            }
            plan.setTaskName(input.getTaskName());
            plan.setTaskStandard(input.getTaskStandard() != null ? input.getTaskStandard() : "");
            plan.setTaskContent(input.getTaskContent() != null ? input.getTaskContent() : "");
            plan.setTaskRequire(input.getTaskRequire() != null ? input.getTaskRequire() : "");
        }
        plan.setUserType(input.getUserType());
        plan.setUserStatus(input.getUserStatus());
//        Boolean resetXxljobFlag = false;
//        if (plan.getId()!=null&& plan.getStatus() != 0 && input.getStatus() == 0) {
//            resetXxljobFlag = true;
//        }
        plan.setStatus(input.getStatus());
        plan.setPackageStatus(input.getPackageStatus());

        //哪天做
        //计划启用期限
        {
            if (input.getStartStatus() == 0) {
                plan.setStartStatus(0);
                plan.setStartTime(curdate);
                plan.setEndTime(null);
            } else {
                plan.setStartStatus(1);
                if (input.getStartTime() != null) {
                    Date startdate = DateToConverter.parseDate(input.getStartTime(), 5);
                    plan.setStartTime(startdate);
                } else {
                    plan.setStartTime(curdate);
                }
                if (input.getEndTime() != null) {
                    Date enddate = DateToConverter.parseDate(input.getEndTime(), 5);
                    plan.setEndTime(enddate);
                } else {
                    plan.setEndTime(null);
                }
            }
        }
        //跳过日期，plan标记使用
        {
            //仅区分工作日2和休息日1 两种
            plan.setEliminateType(input.getEliminateType());
            //任务过期时间
            plan.setExpireType(2);
            if (input.getExpireTiming() != null) {
                plan.setExpireTiming(Integer.parseInt(input.getExpireTiming()));
            } else {
                plan.setExpireTiming(1);

            }

        }
        //任务生成类型0:定时;1:人流;2:立刻
        {
            plan.setTaskCreateType(input.getTaskCreateType());
            if (input.getTaskCreateType() == 1) {
                plan.setActionCount(input.getActionCount());
            } else {
                plan.setActionCount(0);
            }

            //任务执行时段
            {
//                plan.setActionTimeType(input.getActionTimeType());
                if (input.getActionTimeType() == null || input.getActionTimeType() == 0) {
                    plan.setActionTimeType(0);
                    plan.setActionStartTime("");
                    plan.setActionEndTime("");
                } else if (input.getActionTimeType() == 1) {
                    plan.setActionTimeType(input.getActionTimeType());
                    plan.setActionStartTime(input.getActionStartTime());
                    plan.setActionEndTime(input.getActionEndTime());
                }
            }
        }


        //重复设置，重复方式二 设置plan标记依据
        {
            plan.setCircleStatus(input.getCircleStatus());
            plan.setCircleType(input.getCircleType());
            if (input.getCircleNo() != null) {
                String[] split = input.getCircleNo().split(",");
                int[] ret = new int[split.length];//创建一个字符串数组长度的int数组
                Arrays.sort(split);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < split.length; i++) {
                    ret[i] = Integer.parseInt(split[i]);
                }
                Arrays.sort(ret);
                for (int i = 0; i < split.length; i++) {
                    stringBuilder.append(ret[i]).append(",");
                }
                plan.setCircleNo(stringBuilder.substring(0, stringBuilder.length() - 1));

            }
        }

        {
            plan.setIsCross(input.getIsCross());
            plan.setMustStatus(input.getMustStatus());
            plan.setNotStatus(input.getNotStatus());
        }

        //人效管理
        {
            if (input.getWageId() != null) {
                plan.setWageId(input.getWageId());
                plan.setWorkingTiming(input.getWorkingTiming() != null ? input.getWorkingTiming() : 0);
                plan.setTransitionTiming(input.getTransitionTiming() != null ? input.getTransitionTiming() : 0);
                plan.setReadyTiming(input.getReadyTiming() != null ? input.getReadyTiming() : 0);
                plan.setRedundanceTiming(input.getRedundanceTiming() != null ? input.getRedundanceTiming() : 60);

                int totalTiming = plan.getWorkingTiming() + plan.getTransitionTiming() + plan.getReadyTiming() + plan.getRedundanceTiming();
                double wageHour = totalTiming / 60.0;
                wageHour = new BigDecimal(wageHour).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                plan.setWageHour(wageHour);
                Wage wage = wageService.getById(input.getWageId());
                plan.setPoint(wageHour * wage.getPoint());
            } else {
                plan.setWageHour(0.0);
            }

        }
        //标签状态
        {
            if (input.getMustLabelIds() != null && !input.getMustLabelIds().isEmpty()) {
                plan.setMustStatus(1);
            } else {
                plan.setMustStatus(0);

            }
            if (input.getNotLabelIds() != null && !input.getNotLabelIds().isEmpty()) {
                plan.setNotStatus(1);
            } else {
                plan.setNotStatus(0);

            }
        }

        if (plan.getId() == null) {

            List<Scene> scenes = input.getScenes();
            if (input.getPackageStatus() == 1) {
                planService.save(plan);
                setUserOrGroup(plan, input.getUserType(), input.getUserIds(), input.getWorkGroupIds());
                setXxlJobInfo(plan);

                List<PlanScenes> planSceneslist = new ArrayList<>();
                for (Scene scene : scenes) {
                    setPlanScenes(plan, planSceneslist, scene);
                }
                planScenesService.saveBatch(planSceneslist);
                //是否标签
                List<Long> mustLabelIds = input.getMustLabelIds();
                setLabel(plan, mustLabelIds, 0);
                List<Long> notLabelIds = input.getNotLabelIds();
                setLabel(plan, notLabelIds, 1);
                setObject(input, plan, null);
                setOperation(input, plan, null);

            } else {
                List<PlanScenes> planSceneslist = new ArrayList<>();
                for (Scene scene : scenes) {
                    Plan curplan = new Plan();
                    BeanUtils.copyProperties(plan, curplan);

                    planService.save(curplan);
                    //
                    if (input.getUserType() == 1 && input.getUserIds() != null && !input.getUserIds().isEmpty()) {
                        setPlanUser(input.getUserIds(), curplan);
                    }
                    if (input.getUserType() == 2 && input.getWorkGroupIds() != null && !input.getWorkGroupIds().isEmpty()) {
                        setPlanWorkGroup(input.getWorkGroupIds(), curplan);
                    }
                    if (input.getUserType() == 0) {
                        setPlanUser(null, plan);
                        setPlanWorkGroup(null, plan);

                    }
                    setXxlJobInfo(curplan);
                    setPlanScenes(curplan, planSceneslist, scene);
                    //是否标签
                    List<Long> mustLabelIds = input.getMustLabelIds();
                    setLabel(curplan, mustLabelIds, 0);
                    List<Long> notLabelIds = input.getNotLabelIds();
                    setLabel(curplan, notLabelIds, 1);
                    Set<Long> curobjectIds = setObject(input, curplan, scene);

                    setOperation(input, curplan, curobjectIds);

                }
                planScenesService.saveBatch(planSceneslist);
            }
            return ResultResponseBeanUtil.success("添加成功");


        } else {
            planService.updateById(plan);

//            if(resetXxljobFlag){

            String oldtaskId = redisService4.get("Plan:" + plan.getType() + ":" + plan.getId());
            if (oldtaskId != null) {
                XxlJobUtil.pause(Integer.parseInt(oldtaskId));
            }
            plan.setStartTime(curdate);
            setXxlJobInfo(plan);
//            }
            //修改？
            setObject(input, plan, null);
            setOperation(input, plan, null);
            setUserOrGroup(plan, input.getUserType(), input.getUserIds(), input.getWorkGroupIds());
            List<Long> mustLabelIds = input.getMustLabelIds();
            List<Long> notLabelIds = input.getNotLabelIds();

            setLabel(plan, mustLabelIds, 0);
            setLabel(plan, notLabelIds, 1);
            return ResultResponseBeanUtil.success("编辑成功");
        }


    }


    @ApiOperation(value = "添加设备维护计划")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addDevOpsPlan", method = RequestMethod.POST)
    public BaseOutput<String> addDevOpsPlan(HttpServletRequest request, @RequestBody PlanDevOpsInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【addDevOpsPlan】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择所属站点");
        }
        District district = districtService.getById(input.getDistrictId());
        if (district == null) {
            return ResultResponseBeanUtil.fail("站点异常，请刷新页面");
        }

        if (input.getPackageStatus() != null && input.getPackageStatus() == 1 && (input.getScenes() == null || input.getScenes().isEmpty())) {
            return ResultResponseBeanUtil.fail("请选择场景");
        }

        if (input.getTaskTypeIds().isEmpty()) {
            return ResultResponseBeanUtil.fail("请选择任务名称");
        }
        if (input.getWorkingTiming() == null || input.getWorkingTiming() == 0) {
            return ResultResponseBeanUtil.fail("请输入超时时间");
        }
        if (input.getWageId() != null && input.getWageId() > 0) {
            if (input.getWageHour() == null) {
                return ResultResponseBeanUtil.fail("请设置工时");
            }
            if (input.getWageHour() < 0) {
                return ResultResponseBeanUtil.fail("工时需为正数");
            }
        }

        if (input.getActionStartTime() != null && input.getActionEndTime() != null) {


        } else if (input.getActionStartTime() == null && input.getActionEndTime() == null) {

//            return ResultResponseBeanUtil.fail("请选择场景");

        } else {
            return ResultResponseBeanUtil.fail("请完整设置启禁用时间");
        }
        List<Long> userIds = input.getUserIds();
        List<Long> taskTypeIds = input.getTaskTypeIds();
        QueryWrapper<TaskType> typewrapper = WrapperUtils.getWrapper(false);
        typewrapper.in("id", taskTypeIds);
        List<TaskType> list = taskTypeService.list(typewrapper);
        if (input.getPackageStatus() == 1) {
            List<Scene> scenes = input.getScenes();
            ArrayList<PlanScenes> planSceneslist = new ArrayList<>();

            for (Scene scene : scenes) {
                PlanScenes planScenes = new PlanScenes();

                Toilet toilet = null;
                Positions positions = null;
                if (scene.getLevel() == 1) {
                    toilet = toiletService.getById(scene.getId());
                    BeanUtils.copyProperties(toilet, planScenes);
                    planScenes.setScenesId(toilet.getId());
                } else if (scene.getLevel() == 2) {
                    positions = positionsService.getById(scene.getId());
                    BeanUtils.copyProperties(positions, planScenes);
                    planScenes.setScenesId(positions.getId());
                }

                planScenes.setId(null);
                for (TaskType taskType : list) {
                    QueryWrapper<PlanScenes> wrapper = WrapperUtils.getWrapper(false);
                    wrapper.eq("district_id", district.getId());
                    wrapper.eq("task_type_id", taskType.getId());
                    wrapper.eq("scenes_id", scene.getId());
                    wrapper.eq("scenes_level", scene.getLevel());
                    List<PlanScenes> planScenesCheck = planScenesService.list(wrapper);
                    Plan plan;
                    if (planScenesCheck.isEmpty()) {
                        plan = new Plan();

                        plan.setAgentId(district.getAgentId());
                        plan.setPropertyId(district.getPropertyId());
                        plan.setDistrictId(district.getId());
                        plan.setDistrictName(district.getDistrictName());
                        plan.setType(1);
                        plan.setTaskOrder(99);

                    } else {
                        planScenes = planScenesCheck.get(0);

                        plan = planService.getById(planScenes.getPlanId());
                        if (plan == null) {
                            plan = new Plan();
                            plan.setAgentId(district.getAgentId());
                            plan.setPropertyId(district.getPropertyId());
                            plan.setDistrictId(district.getId());
                            plan.setDistrictName(district.getDistrictName());
                            plan.setType(1);
                            plan.setTaskOrder(99);

                        }
                    }


                    plan.setActionStartTime(input.getActionStartTime() != null ? input.getActionStartTime() : "");
                    plan.setActionEndTime(input.getActionEndTime() != null ? input.getActionEndTime() : "");
                    plan.setWorkingTiming(input.getWorkingTiming());
                    plan.setTaskName(taskType.getName());
                    plan.setTaskTypeId(taskType.getId());
                    plan.setStatus(1);
                    plan.setUserType(input.getUserType());
                    plan.setIsCross(input.getIsCross());
                    plan.setClockFlag(input.getClockFlag());
                    plan.setPackageStatus(input.getPackageStatus());
                    plan.setGroupOrder(taskType.getGroupOrder());
                    plan.setPoolOrder(taskType.getPoolOrder());
                    plan.setTaskOrder(taskType.getTaskOrder());
                    plan.setTaskFlag(taskType.getTaskFlag());
                    plan.setNoticeFlag(taskType.getNoticeFlag());
                    plan.setPackageStatus(input.getPackageStatus());
                    setPlanWage(input.getWageId(), plan, input.getWageHour());


//                    if (userIds == null || userIds.isEmpty()) {
//                        plan.setUserType(0);
//                    } else {
//                        plan.setUserType(1);
//                    }
//                    if (input.getPackageStatus() == 0) {
//                        plan.setPackageStatus(0);
//                    } else {
//                        plan.setPackageStatus(1);
//                    }
                    if (plan.getId() == null) {
                        planService.save(plan);
                        setPlanUser(userIds, plan);
                        PlanScenes planScenesnew = new PlanScenes();
                        BeanUtils.copyProperties(planScenes, planScenesnew, "id");
                        planScenesnew.setPlanId(plan.getId());
                        planScenesnew.setTaskTypeId(taskType.getId());
                        planScenesnew.setCreateTime(new Date());
                        planSceneslist.add(planScenesnew);
                        setWorkingTiming(input.getWorkingTiming(), planScenesnew, taskType.getId());
                    } else {
                        planService.updateById(plan);
                        setPlanUser(userIds, plan);
                        setWorkingTiming(input.getWorkingTiming(), planScenes, taskType.getId());
                    }


                }
                planScenesService.saveBatch(planSceneslist);
            }
        } else {
            for (TaskType taskType : list) {

                QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
                wrapper.eq("district_id", district.getId());
                wrapper.eq("task_type_id", taskType.getId());
                List<Plan> planlist = planService.list(wrapper);
                Plan plan;
                if (planlist.isEmpty()) {
                    plan = new Plan();
                    plan.setAgentId(district.getAgentId());
                    plan.setPropertyId(district.getPropertyId());
                    plan.setDistrictId(district.getId());
                    plan.setDistrictName(district.getDistrictName());
                    plan.setType(1);
                    plan.setTaskOrder(99);

                } else {
                    plan = planlist.get(0);
                }
                plan.setClockFlag(input.getClockFlag());
                plan.setIsCross(input.getIsCross());
                plan.setActionStartTime(input.getActionStartTime() != null ? input.getActionStartTime() : "");
                plan.setActionEndTime(input.getActionEndTime() != null ? input.getActionEndTime() : "");
                plan.setWorkingTiming(input.getWorkingTiming());
                plan.setTaskName(taskType.getName());
                plan.setTaskTypeId(taskType.getId());
                plan.setStatus(1);
                plan.setUserType(input.getUserType());
                plan.setPackageStatus(input.getPackageStatus());
                setPlanWage(input.getWageId(), plan, input.getWageHour());


//                if (userIds == null || userIds.isEmpty()) {
//                    plan.setUserType(0);
//                } else {
//                    plan.setUserType(1);
//                }
//                if (input.getIsCross() == 0) {
//                    plan.setIsCross(0);
//                } else {
//                    plan.setIsCross(1);
//                }
                if (plan.getId() == null) {
                    planService.save(plan);

                } else {
                    planService.updateById(plan);
                }
                setPlanUser(userIds, plan);
                redisService4.set("workingTimeing:d:" + plan.getDistrictId() + ":" + taskType.getId(), input.getWorkingTiming().toString());

            }
        }
        //禁用结束时间
        if (input.getActionStartTime() != null) {
            String startBoolean = redisService4.get("devOpsDisable:0:" + input.getActionStartTime());
            if (startBoolean == null) {
                getStringBaseOutput(input.getActionStartTime(), 0);

            }
        }

        //禁用开始时间
        if (input.getActionEndTime() != null) {

            String endBoolean = redisService4.get("devOpsDisable:1:" + input.getActionEndTime());
            if (endBoolean == null) {
                getStringBaseOutput(input.getActionEndTime(), 1);
            }
        }
        return ResultResponseBeanUtil.success("添加成功");

    }

    @ApiOperation(value = "添加/修改指派计划")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addOrUpdateAppointPlan", method = RequestMethod.POST)
    public BaseOutput<String> addOrUpdateAppointPlan(HttpServletRequest request, @RequestBody PlanAppointInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【addOrUpdateAppointPlan】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择所属站点");
        }
        District district = districtService.getById(input.getDistrictId());
        if (district == null) {
            return ResultResponseBeanUtil.fail("站点异常，请刷新页面");
        }

//        if (input.getIsCross()==1&&(input.getScenes() == null || input.getScenes().isEmpty())) {
//            return ResultResponseBeanUtil.fail("请选择场景");
//        }
        if (input.getTaskName() == null || input.getTaskName().trim().equals("")) {
            return ResultResponseBeanUtil.fail("请输入任务名称");
        }
        if (input.getActionTimeType() != null && input.getActionTimeType() == 1) {
            if (input.getStartTime() == null) {
                return ResultResponseBeanUtil.fail("请选择预约时间");
            }
        }
        if (input.getUserType() == 2 && (input.getWorkGroupIds() == null || input.getWorkGroupIds().isEmpty())) {
            return ResultResponseBeanUtil.fail("请选择班组");
        }

        if (input.getWageId() != null && input.getWageId() > 0) {
            if (input.getWageHour() == null) {
                return ResultResponseBeanUtil.fail("请设置工时");
            }
            if (input.getWageHour() < 0) {
                return ResultResponseBeanUtil.fail("工时需为正数");
            }
        }
        Plan plan = null;
        if (input.getId() == null) {
            plan = new Plan();
            plan.setDistrictId(district.getId());
            plan.setDistrictName(district.getDistrictName());
            plan.setAgentId(district.getAgentId());
            String agentName = redisService5.get("name:Agent:" + district.getAgentId());
            plan.setAgentName(agentName);
            String propertyname = redisService5.get("name:Properyt:" + district.getPropertyId());
            plan.setPropertyName(propertyname);
            plan.setPropertyId(district.getPropertyId());
            plan.setType(2);
            plan.setIsCross(1);
            plan.setType(input.getType());
            plan.setStatus(input.getStatus());
            plan.setTaskOrder(99);

        } else {
            plan = planService.getById(input.getId());
            if (plan.getType() != 2) {
                return ResultResponseBeanUtil.fail("当前计划非指派计划");
            }
        }
        Boolean xxlFlag = false;
        if (input.getId() == null) {
            xxlFlag = true;
        } else if (input.getId() != null && plan.getStatus() == 0) {
            if (!DateToConverter.getFormattedDate(plan.getStartTime(), 5).equals(input.getStartTime())) {
                xxlFlag = true;
            }
        }

        plan.setTaskTypeId(17L);
        plan.setTaskName(input.getTaskName());
//            plan.setTaskStandard(input.getTaskStandard() != null ? input.getTaskStandard() : "");
        plan.setTaskContent(input.getTaskContent() != null ? input.getTaskContent() : "");
        plan.setTaskRequire(input.getTaskRequire() != null ? input.getTaskRequire() : "");
        plan.setActionTimeType(input.getActionTimeType());

        setPlanWage(input.getWageId(), plan, input.getWageHour());

        if (input.getActionTimeType() == 1) {
            plan.setTaskCreateType(0);
            plan.setStartTime(DateToConverter.parseDate(input.getStartTime(), 5));
        } else {
            plan.setTaskCreateType(2);
//            plan.setStartTime(DateToConverter.parseDate(input.getStartTime(), 5));

        }
        if (input.getEndTime() != null) {

            plan.setExpireType(2);
            plan.setEndTime(DateToConverter.parseDate(input.getEndTime(), 5));
        } else {
            plan.setExpireType(0);
            plan.setEndTime(null);
            UpdateWrapper<Plan> planupdateWrapper = WrapperUtils.getUpdateWrapper(false);
            planupdateWrapper.eq("id", input.getId());
            planupdateWrapper.set("end_time", null);
            planService.update(planupdateWrapper);

        }

        plan.setUserType(input.getUserType());
        if (input.getUserIds() != null && input.getUserIds().size() == 1) {
            plan.setUserStatus(0);
        } else {
            plan.setUserStatus(1);
        }
        plan.setIsCross(input.getIsCross());
        if (plan.getId() == null) {
            planService.save(plan);

        } else {
            planService.updateById(plan);
            //清除旧数据,仅修改执行中的
            if (plan.getStatus() == 0) {
                UpdateWrapper<PlanUser> userWrapper = Wrappers.update();
                userWrapper.eq("plan_id", plan.getId());
                userWrapper.set("soft_delete", 1);
                planUserService.update(userWrapper);
                UpdateWrapper<PlanScenes> scenesWrapper = Wrappers.update();
                scenesWrapper.eq("plan_id", plan.getId());
                scenesWrapper.set("soft_delete", 1);
                planScenesService.update(scenesWrapper);
            }
        }

        if (input.getIsCross() == 1 && (input.getScenes() != null && !input.getScenes().isEmpty())) {
            //填充用户场景
            List<Scene> scenes = input.getScenes();
            List<PlanScenes> planScenesList = new ArrayList<>();
            for (Scene scene : scenes) {
                PlanScenes planScenes = new PlanScenes();

                Toilet toilet = null;
                Positions positions = null;
                //20231120 王恒需求： setSuperiorGridName场景的获取所属区域名称，区域的仅获取上级区域
                if (scene.getIsscene() == 1) {
                    if (scene.getLevel() == 1) {
                        toilet = toiletService.getById(scene.getId());
                        BeanUtils.copyProperties(toilet, planScenes);
                        planScenes.setScenesId(toilet.getId());
                        planScenes.setScenesLevel(1);
                    } else if (scene.getLevel() == 2) {
                        positions = positionsService.getById(scene.getId());
                        BeanUtils.copyProperties(positions, planScenes);
                        planScenes.setScenesId(positions.getId());
                        planScenes.setScenesLevel(2);
                    }
                } else if (scene.getIsscene() == 0) {
                    if (scene.getLevel() == 1) {
                        Building building = buildingService.getById(scene.getId());
//                        BeanUtils.copyProperties(building, planScenes);
                        planScenes.setAgentId(building.getAgentId());
                        planScenes.setAgentName(building.getAgentName());
                        planScenes.setPropertyId(building.getPropertyId());
                        planScenes.setPropertyName(building.getPropertyName());
                        planScenes.setDistrictId(building.getDistrictId());
                        planScenes.setDistrictName(building.getDistrictName());
                        planScenes.setBuildingId(building.getId());
                        planScenes.setBuildingName(building.getName());
                        planScenes.setName(building.getName());
                        planScenes.setGridLevel(building.getGridLevel());
                        planScenes.setScenesId(0L);
                        planScenes.setSuperiorGridName("");
                    } else if (scene.getLevel() == 2) {
                        Floor floor = floorService.getById(scene.getId());
                        planScenes.setAgentId(floor.getAgentId());
                        planScenes.setAgentName(floor.getAgentName());
                        planScenes.setPropertyId(floor.getPropertyId());
                        planScenes.setPropertyName(floor.getPropertyName());
                        planScenes.setDistrictId(floor.getDistrictId());
                        planScenes.setDistrictName(floor.getDistrictName());
                        planScenes.setBuildingId(floor.getBuildingId());
                        planScenes.setBuildingName(floor.getSuperiorName());
                        planScenes.setGridLevel(floor.getGridLevel());
                        planScenes.setName(floor.getName());
                        planScenes.setFloorId(floor.getId());
                        planScenes.setFloor(floor.getName());
                        planScenes.setScenesId(0L);
                        planScenes.setSuperiorGridName(floor.getSuperiorName() );

                    } else if (scene.getLevel() >= 3) {
                        MultistageGrid multistageGrid = multistageGridService.getById(scene.getId());
                        planScenes.setAgentId(multistageGrid.getAgentId());
                        planScenes.setAgentName(multistageGrid.getAgentName());
                        planScenes.setPropertyId(multistageGrid.getPropertyId());
                        planScenes.setPropertyName(multistageGrid.getPropertyName());
                        planScenes.setDistrictId(multistageGrid.getDistrictId());
                        planScenes.setDistrictName(multistageGrid.getDistrictName());
                        planScenes.setBuildingId(multistageGrid.getBuildingId());
                        planScenes.setBuildingName(multistageGrid.getSuperiorName());
                        planScenes.setGridLevel(multistageGrid.getGridLevel());
                        planScenes.setName(multistageGrid.getName());
                        planScenes.setFloorId(multistageGrid.getFloorId());
                        planScenes.setFloor(multistageGrid.getFloor());
                        planScenes.setMultistageGridId(multistageGrid.getId());
                        planScenes.setMultistageGridName(multistageGrid.getName());
                        planScenes.setScenesId(0L);
                        planScenes.setSuperiorGridName(multistageGrid.getSuperiorName());

                    }
                }
                planScenes.setPlanId(plan.getId());
                planScenes.setTaskTypeId(plan.getTaskTypeId());
                planScenes.setId(null);
                planScenes.setCreateTime(plan.getCreateTime());
                planScenesList.add(planScenes);
            }
            planScenesService.saveBatch(planScenesList);

        }
        if (input.getUserType() != null) {
            setUserOrGroup(plan, input.getUserType(), input.getUserIds(), input.getWorkGroupIds());

        }
        //插入生成任务队列
        if (input.getActionTimeType() == 0 && plan.getStatus() == 0) {
            redisService4.lPush("PlanTaskQueue", plan.getId().toString());
            //插入定时任务
        } else if (input.getActionTimeType() == 1 && plan.getStatus() == 0) {

            if (xxlFlag) {
                String xxlTaskId = redisService4.get("Plan:" + plan.getType() + ":" + plan.getId());
                if (xxlTaskId != null) {
                    XxlJobUtil.remove(Integer.parseInt(xxlTaskId));
                }
                setXxlJobInfo(plan);
            }
        }


        return ResultResponseBeanUtil.success("设置成功");

    }


    @ApiOperation(value = "修改设备维护计划")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/updateDevOpsPlan", method = RequestMethod.POST)
    public BaseOutput<String> updateDevOpsPlan(HttpServletRequest request, @RequestBody PlanDevOpsInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【updateDevOpsPlan】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
        Plan plan = planService.getById(input.getId());
        List<Long> userIds = input.getUserIds();

        if (input.getUserType() == 1 && input.getUserIds() != null && !input.getUserIds().isEmpty()) {
            if (input.getUserIds() == null || input.getUserIds().isEmpty()) {
                return ResultResponseBeanUtil.fail("请选择任务人员");
            }
        }
        if (input.getWageId() != null && input.getWageId() > 0) {
            if (input.getWageHour() == null) {
                return ResultResponseBeanUtil.fail("请设置工时");
            }
            if (input.getWageHour() < 0) {
                return ResultResponseBeanUtil.fail("工时需为正数");
            }
        }
        setUserOrGroup(plan, input.getUserType(), input.getUserIds(), input.getWorkGroupIds());
        plan.setUserType(input.getUserType());
        plan.setActionEndTime(input.getActionEndTime() != null ? input.getActionEndTime() : "");
        plan.setActionStartTime(input.getActionStartTime() != null ? input.getActionStartTime() : "");
        plan.setWorkingTiming(input.getWorkingTiming());
        plan.setIsCross(input.getIsCross());
        plan.setClockFlag(input.getClockFlag());
        setPlanWage(input.getWageId(), plan, input.getWageHour());

        planService.updateById(plan);

        //禁用结束时间
        if (input.getActionStartTime() != null) {
            String startBoolean = redisService4.get("devOpsDisable:0:" + input.getActionStartTime());
            if (startBoolean == null) {
                getStringBaseOutput(input.getActionStartTime(), 0);
            }
        }

        //禁用开始时间
        if (input.getActionEndTime() != null) {
            String endBoolean = redisService4.get("devOpsDisable:1:" + input.getActionEndTime());
            if (endBoolean == null) {
                getStringBaseOutput(input.getActionEndTime(), 1);
            }
        } else {
            //清除禁用标记
            //补发任务

            if (plan.getPackageStatus() == 0) {
                redisService4.remove("Disable:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                String taskCommand = redisService4.rightPop("RebuildTask:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                while (taskCommand != null) {
                    redisService5.lPush("taskCommand", taskCommand);
                    taskCommand = redisService4.rightPop("RebuildTask:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                }
            } else {

                QueryWrapper<PlanScenes> wrapper = WrapperUtils.getWrapper(false);
                wrapper.eq("plan_id", plan.getId());
                List<PlanScenes> list = planScenesService.list(wrapper);
                for (PlanScenes planScenes : list) {
                    if (planScenes.getScenesLevel() == 1) {
                        redisService4.remove("Disable:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                        String taskCommand = redisService4.rightPop("RebuildTask:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                        while (taskCommand != null) {
                            redisService5.lPush("taskCommand", taskCommand);
                            taskCommand = redisService4.rightPop("RebuildTask:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                        }
                    } else if (planScenes.getScenesLevel() == 2) {
                        redisService4.remove("Disable:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId(), "0");

                        String taskCommand = redisService4.rightPop("RebuildTask:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                        while (taskCommand != null) {
                            redisService5.lPush("taskCommand", taskCommand);
                            taskCommand = redisService4.rightPop("RebuildTask:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                        }
                    }
                }
            }
        }
        return ResultResponseBeanUtil.success("修改成功");

    }


    @ApiOperation(value = "删除计划")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/removePlan", method = RequestMethod.GET)
    public BaseOutput<String> removePlan(HttpServletRequest request, @RequestParam Long id) {
        User user = UserUtils.getUser(request);
        log.info("【removePlan】User:" + user.getName() + ",参数：" + id);
        Plan plan = planService.getById(id);
        if (plan != null) {
            plan.setSoftDelete(1);
            planService.updateById(plan);
            if (plan.getType() == 1) {
                //任务调度器停止
                if (plan.getPackageStatus() == 0) {
                    redisService4.remove("Disable:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                    redisService4.remove("workingTimeing:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                    String taskCommand = redisService4.rightPop("RebuildTask:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                    while (taskCommand != null) {
                        redisService5.lPush("taskCommand", taskCommand);
                        taskCommand = redisService4.rightPop("RebuildTask:d:" + plan.getDistrictId() + ":" + plan.getTaskTypeId());
                    }

                } else {
                    QueryWrapper<PlanScenes> planSceneswrapper = WrapperUtils.getWrapper(false);
                    planSceneswrapper.eq("plan_id", plan.getId());
                    List<PlanScenes> list = planScenesService.list(planSceneswrapper);
                    for (PlanScenes planScenes : list) {
                        if (planScenes.getScenesLevel() == 1) {
                            redisService4.remove("workingTimeing:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            redisService4.remove("Disable:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            String taskCommand = redisService4.rightPop("RebuildTask:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            while (taskCommand != null) {
                                redisService5.lPush("taskCommand", taskCommand);
                                taskCommand = redisService4.rightPop("RebuildTask:t:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            }
                        } else if (planScenes.getScenesLevel() == 2) {
                            redisService4.remove("Disable:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            redisService4.remove("workingTimeing:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            String taskCommand = redisService4.rightPop("RebuildTask:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            while (taskCommand != null) {
                                redisService5.lPush("taskCommand", taskCommand);
                                taskCommand = redisService4.rightPop("RebuildTask:p:" + planScenes.getScenesId() + ":" + plan.getTaskTypeId());
                            }
                        }
                        planScenes.setSoftDelete(1);
                        planScenesService.updateById(planScenes);
                    }
                }


            } else {
                //清除任务调度器
                redisService4.remove("Plan:" + plan.getType() + ":" + plan.getId());
            }


        } else {
            return ResultResponseBeanUtil.fail("计划未找到");
        }
        return ResultResponseBeanUtil.success("删除成功");
    }


    @ApiOperation(value = "计划状态设置")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setPlanStatus", method = RequestMethod.POST)
    public BaseOutput<String> setPlanStatus(HttpServletRequest request, @RequestBody PlanStatusInput input) {
        User user = UserUtils.getUser(request);
        log.info("【setPlanStatus】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
        Plan plan = planService.getById(input.getId());
        if (plan != null) {
            plan.setStatus(input.getStatus());
            if (plan.getTaskCreateType() == 0 || plan.getTaskCreateType() == 2) {
                if (input.getStatus() == 0) {
                    plan.setStartTime(new Date());
                    setXxlJobInfo(plan);
                    //任务调度器开启
                } else if (input.getStatus() == 1) {
                    //任务调度器停止
                }
            }
            planService.updateById(plan);

        } else {
            return ResultResponseBeanUtil.fail("计划未找到");
        }
        return ResultResponseBeanUtil.success("设置成功");
    }


    @ApiOperation(value = "查询计划可设置人员")
    @ResponseBody
    @RequestMapping(value = "/planUserList", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<PageOutput<User>> planUserList(HttpServletRequest request, @RequestBody PlanUserPageInput input) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【planUserList】查询计划可设置人员：user" + user.getName() + "，" + JSONObject.toJSONString(input));

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        QueryWrapper<UserProper> userProperQueryWrapper = WrapperUtils.getWrapper(false);
        userProperQueryWrapper.eq("district_id", input.getDistrictId());
        userProperQueryWrapper.le("type", 1);//0保洁1物业 <=1
        List<UserProper> userProperlist = userProperService.list(userProperQueryWrapper);
        List<Long> ids = userProperlist.stream().map(p -> p.getUserId()).collect(Collectors.toList());

        input.setDistrictId(null);
        QueryWrapper<User> userWrapper = WrapperUtils.getWrapper(false);
        WrapperUtils.beanToWrapper(userWrapper, input);
        userWrapper.in("id", ids);

        Page<User> pageList = new Page<>(input.getPage(), input.getRows());
        pageList = userService.page(pageList, userWrapper);
        List<User> userList = pageList.getRecords();
        PageOutput<User> output = new PageOutput<>();
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(userList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "已选中计划人员")
    @ResponseBody
    @RequestMapping(value = "/getPlanUserList", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<List<PlanUser>> getPlanUserList(HttpServletRequest request, @RequestParam Long planId) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        List<PlanUser> users = new ArrayList<>();
        if (planId == null || planId == 0) {
            return ResultResponseBeanUtil.success(users);
        }

        QueryWrapper<PlanUser> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("plan_id", planId);
        users = planUserService.list(wrapper);
        return ResultResponseBeanUtil.success(users);
    }


    @ApiOperation(value = "设备维护计划导出")
    @PostMapping("/planDevopsExport")
    public void planDevopsExport(HttpServletRequest request, HttpServletResponse response, @RequestBody PlanDevOpsPageInput input) throws IOException {
        QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
        User user = UserUtils.getUser(request);
        log.info("【planDevopsExport】user:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

//        Boolean aBoolean = authorityService.checkAuthorityIsagent(user.getAuthorityId());
//        wrapper = WrapperUtils.getByIsAgent(aBoolean, user.getAgentId(), wrapper);
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        wrapper.eq("type", 1);
        List<Plan> planList = planService.list(wrapper);
        List<PlanDevOpsExport> newList = new ArrayList<PlanDevOpsExport>();
        ArrayList<String> strings = new ArrayList<>();

        String[] columns = new String[strings.size()];
        strings.toArray(columns);

//        String[] columns = (String[]) strings.toArray();
        for (Plan plan : planList) {
            PlanDevOpsExport planExport = new PlanDevOpsExport();
            BeanUtils.copyProperties(plan, planExport);

            if (plan.getIsCross() == 1) {
                QueryWrapper<PlanScenes> sceneswrapper = WrapperUtils.getWrapper(false);
                sceneswrapper.eq("plan_id", plan.getId());
                List<PlanScenes> sceneslist = planScenesService.list(sceneswrapper);
                if (!sceneslist.isEmpty()) {
                    PlanScenes planScenes = sceneslist.get(0);
//                    if(planScenes.getScenesLevel()==1){
                    planExport.setSceneString(planScenes.getSuperiorGridName() + "->" + planScenes.getName());
//                    }else {
//                        planDevOpsPageOutput.setSceneString(planScenes.getSuperiorGridName()+"->"+planScenes.gets()+"->"+planScenes.getName());
//
//                    }
                }
            } else {
                planExport.setSceneString("-");

            }
            //时薪
            if (plan.getWageId() != null && plan.getWageId() > 0) {
                Wage wage = wageService.getById(plan.getWageId());
                planExport.setWageName(wage.getName());
            } else {
                planExport.setWageName("");

            }

            if (plan.getUserType() == 1) {
                QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
                userwrapper.eq("plan_id", plan.getId());
                List<PlanUser> userlist = planUserService.list(userwrapper);
//                ArrayList<Long> longs = new ArrayList<>();
                StringBuilder stringBuilder = new StringBuilder();
                for (PlanUser planUser : userlist) {
                    stringBuilder.append(planUser.getName()).append(",");
                }
                if (stringBuilder.length() > 0) {
                    planExport.setUserNames(stringBuilder.substring(0, stringBuilder.length() - 1));
                } else {
                    planExport.setUserNames("");

                }

            } else {
                planExport.setUserNames("不限人员");
            }
            newList.add(planExport);
        }
        String formattedDate = DateToConverter.getFormattedDate(new Date(), 10);
        ExcelUtil<PlanDevOpsExport> util = new ExcelUtil<PlanDevOpsExport>(PlanDevOpsExport.class);
        util.exportExcelByColumns(response, newList, "设备维护任务记录" + formattedDate, columns);
    }


    @ApiOperation(value = "指派计划导出")
    @PostMapping("/planAppointExport")
    public void planAppointExport(HttpServletRequest request, HttpServletResponse response, @RequestBody PlanPageInput input) throws IOException {
        QueryWrapper<Plan> wrapper = WrapperUtils.getWrapper(false);
        User user = UserUtils.getUser(request);
        log.info("【planAppointExport】user:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
        List<Long> planids = null;
        if (input.getScenes() != null && !input.getScenes().isEmpty()) {
            List<Scene> scenes = input.getScenes();
            QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
            pswrapper.eq("district_id", input.getDistrictId());
            HashSet<Long> firstIds = new HashSet<>();
            HashSet<Long> secondIds = new HashSet<>();

            for (Scene scene : scenes) {
                if (scene.getLevel() == 1) {
                    firstIds.add(scene.getId());
                } else if (scene.getLevel() == 2) {
                    secondIds.add(scene.getId());
                }
            }
            if (!firstIds.isEmpty() && !secondIds.isEmpty()) {
                pswrapper.and(wrapperq -> wrapperq.in("scenes_id", firstIds).eq("scenes_level", 1)).or().and(wrapperq -> wrapperq.in("scenes_id", secondIds).eq("scenes_level", 2));
            } else if (!firstIds.isEmpty()) {
                pswrapper.in("scenes_id", firstIds).eq("scenes_level", 1);
            } else if (!secondIds.isEmpty()) {
                pswrapper.in("scenes_id", secondIds).eq("scenes_level", 2);
            }
            pswrapper.groupBy("plan_id");
            List<PlanScenes> list = planScenesService.list(pswrapper);
            planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
            input.setScenes(null);

        }

        if (input.getUserIds() != null && !input.getUserIds().isEmpty()) {
            QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
            userwrapper.eq("district_id", input.getDistrictId());
            userwrapper.eq("user_id", input.getUserIds());
            List<PlanUser> list = planUserService.list(userwrapper);
            if (planids == null) {
                planids = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

            } else {
                List<Long> userPlan = list.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
                planids.addAll(userPlan);
            }
            input.setUserIds(null);
        }

        if (planids != null) {
            wrapper.in("id", planids);
        }


        wrapper = WrapperUtils.beanToWrapper(wrapper, input);


        List<PlanAppointExport> newList = new ArrayList<PlanAppointExport>();
        ArrayList<String> strings = new ArrayList<>();

        String[] columns = new String[strings.size()];
        strings.toArray(columns);

        List<Plan> planList = planService.list(wrapper);
//        String[] columns = (String[]) strings.toArray();
        for (Plan plan : planList) {
            PlanAppointExport planExport = new PlanAppointExport();
            BeanUtils.copyProperties(plan, planExport);
            QueryWrapper<PlanScenes> pswrapper = WrapperUtils.getWrapper(false);
            pswrapper.eq("district_id", input.getDistrictId());
            pswrapper.eq("plan_id", plan.getId());
            List<PlanScenes> pslist = planScenesService.list(pswrapper);
            if (pslist.isEmpty()) {
                planExport.setSceneString("");
            } else {
                StringBuilder stringBuilder = new StringBuilder();
                List<SceneTreeOutput> objects = new ArrayList<>();
                for (PlanScenes planScenes : pslist) {
                    SceneTreeOutput sceneTreeOutput = new SceneTreeOutput();
                    if (planScenes.getScenesId() > 0) {
                        if (planScenes.getScenesLevel() == 1) {
                            sceneTreeOutput.setId(planScenes.getScenesId() + "_s1");
                        } else if (planScenes.getScenesLevel() == 2) {
                            sceneTreeOutput.setId(planScenes.getScenesId() + "_s2");
                        }
                        sceneTreeOutput.setSceneId(planScenes.getScenesId());
                        sceneTreeOutput.setName(planScenes.getName());
                        sceneTreeOutput.setIsscene(1);
                        sceneTreeOutput.setDisable(false);
                        sceneTreeOutput.setLevel(planScenes.getScenesLevel());
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(planScenes.getName()).append(",");

                    } else if (planScenes.getScenesId() == 0) {
                        if (planScenes.getGridLevel() == 1) {
                            sceneTreeOutput.setId(planScenes.getBuildingId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getBuildingId());
                            sceneTreeOutput.setName(planScenes.getBuildingName());
                        } else if (planScenes.getGridLevel() == 2) {
                            sceneTreeOutput.setId(planScenes.getFloorId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getFloorId());
                            sceneTreeOutput.setName(planScenes.getFloor());
                        } else if (planScenes.getGridLevel() >= 3) {
                            sceneTreeOutput.setId(planScenes.getMultistageGridId() + "_" + planScenes.getGridLevel());
                            sceneTreeOutput.setGridId(planScenes.getMultistageGridId());
                            sceneTreeOutput.setName(planScenes.getMultistageGridName());
                        }
                        sceneTreeOutput.setLevel(planScenes.getGridLevel());
                        sceneTreeOutput.setIsscene(0);
                        stringBuilder.append(planScenes.getSuperiorGridName()).append(",");
                    }
                    objects.add(sceneTreeOutput);
                }
                if (stringBuilder.length() > 0) {
                    planExport.setSceneString(stringBuilder.substring(0, stringBuilder.length() - 1));

                } else {
                    planExport.setSceneString("");

                }
//                planPageOutput.setScenesList(objects);
            }

            if (plan.getUserType() == 1) {

                QueryWrapper<PlanUser> userwrapper = WrapperUtils.getWrapper(false);
                userwrapper.eq("district_id", input.getDistrictId());
                userwrapper.eq("plan_id", plan.getId());
                List<PlanUser> list = planUserService.list(userwrapper);
                StringBuffer stringBuffer = new StringBuffer();
                for (PlanUser planUser : list) {
                    stringBuffer.append(planUser.getName()).append(",");
                }
                if (stringBuffer.length() > 0) {
                    planExport.setUserNames(stringBuffer.substring(0, stringBuffer.length() - 1));

                } else {
                    planExport.setUserNames("");

                }

            } else {
                planExport.setUserNames("不限人员");
            }
            //时薪
            if (plan.getWageId() != null && plan.getWageId() > 0) {
                Wage wage = wageService.getById(plan.getWageId());
                planExport.setWageName(wage.getName());
            } else {
                planExport.setWageName("");

            }

            newList.add(planExport);
        }
        String formattedDate = DateToConverter.getFormattedDate(new Date(), 10);
        ExcelUtil<PlanAppointExport> util = new ExcelUtil<PlanAppointExport>(PlanAppointExport.class);
        util.exportExcelByColumns(response, newList, "突发指派任务记录" + formattedDate, columns);
    }


    @ApiOperation(value = "指派计划可设置人员")
    @ResponseBody
    @RequestMapping(value = "/appointPlanUserList", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<PageOutput<AppointUserOutput>> appointPlanUserList(HttpServletRequest request, @RequestBody PlanUserPageInput input) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【planUserList】查询计划可设置人员：user" + user.getName() + "，" + JSONObject.toJSONString(input));
        PageOutput<AppointUserOutput> output = new PageOutput<>();

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        QueryWrapper<User> userWrapper = WrapperUtils.getWrapper(false);
//        QueryWrapper<UserDistrictAttendance> userWorkWrapper = WrapperUtils.getWrapper(false);
        QueryWrapper<UserProper> userProperQueryWrapper = WrapperUtils.getWrapper(false);
        Long districtId = input.getDistrictId();
        userProperQueryWrapper.eq("district_id", districtId);
        userProperQueryWrapper.le("type", 1);//0保洁1物业 <=1
        List<UserProper> userProperlist = userProperService.list(userProperQueryWrapper);
        List<Long> ids = userProperlist.stream().map(p -> p.getUserId()).collect(Collectors.toList());
        if (ids != null && ids.size() > 0) {
            userWrapper.in("id", ids);
//            userWorkWrapper.in("user_id",ids);
//            userWorkWrapper.eq("district_id",input.getDistrictId());
        } else {
            return ResultResponseBeanUtil.success(output);
        }
        input.setDistrictId(null);
        WrapperUtils.beanToWrapper(userWrapper, input);


        Page<User> pageList = new Page<>(input.getPage(), input.getRows());
        pageList = userService.page(pageList, userWrapper);
        List<User> userList = pageList.getRecords();
        List<AppointUserOutput> appointuserList = new ArrayList<AppointUserOutput>();
        Date startTime = DateToConverter.getStartTime();
        for (User curuser : userList) {
            AppointUserOutput appointUserOutput = new AppointUserOutput();
            BeanUtils.copyProperties(curuser, appointUserOutput);
            QueryWrapper<TaskUser> taskUserWrapper = WrapperUtils.getWrapper(false);
            taskUserWrapper.gt("create_time", startTime);
            appointUserOutput.setUserNames(curuser.getName());
            taskUserWrapper.and(wrapperq -> wrapperq.eq("user_id", curuser.getId()).or().eq("user_id", curuser.getId()));
            taskUserWrapper.in("status", 3, 4, 5, 6);
            UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(districtId, curuser.getId());
            appointUserOutput.setWorkAtStatus(userDistrictAttendance.getWorkAtStatus());
            appointUserOutput.setWorkStatus(userDistrictAttendance.getWorkStatus());
            int totalcount = taskUserService.count(taskUserWrapper);
            taskUserWrapper.in("status", 3, 4);
            int taskworkCount = taskUserService.count(taskUserWrapper);
            appointUserOutput.setTaskTotalCount(totalcount);
            appointUserOutput.setTaskworkCount(taskworkCount);
            appointUserOutput.setTaskFinishCount(totalcount - taskworkCount);
            appointuserList.add(appointUserOutput);
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(appointuserList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "例行计划可设置班组")
    @ResponseBody
    @RequestMapping(value = "/getRoutinePlanWorkGroupList", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<PageOutput<PlanWorkGroupOutput>> getRoutinePlanWorkGroupList(HttpServletRequest request, @RequestBody PlanWorkGroupPageInput input) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【getRoutinePlanWorkGroupList】例行计划可设置班组：user" + user.getName() + "，" + JSONObject.toJSONString(input));
        PageOutput<PlanWorkGroupOutput> output = new PageOutput<>();

        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        QueryWrapper<WorkGroupToPrincipal> wgUserWrapper = WrapperUtils.getWrapper(false);
        QueryWrapper<WorkGroupToPrincipal> wgQueryWrapper = WrapperUtils.getWrapper(false);

        if (input.getPrincipalUserName() != null) {
            wgUserWrapper.eq("principal_flag", 1);
            wgUserWrapper.like("user_name", input.getPrincipalUserName());
            if (input.getWorkGroupName() != null) {
                wgUserWrapper.like("work_group_name", input.getWorkGroupName());
            }
            List<WorkGroupToPrincipal> list = workGroupToPrincipalService.list(wgUserWrapper);
            List<Long> wgtpids = list.stream().map(p -> p.getWorkGroupId()).collect(Collectors.toList());
            wgQueryWrapper.in("work_group_id", wgtpids);
            input.setPrincipalUserName(null);
        }
        WrapperUtils.beanToWrapper(wgQueryWrapper, input);
        wgQueryWrapper.groupBy("work_group_id");
        wgQueryWrapper.orderByAsc("work_group_id");
        wgQueryWrapper.select("work_group_id,work_group_name,GROUP_CONCAT(user_name) user_name,GROUP_CONCAT(if(principal_flag=1,user_name,'')) district_name");
        Page<WorkGroupToPrincipal> pageList = new Page<WorkGroupToPrincipal>(input.getPage(), input.getRows());
        List<WorkGroupToPrincipal> list = workGroupToPrincipalService.page(pageList, wgQueryWrapper).getRecords();

        List<PlanWorkGroupOutput> outputList = new ArrayList<PlanWorkGroupOutput>();
        Date startTime = DateToConverter.getStartTime();
        for (WorkGroupToPrincipal workGroupToPrincipal : list) {
            PlanWorkGroupOutput planWorkGroupOutput = new PlanWorkGroupOutput();

            planWorkGroupOutput.setWorkGroupId(workGroupToPrincipal.getWorkGroupId());
            planWorkGroupOutput.setWorkGroupName(workGroupToPrincipal.getWorkGroupName());
            planWorkGroupOutput.setUserNames(workGroupToPrincipal.getUserName());
            String replace = workGroupToPrincipal.getDistrictName().replace(",,", "");
            if (replace.length() > 0) {
                int first = 0;

                int end = replace.length() - 1;
                if (replace.indexOf(",") == 0) {
                    first = 1;
                }
                if (replace.lastIndexOf(",") == end) {
                    end--;
                }
                if (end > 0) {
                    planWorkGroupOutput.setPrincipalUserName(replace.substring(first, end));
                } else {
                    planWorkGroupOutput.setPrincipalUserName("");
                }
            } else {
                planWorkGroupOutput.setPrincipalUserName("");

            }

            outputList.add(planWorkGroupOutput);
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(outputList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "已选中计划班组")
    @ResponseBody
    @RequestMapping(value = "/getPlanWorkGroupList", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<List<PlanWorkGroupOutput>> getPlanWorkGroupList(HttpServletRequest request, @RequestParam Long planId) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        List<PlanWorkGroupOutput> list = new ArrayList<>();
        if (planId == null || planId == 0) {
            return ResultResponseBeanUtil.success(list);
        }

        QueryWrapper<PlanWorkGroup> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("plan_id", planId);
        List<PlanWorkGroup> querylist = planWorkGroupService.list(wrapper);
        for (PlanWorkGroup planWorkGroup : querylist
        ) {
            PlanWorkGroupOutput planWorkGroupOutput = new PlanWorkGroupOutput();
            planWorkGroupOutput.setPrincipalUserName(planWorkGroup.getNote());
            planWorkGroupOutput.setWorkGroupName(planWorkGroup.getWorkGroupName());
            planWorkGroupOutput.setWorkGroupId(planWorkGroup.getWorkGroupId());
            list.add(planWorkGroupOutput);
        }
        return ResultResponseBeanUtil.success(list);
    }


    @ApiOperation(value = "例行计划的集合信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/getPlanListInfo", method = RequestMethod.GET)
    public BaseOutput<PlanListInfoOutput> getPlanListInfo(HttpServletRequest request, @RequestParam Long planId) {

        QueryWrapper<PlanLogicLabel> mustWrapper = WrapperUtils.getWrapper(false);
        mustWrapper.eq("plan_id", planId);
        mustWrapper.eq("logic_type", 0);
        List<PlanLogicLabel> mustlist = planLogicLabelService.list(mustWrapper);
        List<Long> mustIds = mustlist.stream().map(label -> label.getLabelId()).collect(Collectors.toList());

        QueryWrapper<PlanLogicLabel> notWrapper = WrapperUtils.getWrapper(false);
        notWrapper.eq("plan_id", planId);
        notWrapper.eq("logic_type", 1);
        List<PlanLogicLabel> notlist = planLogicLabelService.list(notWrapper);
        List<Long> notIds = notlist.stream().map(label -> label.getLabelId()).collect(Collectors.toList());

        QueryWrapper<PlanObject> objectWrapper = WrapperUtils.getWrapper(false);
        objectWrapper.eq("plan_id", planId);
        List<PlanObject> objectlist = planObjectService.list(objectWrapper);
        Set<Long> objectIdSet = objectlist.stream().map(planObject -> planObject.getObjectId()).collect(Collectors.toSet());
        List<Long> objectIds = new ArrayList(objectIdSet);

        QueryWrapper<PlanOperation> operationWrapper = WrapperUtils.getWrapper(false);
        operationWrapper.eq("plan_id", planId);
        List<PlanOperation> operationlist = planOperationService.list(operationWrapper);
        List<PlanOperationOutput> operationoutlist = new ArrayList<>();
        for (PlanOperation planOperation : operationlist) {
            PlanOperationOutput planOperationOutput = new PlanOperationOutput();
            planOperationOutput.setId(planOperation.getOperationId());
            planOperationOutput.setName(planOperation.getOperationName());
            operationoutlist.add(planOperationOutput);
        }
//        List<Long> operationIds = operationlist.stream().map(label -> label.getOperationId()).collect(Collectors.toList());


        PlanListInfoOutput planListInfoOutput = new PlanListInfoOutput();
        planListInfoOutput.setMustLabelIds(mustIds);
        planListInfoOutput.setNotLabelIds(notIds);
        planListInfoOutput.setObjectIds(objectIds);
        planListInfoOutput.setOperationList(operationoutlist);
        return ResultResponseBeanUtil.success(planListInfoOutput);

    }


    @ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
    @ResponseBody
    @RequestMapping(value = "/inspectPlanList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<PlanPageOutput>> inspectPlanList(HttpServletRequest request, @RequestBody InspectPlanPageInput input) {
        log.info("【inspectPlanList】input:" + JSONObject.toJSONString(input));
        if (input.getDistrictId() == null) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        User user = UserUtils.getUser(request);
        PageOutput<PlanPageOutput> output = new PageOutput<PlanPageOutput>();
        Page<Plan> pageList = new Page<Plan>(input.getPage(), input.getRows());
        List<PlanPageOutput> outList = new ArrayList<PlanPageOutput>();
        QueryWrapper<Plan> planQueryWrapper = WrapperUtils.getWrapper(false);

        if (input.getCreateTimeStart() == null || input.getCreateTimeStart().trim().equals("")) {
//            return ResultResponseBeanUtil.fail("请选择查询开始时间");
        } else {
            planQueryWrapper.gt("create_time", input.getCreateTimeStart());
        }

        if (input.getCreateTimeEnd() == null || input.getCreateTimeEnd().trim().equals("")) {
//            return ResultResponseBeanUtil.fail("请选择查询结束时间");
        } else {
            planQueryWrapper.lt("create_time", input.getCreateTimeEnd());
        }
        planQueryWrapper.eq("type", 5);
        planQueryWrapper.eq("district_id", input.getDistrictId());

        if (input.getCircleType() != null) {
            planQueryWrapper.eq("circle_type", input.getCircleType());
        }
        if (input.getTaskName() != null) {
            planQueryWrapper.like("task_name", input.getTaskName());
        }
        if (input.getActionUserName() != null) {
            QueryWrapper<PlanWorkGroup> wrapperPWG = WrapperUtils.getWrapper(false);
            wrapperPWG.eq("district_id", input.getDistrictId());
            wrapperPWG.like("work_group_name", input.getActionUserName());
            List<PlanWorkGroup> groupList = planWorkGroupService.list(wrapperPWG);
            List<Long> planIds = groupList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
            QueryWrapper<PlanUser> wrapperUser = WrapperUtils.getWrapper(false);
            wrapperUser.like("name", input.getActionUserName());
            List<PlanUser> userList = planUserService.list(wrapperUser);

            planIds.addAll(userList.stream().map(p -> p.getPlanId()).collect(Collectors.toList()));
            if (planIds.isEmpty()) {
                output.setPage(pageList.getCurrent());
                output.setRecords(pageList.getTotal());
                output.setTotal(pageList.getPages());
                output.setRows(outList);
                return ResultResponseBeanUtil.success(output);
            } else {
                planQueryWrapper.in("id", planIds);
            }
        }

        if (StringUtil.isNotEmpty(input.getScene())) {
            Set<Long> planIds = getQueryCiteria(input);
            if (planIds.size() == 0) {
                return ResultResponseBeanUtil.success(output);
            } else {
                planQueryWrapper.in("id", planIds);
            }
            input.setScene(null);
        }

//
//        if (input.getScene() != null) {
//            QueryWrapper<PlanScenes> wrapperPS = WrapperUtils.getWrapper(false);
//            wrapperPS.eq("district_id", input.getDistrictId());
//            wrapperPS.eq("scenes_id", input.getScene().getSceneId());
//            wrapperPS.eq("scenes_level", input.getScene().getLevel());
//            wrapperPS.groupBy("plan_id");
//            List<PlanScenes> groupList = planScenesService.list(wrapperPS);
//            if (!groupList.isEmpty()) {
//                List<Long> planIds = groupList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
//                planQueryWrapper.in("id", planIds);
//            } else {
//                output.setPage(pageList.getCurrent());
//                output.setRecords(pageList.getTotal());
//                output.setTotal(pageList.getPages());
//                output.setRows(outList);
//                return ResultResponseBeanUtil.success(output);
//            }
//        }


        QueryWrapper<TaskInfo> task1QueryWrapper = WrapperUtils.getWrapper(false);
        task1QueryWrapper.eq("task_type", 5);
        task1QueryWrapper.eq("status", 4);
        task1QueryWrapper.eq("district_id", input.getDistrictId());
        task1QueryWrapper.groupBy("plan_id");
        List<TaskInfo> tasklist = taskInfoService.list(task1QueryWrapper);
        List<Long> workingPlanIds = tasklist.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

        if (input.getStatus() != null) {
            List<Integer> statusList = input.getStatus();
            if (statusList.size() == 2) {
                if (statusList.contains(1) && statusList.contains(0)) {
                    planQueryWrapper.eq("status", 0);
                }
//                else if(){
//
//                }
            } else if (statusList.size() == 1) {
                switch (statusList.get(0)) {
                    case 0:
                        planQueryWrapper.eq("status", 0);
                        if (workingPlanIds != null && !workingPlanIds.isEmpty()) {
                            planQueryWrapper.notIn("id", workingPlanIds);
                        }
                        break;
                    case 1:
                        planQueryWrapper.eq("status", 0);
                        if (workingPlanIds != null && !workingPlanIds.isEmpty()) {
                            planQueryWrapper.in("id", workingPlanIds);
                        } else {
                            planQueryWrapper.eq("id", 0);

                        }
                        break;
                    case 2:
                        planQueryWrapper.eq("status", 2);
                        break;
                    default:
                        break;
                }
            }


        }


        planQueryWrapper.orderByDesc("id");

        Page<Plan> page = planService.page(pageList, planQueryWrapper);
        List<Plan> planList = page.getRecords();

        if (planList.isEmpty()) {
            output.setPage(pageList.getCurrent());
            output.setRecords(pageList.getTotal());
            output.setTotal(pageList.getPages());
            output.setRows(outList);
            return ResultResponseBeanUtil.success(output);
        }

        List<Long> planIds = planList.stream().map(p -> p.getId()).collect(Collectors.toList());
        //userMap
        QueryWrapper<PlanUser> queryWrapperPU = WrapperUtils.getWrapper(false);
        queryWrapperPU.in("plan_id", planIds);
        queryWrapperPU.groupBy("plan_id");
        queryWrapperPU.select("plan_id,GROUP_CONCAT(distinct name order by name ASC) name");
        List<PlanUser> planUserlist = planUserService.list(queryWrapperPU);
        Map<Long, String> userMap = planUserlist.stream().collect(Collectors.toMap(PlanUser::getPlanId, PlanUser::getName));

        QueryWrapper<PlanWorkGroup> queryWrapperPWG = WrapperUtils.getWrapper(false);
        queryWrapperPWG.in("plan_id", planIds);
        queryWrapperPWG.groupBy("plan_id");
        queryWrapperPWG.select("plan_id,GROUP_CONCAT(distinct work_group_name order by work_group_name ASC) work_group_name");
        List<PlanWorkGroup> planWorkGroupList = planWorkGroupService.list(queryWrapperPWG);
        Map<Long, String> groupMap = planWorkGroupList.stream().collect(Collectors.toMap(PlanWorkGroup::getPlanId, PlanWorkGroup::getWorkGroupName));

        QueryWrapper<PlanScenes> queryWrapperPS = WrapperUtils.getWrapper(false);
        queryWrapperPS.in("plan_id", planIds);
        queryWrapperPS.groupBy("plan_id");
        queryWrapperPS.select("plan_id,GROUP_CONCAT(superior_grid_name,'',name) name");
        List<PlanScenes> planScenesList = planScenesService.list(queryWrapperPS);
        Map<Long, String> sceneMap = planScenesList.stream().collect(Collectors.toMap(PlanScenes::getPlanId, PlanScenes -> PlanScenes.getName()));

        QueryWrapper<TaskInfo> queryWrapperTask = WrapperUtils.getWrapper(false);
        queryWrapperTask.in("plan_id", planIds);
        queryWrapperTask.eq("status", 4);
        List<TaskInfo> taskInfoList = taskInfoService.list(queryWrapperTask);
        List<Long> planTaskId = taskInfoList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

        for (Plan plan : planList) {
            PlanPageOutput planPageOutput = new PlanPageOutput();
            BeanUtils.copyProperties(plan, planPageOutput);
//            planPageOutput.setId(plan.getId());
//            planPageOutput.setTaskName(plan.getTaskName());
//            planPageOutput.setStartTime(plan.getStartTime());
//            planPageOutput.setEndTime(plan.getEndTime());
//            planPageOutput.setActionStartTime(plan.getActionStartTime());
//            planPageOutput.setActionEndTime(plan.getActionEndTime());
//            planPageOutput.setActionTimeType(plan.getActionTimeType());
//            planPageOutput.setCreateName(plan.getCreateName());
//            planPageOutput.setCreateTime(plan.getCreateTime());
            planPageOutput.setActionTimeString(plan.getActionStartTime() + "-" + plan.getActionEndTime());
            String endTime;
            if (plan.getActionTimeType() == 0 || plan.getEndTime() == null) {
                endTime = "永久有效";
            } else {
                endTime = DateToConverter.getFormattedDate(plan.getEndTime(), 0);
            }
            planPageOutput.setDateString(DateToConverter.getFormattedDate(plan.getStartTime(), 0) + "-" + endTime);
            switch (plan.getCircleType()) {
                case 0:
                    planPageOutput.setCircleNoString("-");
                    break;
                case 1:
                    String circleString1 = plan.getCircleNo().replace(",", "/").replace("1", "周一").replace("2", "周二").replace("3", "周三").replace("4", "周四").replace("5", "周五").replace("6", "周六").replace("7", "周日");
                    planPageOutput.setCircleNoString(circleString1);
                    break;
                case 2:
                    String circleString2 = plan.getCircleNo().replace(",", "/").replace("99", "月末");
                    planPageOutput.setCircleNoString("每月" + circleString2);
                    break;
                default:
                    break;
            }
            if (userMap.containsKey(plan.getId())) {
                planPageOutput.setUserName(userMap.get(plan.getId()));
            }
            if (groupMap.containsKey(plan.getId())) {
                planPageOutput.setUserName(groupMap.get(plan.getId()));
            }

            if (sceneMap.containsKey(plan.getId())) {
                String s = sceneMap.get(plan.getId());
                planPageOutput.setScenesName(s.replace("->", ""));
            }
            if (plan.getStatus() == 2) {
                planPageOutput.setStatus(2);
            } else {
                if (planTaskId.contains(plan.getId())) {
                    planPageOutput.setStatus(1);
                } else {
                    planPageOutput.setStatus(0);
                }
            }
            if (plan.getWageId().longValue() == 0) {
                planPageOutput.setWageId(null);
            }
            outList.add(planPageOutput);
        }

        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(outList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "巡检计划导出")
    @PostMapping("/planInspectExport")
    public void planInspectExport(HttpServletRequest request, HttpServletResponse response, @RequestBody InspectPlanPageInput input) throws IOException {
        log.info("【planInspectExport】input:" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
//        PageOutput<PlanPageOutput> output = new PageOutput<PlanPageOutput>();
//        Page<Plan> pageList = new Page<Plan>(input.getPage(), input.getRows());
//        List<PlanPageOutput> outList = new ArrayList<PlanPageOutput>();
        List<PlanInspectExport> newList = new ArrayList<PlanInspectExport>();
        QueryWrapper<Plan> planQueryWrapper = WrapperUtils.getWrapper(false);
        planQueryWrapper.eq("type", 5);
        planQueryWrapper.eq("district_id", input.getDistrictId());
        if (input.getCreateTimeStart() == null || input.getCreateTimeStart().trim().equals("")) {
//            return ResultResponseBeanUtil.fail("请选择查询开始时间");
        } else {
            planQueryWrapper.gt("create_time", input.getCreateTimeStart());
        }

        if (input.getCreateTimeEnd() == null || input.getCreateTimeEnd().trim().equals("")) {
//            return ResultResponseBeanUtil.fail("请选择查询结束时间");
        } else {
            planQueryWrapper.lt("create_time", input.getCreateTimeEnd());
        }
        if (input.getCircleType() != null) {
            planQueryWrapper.eq("circle_type", input.getCircleType());
        }
        if (input.getTaskName() != null) {
            planQueryWrapper.like("task_name", input.getTaskName());
        }
        if (input.getActionUserName() != null) {
            QueryWrapper<PlanWorkGroup> wrapperPWG = WrapperUtils.getWrapper(false);
            wrapperPWG.eq("district_id", input.getDistrictId());
            wrapperPWG.like("work_group_name", input.getActionUserName());
            List<PlanWorkGroup> groupList = planWorkGroupService.list(wrapperPWG);
            List<Long> planIds = groupList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
            QueryWrapper<PlanUser> wrapperUser = WrapperUtils.getWrapper(false);
            wrapperUser.like("name", input.getActionUserName());
            List<PlanUser> userList = planUserService.list(wrapperUser);

            planIds.addAll(userList.stream().map(p -> p.getPlanId()).collect(Collectors.toList()));
            if (planIds.isEmpty()) {
                planQueryWrapper.eq("id", 0);

            } else {
                planQueryWrapper.in("id", planIds);
            }
        }

        if (StringUtil.isNotEmpty(input.getScene())) {
            Set<Long> planIds = getQueryCiteria(input);
            if (planIds.size() == 0) {
                return;
            } else {
                planQueryWrapper.in("id", planIds);
            }
            input.setScene(null);
        }


//        if (input.getScene() != null) {
//            QueryWrapper<PlanScenes> wrapperPS = WrapperUtils.getWrapper(false);
//            wrapperPS.eq("district_id", input.getDistrictId());
//            wrapperPS.eq("scenes_id", input.getScene().getSceneId());
//            wrapperPS.eq("scenes_level", input.getScene().getLevel());
//            wrapperPS.groupBy("plan_id");
//            List<PlanScenes> groupList = planScenesService.list(wrapperPS);
//            if (!groupList.isEmpty()) {
//                List<Long> planIds = groupList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());
//                planQueryWrapper.in("id", planIds);
//            } else {
//                planQueryWrapper.eq("id", 0);
//            }
//        }


        QueryWrapper<TaskInfo> task1QueryWrapper = WrapperUtils.getWrapper(false);
        task1QueryWrapper.eq("task_type", 5);
        task1QueryWrapper.eq("status", 4);
        task1QueryWrapper.eq("district_id", input.getDistrictId());
        task1QueryWrapper.groupBy("plan_id");
        List<TaskInfo> tasklist = taskInfoService.list(task1QueryWrapper);
        List<Long> workingPlanIds = tasklist.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

        if (input.getStatus() != null) {
            List<Integer> statusList = input.getStatus();
            if (statusList.size() == 2) {
                if (statusList.contains(1) && statusList.contains(0)) {
                    planQueryWrapper.eq("status", 0);
                }
//                else if(){
//
//                }
            } else if (statusList.size() == 1) {
                switch (statusList.get(0)) {
                    case 0:
                        planQueryWrapper.eq("status", 0);
                        if (workingPlanIds != null && !workingPlanIds.isEmpty()) {
                            planQueryWrapper.notIn("id", workingPlanIds);
                        }
                        break;
                    case 1:
                        planQueryWrapper.eq("status", 0);
                        if (workingPlanIds != null && !workingPlanIds.isEmpty()) {
                            planQueryWrapper.in("id", workingPlanIds);
                        } else {
                            planQueryWrapper.eq("id", 0);

                        }
                        break;
                    case 2:
                        planQueryWrapper.eq("status", 2);
                        break;
                    default:
                        break;
                }
            }


        }


        planQueryWrapper.orderByDesc("id");
        List<Plan> planList = planService.list(planQueryWrapper);

        if (!planList.isEmpty()) {


            List<Long> planIds = planList.stream().map(p -> p.getId()).collect(Collectors.toList());
            //userMap
            QueryWrapper<PlanUser> queryWrapperPU = WrapperUtils.getWrapper(false);
            queryWrapperPU.in("plan_id", planIds);
            queryWrapperPU.groupBy("plan_id");
            queryWrapperPU.select("plan_id,GROUP_CONCAT(distinct name order by name ASC) name");
            List<PlanUser> planUserlist = planUserService.list(queryWrapperPU);
            Map<Long, String> userMap = planUserlist.stream().collect(Collectors.toMap(PlanUser::getPlanId, PlanUser::getName));

            QueryWrapper<PlanWorkGroup> queryWrapperPWG = WrapperUtils.getWrapper(false);
            queryWrapperPWG.in("plan_id", planIds);
            queryWrapperPWG.groupBy("plan_id");
            queryWrapperPWG.select("plan_id,GROUP_CONCAT(distinct work_group_name order by work_group_name ASC) work_group_name");
            List<PlanWorkGroup> planWorkGroupList = planWorkGroupService.list(queryWrapperPWG);
            Map<Long, String> groupMap = planWorkGroupList.stream().collect(Collectors.toMap(PlanWorkGroup::getPlanId, PlanWorkGroup::getWorkGroupName));

            QueryWrapper<PlanScenes> queryWrapperPS = WrapperUtils.getWrapper(false);
            queryWrapperPS.in("plan_id", planIds);
            queryWrapperPS.groupBy("plan_id");
            queryWrapperPS.select("plan_id,GROUP_CONCAT(superior_grid_name,'',name) name");
            List<PlanScenes> planScenesList = planScenesService.list(queryWrapperPS);
            Map<Long, String> sceneMap = planScenesList.stream().collect(Collectors.toMap(PlanScenes::getPlanId, PlanScenes -> PlanScenes.getName()));

            QueryWrapper<TaskInfo> queryWrapperTask = WrapperUtils.getWrapper(false);
            queryWrapperTask.in("plan_id", planIds);
            queryWrapperTask.eq("status", 4);
            List<TaskInfo> taskInfoList = taskInfoService.list(queryWrapperTask);
            List<Long> planTaskId = taskInfoList.stream().map(p -> p.getPlanId()).collect(Collectors.toList());

            for (Plan plan : planList) {
                PlanInspectExport planInspectExport = new PlanInspectExport();
                BeanUtils.copyProperties(plan, planInspectExport);

                String endTime;
                if (plan.getActionTimeType() == 0 || plan.getEndTime() == null) {
                    endTime = "永久有效";
                } else {
                    endTime = DateToConverter.getFormattedDate(plan.getEndTime(), 0);
                }
                planInspectExport.setDateString(DateToConverter.getFormattedDate(plan.getStartTime(), 0) + "-" + endTime);
                switch (plan.getCircleType()) {
                    case 0:
                        planInspectExport.setCircleNoString("-");
                        break;
                    case 1:
                        String circleString1 = plan.getCircleNo().replace(",", "/").replace("1", "周一").replace("2", "周二").replace("3", "周三").replace("4", "周四").replace("5", "周五").replace("6", "周六").replace("7", "周日");
                        planInspectExport.setCircleNoString(circleString1);
                        break;
                    case 2:
                        String circleString2 = plan.getCircleNo().replace(",", "/").replace("99", "月末");
                        planInspectExport.setCircleNoString("每月" + circleString2);
                        break;
                    default:
                        break;
                }
                if (userMap.containsKey(plan.getId())) {
                    planInspectExport.setUserNames(userMap.get(plan.getId()));
                }
                if (groupMap.containsKey(plan.getId())) {
                    planInspectExport.setUserNames(groupMap.get(plan.getId()));
                }

                if (sceneMap.containsKey(plan.getId())) {
                    String s = sceneMap.get(plan.getId());
                    planInspectExport.setSceneString(s.replace("->", ""));
                }
                if (plan.getStatus() == 2) {
                    planInspectExport.setStatus(2);
                } else {
                    if (planTaskId.contains(plan.getId())) {
                        planInspectExport.setStatus(1);
                    } else {
                        planInspectExport.setStatus(0);
                    }
                }
                //时薪
                if (plan.getWageId() != null && plan.getWageId() > 0) {
                    Wage wage = wageService.getById(plan.getWageId());
                    planInspectExport.setWageName(wage.getName());
                } else {
                    planInspectExport.setWageName("");

                }
                planInspectExport.setActionTimeString(plan.getActionStartTime() + "-" + plan.getActionEndTime());
                newList.add(planInspectExport);
            }
            ArrayList<String> strings = new ArrayList<>();
            String[] columns = new String[strings.size()];
            strings.toArray(columns);
            String formattedDate = DateToConverter.getFormattedDate(new Date(), 10);
            ExcelUtil<PlanInspectExport> util = new ExcelUtil<PlanInspectExport>(PlanInspectExport.class);
            util.exportExcelByColumns(response, newList, "巡检计划" + formattedDate, columns);
        }

    }

    @ApiOperation(value = "计划工时设置")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setWageHout", method = RequestMethod.POST)
    public BaseOutput<String> setWageHout(HttpServletRequest request, @RequestBody WageSetInput input) {
        User user = UserUtils.getUser(request);
        log.info("【setWageHout】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getPlanId() == null || input.getPlanId() == 0) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        Plan plan = planService.getById(input.getPlanId());
        if (plan == null) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        setPlanWage(input.getWageId(), plan, input.getWageHour());
        planService.updateById(plan);
        return ResultResponseBeanUtil.success("操作成功");

    }

    @ApiOperation(value = "计划类优先级设置")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setPlanTaskOrder", method = RequestMethod.POST)
    public BaseOutput<String> setPlanTaskOrder(HttpServletRequest request, @RequestBody PlanTaskOrderInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【setPlanTaskOrder】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getPlanId() == null || input.getPlanId() == 0) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        Plan plan = planService.getById(input.getPlanId());
        if (plan == null) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        plan.setTaskOrder(input.getTaskOrder());
        try {
            planService.updateById(plan);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("操作失败");
        }
        return ResultResponseBeanUtil.success("操作成功");

    }
    @ApiOperation(value = "任务开关配置")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setPlanFlag", method = RequestMethod.POST)
    public BaseOutput<String> setPlanFlag(HttpServletRequest request, @RequestBody PlanFlagInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【setPlanTaskOrder】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

        if (input.getPlanId() == null || input.getPlanId() == 0) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        Plan plan = planService.getById(input.getPlanId());
        if (plan == null) {
            return ResultResponseBeanUtil.fail("计划异常");
        }
        plan.setTaskFlag(input.getTaskFlag());
        plan.setNoticeFlag(input.getNoticeFlag());
        try {
            planService.updateById(plan);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("操作失败");
        }
        return ResultResponseBeanUtil.success("操作成功");

    }


    //设置时薪
    private void setPlanWage(Long wageId, Plan plan, Double wageHour) {
        if (wageId != null && wageId > 0) {
            plan.setWageHour(wageHour);
            Wage wage = wageService.getById(wageId);
            if (wage != null) {
                plan.setPoint(plan.getWageHour() * wage.getPoint());
                plan.setWageId(wageId);
            }
        } else {
            plan.setWageHour(0.0);
            plan.setPoint(0.0);
            plan.setWageId(0L);
        }
    }


    private void setUserOrGroup(Plan plan, Integer userType, List<Long> userIds2, List<Long> workGroupIds) {
        if (userType == 1 && userIds2 != null && !userIds2.isEmpty()) {
            setPlanUser(userIds2, plan);
        }
        if (userType == 2 && workGroupIds != null && !workGroupIds.isEmpty()) {
            setPlanWorkGroup(workGroupIds, plan);
        }
        if (userType == 0) {
            setPlanUser(null, plan);
            setPlanWorkGroup(null, plan);
        }
    }


    /**
     * @param time   hh:MM:ss
     * @param status 1:start,2:end
     * @return
     */
    private Boolean getStringBaseOutput(String time, Integer status) {
        String[] times = time.split(":");
        String tronTime = times[2] + " " + times[1] + " " + times[0] + " ? * *";
        XxlJobInfo jobInfo2 = new XxlJobInfo();
        jobInfo2.setAddTime(new Date());
        jobInfo2.setAuthor("后台创建");
        jobInfo2.setExecutorBlockStrategy("SERIAL_EXECUTION");
        jobInfo2.setExecutorFailRetryCount(0);
        jobInfo2.setExecutorHandler("planDisableTask");
        jobInfo2.setExecutorParam(time + "--" + status);
        jobInfo2.setExecutorRouteStrategy("ROUND");// 轮训
        jobInfo2.setExecutorTimeout(3000);
        jobInfo2.setGlueRemark("GLUE代码初始化");
        jobInfo2.setGlueType("BEAN");
        jobInfo2.setScheduleType("CRON");
        jobInfo2.setMisfireStrategy("DO_NOTHING");
//        jobInfo2.setJobCron(tronTime);
        jobInfo2.setScheduleConf(tronTime);
        jobInfo2.setJobDesc("任务禁用:" + status);
//				{"code":200,"msg":null,"content":"18"}
        String returns = XxlJobUtil.addAndStart(jobInfo2);
        JSONObject returnJsonObject = JSON.parseObject(returns);
        int code = returnJsonObject.getIntValue("code");
        if (code == 200) {
            String taskId = returnJsonObject.getString("content");
            redisService4.set("planDisableTask:" + status.toString() + ":" + time, taskId);
            redisService4.set("devOpsDisable:" + status + ":" + time, status.toString());
            return true;
        } else {
            // 否则关掉上个任务
            return false;
        }
    }


    /**
     * @return
     */
    private Boolean setXxlJobInfo(Plan plan) {
        String jobName = "计划创建任务";
        String time = null;
        //生成任务触发时间
        //计划任务
        if (plan.getType() == 0) {
            Date curDate = new Date();
            Date curTime = DateToConverter.parseDate(DateToConverter.getDateAddOrSub(12, 2, curDate), 5);
            //由任务创建时判断
            if (plan.getTaskCreateType() == 0 && plan.getType() == 0) {
                try {
                    if (plan.getActionStartTime() != null && !plan.getActionStartTime().equals("")) {
                        String curTimeStr = DateToConverter.getFormattedDate(curTime, 0);
                        Date date = DateToConverter.parseDate(curTimeStr + " " + plan.getActionStartTime() + ":00", 5);
                        Date curdate = new Date();
                        if (curdate.getTime() < date.getTime()) {
                            time = DateToConverter.getCron(date);
                        } else {
                            time = DateToConverter.getCron(DateToConverter.parseDate(DateToConverter.getDateAddOrSub(5, 1, date), 5));
                        }
                    } else {
                        time = DateToConverter.getCron(curTime);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("【setXxlJobInfo】起始执行时间格式异常" + plan.getActionStartTime());
                }

            }
//            Integer circleType = plan.getCircleType();
//            if(circleType==0){
//                time = DateToConverter.getCron(plan.getStartTime());
//
//            }else if(circleType==1){
//
//            }else if(circleType==2){
//
//            }else{
//                return false;
//            }


            //指派任务 仅生成一次
        } else if (plan.getType() == 2) {
            time = DateToConverter.getCron(plan.getStartTime());
        }

//        String[] times = time.split(":");
//        String tronTime = times[2] + " " + times[1] + " " + times[0] + " ? * *";


        XxlJobInfo jobInfo2 = new XxlJobInfo();
        jobInfo2.setAddTime(new Date());
        jobInfo2.setAuthor("后台创建");
        jobInfo2.setExecutorBlockStrategy("SERIAL_EXECUTION");
        jobInfo2.setExecutorFailRetryCount(0);
        jobInfo2.setExecutorHandler("planCreateTask");
        jobInfo2.setExecutorParam(plan.getId().toString());
        jobInfo2.setExecutorRouteStrategy("ROUND");// 轮训
        jobInfo2.setExecutorTimeout(3000);
        jobInfo2.setGlueRemark("GLUE代码初始化");
        jobInfo2.setGlueType("BEAN");
        jobInfo2.setScheduleType("CRON");
        jobInfo2.setMisfireStrategy("DO_NOTHING");
//        jobInfo2.setJobCron(tronTime);
        jobInfo2.setScheduleConf(time);
        jobInfo2.setJobDesc(jobName + plan.getId());
//				{"code":200,"msg":null,"content":"18"}
        String returns = XxlJobUtil.addAndStart(jobInfo2);
        JSONObject returnJsonObject = JSON.parseObject(returns);
        int code = returnJsonObject.getIntValue("code");
        if (code == 200) {
            String taskId = returnJsonObject.getString("content");
            redisService4.set("Plan:" + plan.getType() + ":" + plan.getId(), taskId);
//            redisService4.set("planDisableTask:" + status.toString() + ":" + time, taskId);
//            redisService4.set("devOpsDisable:" + status + ":" + time, status.toString());
            return true;
        } else {
            // 否则关掉上个任务
            return false;
        }
    }

    private void setPlanUser(List<Long> userIds, Plan plan) {

        UpdateWrapper<PlanUser> userWrapper = Wrappers.update();
        userWrapper.set("soft_delete", 1);
        userWrapper.eq("plan_id", plan.getId());
        userWrapper.eq("soft_delete", 0);
        planUserService.update(userWrapper);

        if (plan.getUserType() == 1 && userIds != null && !userIds.isEmpty()) {
            ArrayList<PlanUser> planUserlist = new ArrayList<>();
            for (Long userid : userIds) {
                PlanUser planUser = new PlanUser();
                planUser.setAgentId(plan.getAgentId());
                planUser.setPropertyId(plan.getPropertyId());
                planUser.setDistrictId(plan.getDistrictId());
                planUser.setDistrictName(plan.getDistrictName());
                planUser.setUserId(userid);
                User curuser = userService.getById(userid);
                if (curuser == null) {
                    log.info("【setPlanUser】plan：" + plan.getId() + "用户id:" + userid + "为null");
                    continue;
                }
                planUser.setApprole(curuser.getApprole());
                planUser.setName(curuser.getName());
                planUser.setMobile(curuser.getMobile());
                planUser.setPlanId(plan.getId());
                planUser.setCreateTime(plan.getCreateTime());
                planUserlist.add(planUser);
            }
            planUserService.saveBatch(planUserlist);
        }
    }

    private void setPlanWorkGroup(List<Long> workGroupIds, Plan plan) {

        UpdateWrapper<PlanWorkGroup> workGroupWrapper = Wrappers.update();
        workGroupWrapper.set("soft_delete", 1);
        workGroupWrapper.eq("plan_id", plan.getId());
        workGroupWrapper.eq("soft_delete", 0);
        planWorkGroupService.update(workGroupWrapper);
        if (plan.getUserType() == 2 && workGroupIds != null && !workGroupIds.isEmpty()) {
            ArrayList<PlanWorkGroup> planworkGrouplist = new ArrayList<>();

            for (Long workGroupid : workGroupIds) {
                PlanWorkGroup planWorkGroup = new PlanWorkGroup();

                QueryWrapper<WorkGroupToPrincipal> wgQueryWrapper = WrapperUtils.getWrapper(false);
                wgQueryWrapper.eq("work_group_id", workGroupid);
                //仅负责人
                wgQueryWrapper.eq("principal_flag", 1);
                wgQueryWrapper.groupBy("work_group_id");
                wgQueryWrapper.orderByAsc("work_group_id");
                wgQueryWrapper.select("work_group_id,work_group_name,GROUP_CONCAT(user_name) user_name,GROUP_CONCAT(if(principal_flag=1,user_name,'')) district_name");
                List<WorkGroupToPrincipal> list = workGroupToPrincipalService.list(wgQueryWrapper);
                if (list.isEmpty()) {
                    log.info("【setPlanWorkGroup】planId:" + plan.getId() + "新增班组：" + workGroupid + "负责人未找到");
                    planWorkGroup.setNote("");
                    WorkGroup workGroup = workGroupService.getById(workGroupid);
                    if (workGroup == null) {
                        continue;
                    } else {
                        planWorkGroup.setWorkGroupName(workGroup.getWorkGroupName());

                    }

//                    continue;
                } else {
                    WorkGroupToPrincipal workGroupToPrincipal = list.get(0);
                    planWorkGroup.setWorkGroupName(workGroupToPrincipal.getWorkGroupName());
                    planWorkGroup.setNote(workGroupToPrincipal.getUserName());
                }
                planWorkGroup.setAgentId(plan.getAgentId());
                planWorkGroup.setDistrictId(plan.getDistrictId());
                planWorkGroup.setPropertyId(plan.getPropertyId());
                planWorkGroup.setAgentName(plan.getAgentName());
                planWorkGroup.setDistrictName(plan.getDistrictName());
                planWorkGroup.setPropertyName(plan.getPropertyName());
                planWorkGroup.setPlanId(plan.getId());
                planWorkGroup.setWorkGroupId(workGroupid);


                planworkGrouplist.add(planWorkGroup);
            }
            planWorkGroupService.saveBatch(planworkGrouplist);
        }
    }

//
//    private void setPlanLogicLabel(Plan plan, List<Long> labelIds, Integer logicType) {
//        UpdateWrapper<PlanLogicLabel> delWrapper = Wrappers.update();
//        delWrapper.set("soft_delete", 1);
//        delWrapper.eq("plan_id", plan.getId());
//        delWrapper.eq("soft_delete", 0);
//        delWrapper.eq("logic_type", logicType);
//        planLogicLabelService.update(delWrapper);
//
//        if (labelIds != null && !labelIds.isEmpty()) {
//            QueryWrapper<LabelManage> lablewrapper = WrapperUtils.getWrapper(false);
//            lablewrapper.eq("district_id", plan.getDistrictId());
//            lablewrapper.in("id", labelIds);
//            List<LabelManage> labellist = labelManageService.list(lablewrapper);
//            for (LabelManage labelManage : labellist) {
//                PlanLogicLabel planLogicLabel = new PlanLogicLabel();
//                BeanUtils.copyProperties(labelManage, planLogicLabel, "id");
//                planLogicLabel.setPlanId(plan.getId());
//                planLogicLabel.setLogicType(logicType);
//                planLogicLabel.setLabelId(labelManage.getId());
//                planLogicLabelService.save(planLogicLabel);
//            }
//        }
//    }


    private void setWorkingTiming(Integer workingTiming, PlanScenes planScenes, Long taskTypeId) {
        if (planScenes.getScenesLevel() == 1) {
            redisService4.set("workingTimeing:t:" + planScenes.getScenesId() + ":" + taskTypeId, workingTiming.toString());
        } else if (planScenes.getScenesLevel() == 2) {
            redisService4.set("workingTimeing:p:" + planScenes.getScenesId() + ":" + taskTypeId, workingTiming.toString());
        }
    }


    /**
     * @param input
     * @param plan
     * @param scene 暂时不用
     */
    private Set<Long> setObject(PlanInsert input, Plan plan, Scene scene) {
        UpdateWrapper<PlanObject> objectWrapper = Wrappers.update();
        objectWrapper.set("soft_delete", 1);
        objectWrapper.eq("plan_id", plan.getId());
//        objectWrapper.eq("object_id", input.getObjectIds());
        objectWrapper.eq("soft_delete", 0);
        planObjectService.update(objectWrapper);
        List<PlanObject> planObjects = new ArrayList<>();
        Set<Long> curobjectIds = new HashSet<>();

        if (input.getObjectIds() != null && !input.getObjectIds().isEmpty()) {
            List<Long> objectIds = input.getObjectIds();

            if (scene == null) {

                QueryWrapper<Object> objectQueryWrapper = WrapperUtils.getWrapper(false);
                objectQueryWrapper.in("id", objectIds);
                List<Object> objectlist = objectService.list(objectQueryWrapper);
                for (Object object : objectlist) {
                    PlanObject planObject = new PlanObject();
                    planObject.setObjectId(object.getId());
                    planObject.setObjectLevel(object.getLevel());
                    planObject.setObjectName(object.getName());
                    planObject.setObjectParentId(object.getParentId());
                    planObject.setObjectParentName(object.getParentName());
                    planObject.setPlanId(plan.getId());
                    planObjects.add(planObject);
                }
            } else {
                QueryWrapper<SceneObject> objectQueryWrapper = WrapperUtils.getWrapper(false);
                objectQueryWrapper.in("object_id", objectIds);
                objectQueryWrapper.eq("scenes_id", scene.getId());
                objectQueryWrapper.eq("scenes_level", scene.getLevel());
                List<SceneObject> objectlist = sceneObjectService.list(objectQueryWrapper);
                for (SceneObject object : objectlist) {
                    PlanObject planObject = new PlanObject();
                    planObject.setObjectId(object.getObjectId());
                    planObject.setObjectLevel(object.getLevel());
                    planObject.setObjectName(object.getObjectName());
                    planObject.setObjectParentId(object.getObjectParentId());
                    planObject.setObjectParentName(object.getObjectParentName());
                    planObject.setPlanId(plan.getId());
                    planObjects.add(planObject);
                    curobjectIds.add(object.getObjectId());
                }
            }
            planObjectService.saveBatch(planObjects);
        }
        return curobjectIds;
    }

    private void setOperation(PlanInsert input, Plan plan, Set<Long> objectIds) {
        UpdateWrapper<PlanOperation> objectWrapper = Wrappers.update();
        objectWrapper.set("soft_delete", 1);
        objectWrapper.eq("plan_id", plan.getId());
//        objectWrapper.eq("object_id", input.getObjectIds());
        objectWrapper.eq("soft_delete", 0);
        planOperationService.update(objectWrapper);

        if (input.getOperationIds() != null && !input.getOperationIds().isEmpty()) {
            List<Long> operationIds = input.getOperationIds();
            QueryWrapper<Operation> objectQueryWrapper = WrapperUtils.getWrapper(false);
            objectQueryWrapper.in("id", operationIds);
            if (objectIds != null) {
                if (objectIds.size() > 0) {
                    objectQueryWrapper.in("object_id", objectIds);
                } else {
                    log.info("【setOperation】未找到相关对象");
                    return;
                }
            }
            List<Operation> objectlist = operationService.list(objectQueryWrapper);
            List<PlanOperation> planOperations = new ArrayList<>();

            for (Operation operation : objectlist) {
                PlanOperation planOperation = new PlanOperation();
                planOperation.setOperationToolIds(operation.getToolIds());
                planOperation.setOperationToolNames(operation.getToolNames());
                planOperation.setOperationMethod(operation.getMethod());
                planOperation.setOperationName(operation.getName());
                planOperation.setOperationStandard(operation.getStandard());
                planOperation.setPlanId(plan.getId());
                planOperation.setOperationId(operation.getId());
                planOperations.add(planOperation);
            }
            planOperationService.saveBatch(planOperations);
        }
    }


    private void setLabel(Plan plan, List<Long> mustLabelIds, Integer type) {
        UpdateWrapper<PlanLogicLabel> mustWrapper = Wrappers.update();
        mustWrapper.set("soft_delete", 1);
        mustWrapper.eq("plan_id", plan.getId());
        mustWrapper.eq("logic_type", type);
        mustWrapper.eq("soft_delete", 0);
        planLogicLabelService.update(mustWrapper);
        if (mustLabelIds != null && !mustLabelIds.isEmpty()) {
            QueryWrapper<LabelManage> labelManageQueryWrapper = WrapperUtils.getWrapper(false);
            labelManageQueryWrapper.eq("district_id", plan.getDistrictId());
            labelManageQueryWrapper.in("id", mustLabelIds);
            List<LabelManage> curlist = labelManageService.list(labelManageQueryWrapper);
            List<PlanLogicLabel> planLogicLabels = new ArrayList<>();
            for (LabelManage labelManage : curlist) {
                PlanLogicLabel planLogicLabel = new PlanLogicLabel();
                planLogicLabel.setAgentId(plan.getAgentId());
                planLogicLabel.setPropertyId(plan.getPropertyId());
                planLogicLabel.setDistrictId(plan.getDistrictId());
                planLogicLabel.setLabelId(labelManage.getId());
                planLogicLabel.setLabelName(labelManage.getLabelName());
                planLogicLabel.setLogicType(type);
                planLogicLabel.setPlanId(plan.getId());
                planLogicLabel.setColorValue(labelManage.getColorValue());
                planLogicLabels.add(planLogicLabel);
            }
            if (!planLogicLabels.isEmpty()) {
                planLogicLabelService.saveBatch(planLogicLabels);
            }
        }
    }

    private void setPlanScenes(Plan plan, List<PlanScenes> planSceneslist, Scene scene) {
        PlanScenes planScenes = new PlanScenes();
        Toilet toilet = null;
        Positions positions = null;
        if (scene.getLevel() == 1) {
            toilet = toiletService.getById(scene.getId());
            BeanUtils.copyProperties(toilet, planScenes);
            planScenes.setScenesId(toilet.getId());
            if (plan.getTaskCreateType() == 1) {
                redisService4.set("UserCount:t:" + scene.getId() + ":" + plan.getId(), plan.getActionCount().toString());
                redisService4.add("UserCount:t:" + scene.getId(), plan.getId().toString());
            }

        } else if (scene.getLevel() == 2) {
            positions = positionsService.getById(scene.getId());
            BeanUtils.copyProperties(positions, planScenes);
            planScenes.setScenesId(positions.getId());
            if (plan.getTaskCreateType() == 1) {
                redisService4.set("UserCount:p:" + scene.getId() + ":" + plan.getId(), plan.getActionCount().toString());
                redisService4.add("UserCount:p:" + scene.getId(), plan.getId().toString());

            }
        }
        planScenes.setId(null);
        planScenes.setPlanId(plan.getId());
        planScenes.setTaskTypeId(plan.getTaskTypeId());
        planScenes.setCreateTime(new Date());
        planSceneslist.add(planScenes);
    }


    /********
     * 查询列表和导出统一处理查询条件
     *
     * @param input
     * @return
     */
    private Set<Long> getQueryCiteria(InspectPlanPageInput input) {
        Set<Long> planIds = new HashSet<Long>();
        List<GridAndSceneInput> gridAndScenes = input.getScene();
        for (GridAndSceneInput gridAndSceneInput : gridAndScenes) {
            QueryWrapper<PlanScenes> wrapperTaskScenes = WrapperUtils.getWrapper(false);
            wrapperTaskScenes.eq("district_id", input.getDistrictId());
//				@ApiModelProperty("网格或场景级别")
            Integer level = gridAndSceneInput.getLevel();
//				@ApiModelProperty(value = "网格ID")
            Long gridId = gridAndSceneInput.getGridId();
//				@ApiModelProperty(value = "场景ID")
            Long sceneId = gridAndSceneInput.getSceneId();
//				@ApiModelProperty(value = "是否场景，0:否;1:是")
            Integer isscene = gridAndSceneInput.getIsscene();
            if (isscene == 0) {
                switch (level) {
                    case 1:
                        wrapperTaskScenes.eq("building_id", gridId);
                        break;
                    case 2:
                        wrapperTaskScenes.eq("floor_id", gridId);
                        break;
                    default:
                        wrapperTaskScenes.eq("multistage_grid_id", gridId);
                        break;
                }
                wrapperTaskScenes.eq("grid_level", level);
            } else {
                switch (level) {
                    case 1:
                        wrapperTaskScenes.eq("scenes_id", sceneId);
                        break;
                    case 2:
                        wrapperTaskScenes.eq("scenes_id", sceneId);
                        break;
                }
                wrapperTaskScenes.eq("scenes_level", level);
            }
//			@ApiModelProperty(value = "任务生成时间")
//			private String createTimeStart;
            if (StringUtil.isNotEmpty(input.getCreateTimeStart())) {
                wrapperTaskScenes.ge("create_time", input.getCreateTimeStart());
                wrapperTaskScenes.le("create_time", input.getCreateTimeEnd());
            }
            List<PlanScenes> taskScenes = planScenesService.list(wrapperTaskScenes);
            planIds.addAll(taskScenes.stream().map(taskScen -> taskScen.getPlanId()).collect(Collectors.toSet()));
        }
        return planIds;
    }


}
