package xiaoqu.home.open.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import xiaoqu.home.open.entity.TaskCommandInfo;
import xiaoqu.home.open.entity.TaskPlanEntity;
import xiaoqu.home.open.model.db1.Positions;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db1.UserDistrictAttendance;
import xiaoqu.home.open.model.db1.UserProper;
import xiaoqu.home.open.model.db2.*;
import xiaoqu.home.open.publicBean.MessageNotification;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.PositionsService;
import xiaoqu.home.open.service.db1.UserDistrictAttendanceService;
import xiaoqu.home.open.service.db1.UserProperService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.*;
import xiaoqu.home.open.utils.DateToConverter;
import xiaoqu.home.open.utils.WrapperUtils;

import java.lang.Object;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 任务相关设置
 * 1,任务人员派单
 * 2,任务系统过期处理
 * 3,任务完成后逻辑处理
 * 4,任务重派发
 * 5,任务状态变更临期队列去除
 * 6,任务临期变更
 * 7,巡检任务人员派单
 * 8,上报任务人员派单
 * 9,设备维护类任务自动完成
 */
@Component
@Slf4j(topic = "task")
public class TaskCorrelationSetTask {
    //    @Autowired
//    private XxlJobUtil xxlJobUtil;
    @Autowired
    private RedisService4 redisService4;
    @Autowired
    private UserDistrictAttendanceService userDistrictAttendanceService;
    @Autowired
    private PlanService planService;
    @Autowired
    private RedisService5 redisService5;
    @Autowired
    private UserService userService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private PlanUserService planUserService;
    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private UserProperService userProperService;
    @Autowired
    private PlanWorkGroupService planWorkGroupService;
    @Autowired
    private WorkGroupToPrincipalService workGroupToPrincipalService;
    @Autowired
    private PlanScenesService planScenesService;
    @Autowired
    private PlanLogicLabelService planLogicLabelService;
    @Autowired
    private UserToLabelService userToLabelService;
    @Autowired
    private TaskScenesService taskScenesService;
    @Autowired
    private TaskStatusLogService taskStatusLogService;
    @Autowired
    private UserToServiceAreaService userToServiceAreaService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private EscalationUserService escalationUserService;

    @Autowired
    private EscalationServiceAreaService escalationServiceAreaService;

    @Autowired
    private UserToMatterService userToMatterService;
    @Autowired
    private PositionsService positionsService;
    @Autowired
    private TaskTypeService taskTypeService;
    @Autowired
    private TaskDistrictParamService taskDistrictParamService;


    /**
     * 1
     * 执行人员派单-推送任务
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskUserCreate() {
        String taskCommand = redisService4.rightPop("taskUserQueue");
        while (taskCommand != null) {
            log.info("【taskUserCreate】"+taskCommand);

            Date date = new Date();
            TaskPlanEntity taskPlanEntity = JSONObject.parseObject(taskCommand, TaskPlanEntity.class);
            TaskInfo taskInfo = taskPlanEntity.getTaskInfo();
            Plan plan = taskPlanEntity.getPlan();
            if (plan == null && taskInfo.getTaskType() == 1 && taskInfo.getStatus() <= 2) {
                //仅初次派单
                plan = new Plan();
                plan.setUserType(0);
                plan.setType(1);
                plan.setIsCross(0);
                plan.setDistrictId(taskInfo.getDistrictId());
                plan.setActionTimeType(0);
                plan.setWorkingTiming(40);
                plan.setRedundanceTiming(0);
                plan.setReadyTiming(0);
                plan.setExpireTiming(0);
                plan.setTransitionTiming(0);
            }

            List<Long> userIds = null;
            boolean autoTaskTakeFlag = false;
            Boolean appointUserflag = false;

            String userAppointFlag = redisService5.hmGet("Dictionary", "UserAppointFlag") != null ? redisService5.hmGet("Dictionary", "UserAppointFlag").toString() : null;
            if (taskInfo.getTaskType() == 2 || (taskInfo.getTaskType() == 0 && taskInfo.getUserStatus() == 1)) {
                autoTaskTakeFlag = true;
            }
            if (userAppointFlag != null && userAppointFlag.equals("1")) {


                switch (plan.getUserType()) {
                    case 0:
                        QueryWrapper<UserProper> wrapperUP = WrapperUtils.getWrapper(false);
                        wrapperUP.eq("district_id", plan.getDistrictId());
                        wrapperUP.in("type", 0, 1);// 保洁和物业
                        List<UserProper> userPropers = userProperService.list(wrapperUP);
                        userIds = userPropers.stream().map(p -> p.getUserId()).collect(Collectors.toList());


                        break;
                    case 1:
                        QueryWrapper<PlanUser> wrapperPU = WrapperUtils.getWrapper(false);
                        wrapperPU.eq("plan_id", plan.getId());
                        List<PlanUser> planUserList = planUserService.list(wrapperPU);
                        if (planUserList.size() == 1) {
                            autoTaskTakeFlag = true;
                        }
                        userIds = planUserList.stream().map(PlanUser::getUserId).collect(Collectors.toList());
                        break;
                    case 2:
                        QueryWrapper<PlanWorkGroup> wrapperPWG = WrapperUtils.getWrapper(false);
                        wrapperPWG.eq("plan_id", plan.getId());
                        List<PlanWorkGroup> planWorkGroupList = planWorkGroupService.list(wrapperPWG);
                        if (!planWorkGroupList.isEmpty()) {
                            List<Long> groupIds = planWorkGroupList.stream().map(PlanWorkGroup::getWorkGroupId).collect(Collectors.toList());
                            QueryWrapper<WorkGroupToPrincipal> wrapperWGP = WrapperUtils.getWrapper(false);
                            wrapperWGP.in("work_group_id", groupIds);
                            wrapperWGP.orderByDesc("principal_flag");
                            wrapperWGP.groupBy("user_id");
                            List<WorkGroupToPrincipal> workGroupToPrincipals = workGroupToPrincipalService.list(wrapperWGP);
                            List<Long> curUserIdList = new ArrayList<>();
                            StringBuilder principalName = new StringBuilder();
                            for (WorkGroupToPrincipal workGroupToPrincipal : workGroupToPrincipals) {
                                curUserIdList.add(workGroupToPrincipal.getUserId());
                                if (workGroupToPrincipal.getPrincipalFlag() == 1) {
                                    principalName.append(workGroupToPrincipal.getUserName()).append(",");
                                }
                            }
                            if (principalName.length() > 0) {
                                taskInfo.setUploadManageUser(principalName.substring(0, principalName.length() - 1));
                            }


                            userIds = workGroupToPrincipals.stream().map(WorkGroupToPrincipal::getUserId).collect(Collectors.toList());
                        }
                        break;
                    default:
                        break;
                }
                if (userIds == null || userIds.isEmpty()) {
                    //未匹配到人员
                    setTaskStatusLog(date, taskInfo, -1, "任务派单筛选未找到匹配人员(userAppointFlag)");
                    taskCommand = redisService4.rightPop("taskUserQueue");
                    continue;
                }
            }


            //作用域
            String userAreaFlag = redisService5.hmGet("Dictionary", "UserAreaFlag") != null ? redisService5.hmGet("Dictionary", "UserAreaFlag").toString() : null;
            if (userAreaFlag != null && userAreaFlag.equals("1") && plan.getType() != 2) {

                if (plan.getIsCross() == 0) {

                    List<Long> userAreaList = new ArrayList<>();
                    QueryWrapper<TaskScenes> wrapperPS = WrapperUtils.getWrapper(false);
                    wrapperPS.eq("task_id", taskInfo.getId());
                    List<TaskScenes> listTS = taskScenesService.list(wrapperPS);
                    if (listTS.isEmpty()) {
                        setTaskStatusLog(date, taskInfo, -1, "任务未找到作用域(UserAreaFlag)：" + userAreaFlag);
                        taskCommand = redisService4.rightPop("taskUserQueue");
                        continue;

                    }
                    for (TaskScenes taskScenes : listTS) {
                        QueryWrapper<UserToServiceArea> wrapperUTSA = WrapperUtils.getWrapper(false);
                        wrapperUTSA.in("user_id", userIds);
                        wrapperUTSA.eq("service_area_id", taskScenes.getScenesId());
                        //斤场景
                        wrapperUTSA.eq("service_type", 1);

                        wrapperUTSA.eq("grid_scenes_level", taskScenes.getScenesLevel());
                        List<UserToServiceArea> utsalist = userToServiceAreaService.list(wrapperUTSA);
                        List<Long> curUserList = utsalist.stream().map(UserToServiceArea::getUserId).collect(Collectors.toList());
                        userAreaList.addAll(curUserList);
                    }
                    userIds = userAreaList;
                }
                if (userIds == null || userIds.isEmpty()) {
                    //未匹配到人员
                    setTaskStatusLog(date, taskInfo, -1, "任务派单筛选未找到匹配人员(userAreaFlag):" + userAreaFlag);
                    taskCommand = redisService4.rightPop("taskUserQueue");
                    continue;
                }
            }


            //上班校验
            //公司级转站点级
            QueryWrapper<TaskDistrictParam> wrapperTDP = WrapperUtils.getWrapper(false);
            wrapperTDP.eq("district_id", plan.getDistrictId());
//            wrapperTDP.eq("status", 1);

            TaskDistrictParam taskDistrictParam = taskDistrictParamService.getOne(wrapperTDP);
            if(taskDistrictParam==null){
                String userDutyFlag = redisService5.hmGet("Dictionary", "UserDutyFlag") != null ? redisService5.hmGet("Dictionary", "UserDutyFlag").toString() : null;
                taskDistrictParam = new TaskDistrictParam();
                taskDistrictParam.setDutyTaskFlag(Integer.getInteger(userDutyFlag));
            }

            if (taskDistrictParam.getDutyTaskFlag()==1 && plan.getType() != 2) {
                //原20220616 包含相关，后221028注释，20240603 再次使用
//                QueryWrapper<User> wrapperUser = WrapperUtils.getWrapper(false);
//                wrapperUser.eq("work_status", 0);
//                //排除休息
//                wrapperUser.notIn("work_at_status", 3);
//                wrapperUser.in("id", userIds);
//                List<User> userlist = userService.list(wrapperUser);
//                userIds = userlist.stream().map(User::getId).collect(Collectors.toList());

                ArrayList<Long> userIdlist = new ArrayList<Long>();
                for (Long userId : userIds) {
                    //2240611 取消休息验证，拿出独立验证
                    UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(taskInfo.getDistrictId(), userId);
                    if (userDistrictAttendance.getWorkStatus() == 0) {
                        userIdlist.add(userId);
                    }
                }
                userIds = userIdlist;
                if (userIds == null || userIds.isEmpty()) {
                    //未匹配到人员
                    setTaskStatusLog(date, taskInfo, -1, "任务派单筛选未找到已上班人员(dutyTaskFlag1)" + taskDistrictParam.getDutyTaskFlag());
                    taskCommand = redisService4.rightPop("taskUserQueue");
                    continue;
                }
            }

            //原20220616 包含相关，后221028注释，20240603 再次使用，不与上下班关联，独立使用
            {
                QueryWrapper<UserDistrictAttendance> wrapperUser = WrapperUtils.getWrapper(false);
                //排除休息
                wrapperUser.notIn("work_at_status", 3);
                wrapperUser.eq("district_id", taskInfo.getDistrictId());
                wrapperUser.in("user_id", userIds);
                List<UserDistrictAttendance> userlist = userDistrictAttendanceService.list(wrapperUser);
                userIds = userlist.stream().map(UserDistrictAttendance::getUserId).collect(Collectors.toList());
                if (userIds == null || userIds.isEmpty()) {
                    //未匹配到人员
                    setTaskStatusLog(date, taskInfo, -1, "任务派单筛选未找到不休息的工作人员");
                    taskCommand = redisService4.rightPop("taskUserQueue");
                    continue;
                }
            }


// && !userIds.isEmpty()
            String logicFlag = redisService5.hmGet("Dictionary", "LogicFlag") != null ? redisService5.hmGet("Dictionary", "LogicFlag").toString() : null;
            if (logicFlag != null && logicFlag.equals("1")) {
                QueryWrapper<PlanLogicLabel> wrapperPLL = WrapperUtils.getWrapper(false);
                wrapperPLL.eq("plan_id", plan.getId());
//                wrapperPLL.and(e -> e.eq("must_status", 1).or().eq("not_status", 1));
                List<PlanLogicLabel> logicLabelslist = planLogicLabelService.list(wrapperPLL);
                if (logicLabelslist.isEmpty()) {

                } else {
                    List<Long> mustIds = new ArrayList<>();
                    List<Long> notIds = new ArrayList<>();
                    for (PlanLogicLabel planLogicLabel : logicLabelslist) {
                        if (planLogicLabel.getLogicType() == 0) {
                            mustIds.add(planLogicLabel.getLabelId());
                        } else if (planLogicLabel.getLogicType() == 1) {
                            notIds.add(planLogicLabel.getLabelId());
                        }
                    }


                    //必须有
                    if (!mustIds.isEmpty()) {

                        QueryWrapper<UserToLabel> wrapperUTL = WrapperUtils.getWrapper(false);
                        wrapperUTL.in("user_id", userIds);
                        wrapperUTL.groupBy("user_id");
                        wrapperUTL.in("label_id", mustIds);
                        List<UserToLabel> userToLabels = userToLabelService.list(wrapperUTL);


                        userIds = userToLabels.stream().map(UserToLabel::getUserId).collect(Collectors.toList());
                        if (userIds.isEmpty()) {
                            //未匹配到人员
                            setTaskStatusLog(date, taskInfo, -1, "任务派单筛选未找到符合是标签人员(logicFlag)");

//                    StringBuilder stringBuilder = new StringBuilder();
//                    stringBuilder.append("【taskUserCreate】未找到已上班筛选人员，计划id：").append(plan.getId()).append(",任务id：").append(taskInfo.getId());
//                    log.info(stringBuilder.toString());
                            taskCommand = redisService4.rightPop("taskUserQueue");
                            continue;
                        }
                    }

                    //必须没有
                    if (!notIds.isEmpty()) {
                        QueryWrapper<UserToLabel> wrapperUTL = WrapperUtils.getWrapper(false);
                        wrapperUTL.in("user_id", userIds);
                        wrapperUTL.groupBy("user_id");
                        wrapperUTL.in("label_id", notIds);
                        List<UserToLabel> userToLabels = userToLabelService.list(wrapperUTL);
                        List<Long> notuserid = userToLabels.stream().map(UserToLabel::getUserId).collect(Collectors.toList());
                        userIds.removeAll(notuserid);
                    }

                    if (userIds.isEmpty()) {
                        //未匹配到人员
                        setTaskStatusLog(date, taskInfo, -1, "任务派单筛选去除否标签后未找到符合人员(logicFlag)");
                        taskCommand = redisService4.rightPop("taskUserQueue");
                        continue;
                    }
                }

            }

            String taskNearFlag = redisService5.hmGet("Dictionary", "TaskNearFlag") != null ? redisService5.hmGet("Dictionary", "TaskNearFlag").toString() : null;
            String taskTypeNearFlag = redisService5.get("entity:TaskTypeNearFlag:" + taskInfo.getTypeId() + ":" + taskInfo.getDistrictId());
            if (taskTypeNearFlag != null && (taskInfo.getTypeId() == 8 || taskInfo.getTypeId() == 9)) {
                taskNearFlag = taskTypeNearFlag;
            }
            if (taskNearFlag != null && taskNearFlag.equals("1")) {
                QueryWrapper<TaskScenes> wrapperTS = WrapperUtils.getWrapper(false);
                wrapperTS.eq("plan_id", plan.getId());
                wrapperTS.eq("task_id", taskInfo.getId());
                List<TaskScenes> taskScenes = taskScenesService.list(wrapperTS);
                if (taskScenes != null && !taskScenes.isEmpty()) {
                    Set<Long> planIds = new HashSet<>();
                    for (TaskScenes taskScene : taskScenes) {
                        QueryWrapper<TaskScenes> wrapperTSByPlan = WrapperUtils.getWrapper(false);
                        wrapperTSByPlan.eq("district_id", plan.getDistrictId());
                        wrapperTSByPlan.eq("scenes_level", taskScene.getScenesLevel());
                        wrapperTSByPlan.eq("scenes_id", taskScene.getScenesId());

                        wrapperTSByPlan.eq("status", 0);
                        List<TaskScenes> taskScenesPlan = taskScenesService.list(wrapperTSByPlan);
                        planIds.addAll(taskScenesPlan.stream().map(taskScen -> taskScen.getPlanId()).collect(Collectors.toSet()));
                    }
                    QueryWrapper<TaskUser> wrapperTU = WrapperUtils.getWrapper(false);
                    wrapperTU.in("plan_id", planIds);
                    //待完成
                    wrapperTU.in("status", "3", "4");
                    if (taskInfo != null && (taskInfo.getTypeId() == 8 || taskInfo.getTypeId() == 9)) {
                        wrapperTU.eq("task_type", 1);
                    }
                    wrapperTU.groupBy("user_id");
                    List<TaskUser> taskUserList = taskUserService.list(wrapperTU);
                    List<Long> nearIds = taskUserList.stream().map(TaskUser::getUserId).collect(Collectors.toList());
                    log.info("【taskUserCreate】near:userids" + JSONObject.toJSONString(userIds) + ";nearIds:" + JSONObject.toJSONString(nearIds));

                    //20221011 由取并集变成取交集
                    {
                        if (!nearIds.isEmpty()) {
                            Collection intersection = CollectionUtils.intersection(userIds, nearIds);

                            if (!intersection.isEmpty()) {
                                userIds = new ArrayList<Long>(intersection);
                            }

                        }

                    }
                    //原取并集
//                    userIds.addAll(nearIds);
                }
                //提升优先级
                if (userIds.size() > 0 && (taskInfo.getTypeId() == 8 || taskInfo.getTypeId() == 9)) {
                    taskInfo.setPoolOrder(2);
                }
            }

            assert userIds != null;
            if (userIds != null && !userIds.isEmpty()) {

                //20221011 人员的二次匹配
                if (taskInfo.getStatus() == 2) {
                    if (userIds != null && !userIds.isEmpty()) {
                        taskInfo.setSendTime(date);
                        QueryWrapper<TaskUser> wrapperTaskUser = WrapperUtils.getWrapper(false);
                        wrapperTaskUser.eq("task_id", taskInfo.getId());
                        List<TaskUser> list = taskUserService.list(wrapperTaskUser);
                        List<Long> confirmUserIds = list.stream().map(p -> p.getUserId()).collect(Collectors.toList());
                        userIds.removeAll(confirmUserIds);
                        Set<Long> choseUser = getUserIds(taskInfo, userIds);
                        if (!choseUser.isEmpty()) {

                            String hour = null;
                            StringBuilder stringBuilder = new StringBuilder();
                            StringBuilder acceptUserName = new StringBuilder();


                            for (Long userId : choseUser) {
                                User user = userService.getById(userId);
//                                if (user.getOffTime() != null && !user.getOffTime().trim().equals("")) {
//                                    if (hour == null) {
//                                        hour = user.getOffTime();
//                                    } else {
//                                        hour = DateToConverter.compareHourMinter(hour, user.getOffTime());
//                                    }
//                                }
                                createTaskUser(date, taskInfo, user);
                                stringBuilder.append(user.getName()).append(" ").append(user.getMobile()).append(",");
                                acceptUserName.append(user.getName()).append(",");
                            }
                            //推送
                            setTaskPushQueue(taskInfo);
                            //任务派单人员赋值
                            if (acceptUserName.length() > 0) {
                                String acceptUserNameStr = acceptUserName.toString().substring(0, acceptUserName.length() - 1);
                                taskInfo.setTaskDistributiUser(taskInfo.getTaskDistributiUser() + "," + acceptUserName.substring(0, acceptUserName.length() - 1));
                                UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                                updateWrapper.eq("task_id", taskInfo.getId());
                                updateWrapper.set("send_time", date);
                                updateWrapper.set("task_distributi_user", taskInfo.getTaskDistributiUser());
                                taskUserService.update(updateWrapper);
                            }
                            //任务状态变更日志
                            if (stringBuilder.length() > 0) {
                                setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "再次匹配人员:" + stringBuilder.substring(0, stringBuilder.length() - 1));
                            } else {
                                setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "");
                            }
                            choseUser.addAll(confirmUserIds);
                            setUploadManagerUser(taskInfo, new ArrayList<>(choseUser));

                            redisService4.lPush("IntellectualTaskIdList", taskInfo.getId().toString());

                        } else {
                            setTaskStatusLog(date, taskInfo, -1, "再次匹配人员的 任务派单池已满，等待下次派单匹配");
                        }
                    }


                } else {
                    Set<Long> choseUser = getUserIds(taskInfo, userIds);
                    if (!choseUser.isEmpty()) {
                        if (userIds.size() > 0 && (taskInfo.getTypeId() == 8 || taskInfo.getTypeId() == 9)) {
                            taskInfo.setPoolOrder(2);
                        }
                        taskInfo.setSendTime(date);
                        taskInfo.setMatchTime(date);
                        StringBuilder stringBuilder = new StringBuilder();
                        StringBuilder acceptUserName = new StringBuilder();
                        String hour = null;


                        if (autoTaskTakeFlag) {
                            taskInfo.setStatus(3);
                            taskInfo.setConfirmTime(date);
                            //
                            if (plan.getType() == 0) {
                                int taskTime = plan.getWorkingTiming() + plan.getTransitionTiming() + plan.getReadyTiming() + plan.getRedundanceTiming();
                                String dateAddOrSub = DateToConverter.getDateAddOrSub(12, taskTime, date);
                                Date preFinishTime = DateToConverter.parseDate(dateAddOrSub, 5);
                                if (taskInfo.getPreFinishTime() != null) {
                                    if (taskInfo.getPreFinishTime().getTime() > preFinishTime.getTime()) {
                                        taskInfo.setPreFinishTime(preFinishTime);
                                    }
                                } else {
                                    taskInfo.setPreFinishTime(preFinishTime);
                                }
                            }


//                        if (taskInfo.getTaskType() == 0 && taskInfo.getExpireType() == 2) {
//
//
//                        }
                            //20231123 如果只有一个人，就直接接单，梳理逻辑，无其他地方修改
                        }else if (choseUser.size()==1){
                            taskInfo.setStatus(3);
                            taskInfo.setConfirmTime(date);
                        }else {
                            taskInfo.setStatus(2);
                        }
                        String executeEndDate = null;


                        //任务执行期末时间
                        try {
                            if (plan.getActionTimeType() != null && plan.getActionTimeType() == 1) {
                                Date expireTime = taskInfo.getExpireTime();
                                if (expireTime != null) {
                                    if (plan.getActionEndTime() != null && !plan.getActionEndTime().equals("")) {
                                        executeEndDate = DateToConverter.getFormattedDate(expireTime, 5);
                                        executeEndDate = executeEndDate.replace(executeEndDate.substring(11, 16), plan.getActionEndTime().substring(0, 5));
                                    }
                                } else {
                                    if (plan.getActionEndTime() != null && !plan.getActionEndTime().equals("")) {
                                        executeEndDate = DateToConverter.getFormattedDate(date, 5);
                                        executeEndDate = executeEndDate.replace(executeEndDate.substring(11, 16), plan.getActionEndTime().substring(0, 5));
                                    }
                                }
                            } else {
                                Date expireTime = taskInfo.getExpireTime();

                                if (expireTime != null) {
                                    if (hour != null) {
                                        executeEndDate = DateToConverter.getFormattedDate(expireTime, 5);
                                        executeEndDate = executeEndDate.replace(executeEndDate.substring(11, 16), hour.substring(0, 5));
                                    }
                                } else {
                                    if (hour != null) {
                                        executeEndDate = DateToConverter.getFormattedDate(date, 5);
                                        executeEndDate = executeEndDate.replace(executeEndDate.substring(11, 16), hour.substring(0, 5));
                                    }
                                }
                            }
                        } finally {
                            if (executeEndDate != null) {
                                taskInfo.setExecutionPhaseEndTime(DateToConverter.parseDate(executeEndDate, 5));

                            } else {

                                taskInfo.setExecutionPhaseEndTime(null);


                            }
                        }

                        //临期派单时间
                        if (taskInfo.getExecutionPhaseEndTime() != null) {
                            if (taskInfo.getTaskType() == 0) {
                                int taskTime = 0 - (plan.getWorkingTiming() + plan.getTransitionTiming() + plan.getReadyTiming() + plan.getRedundanceTiming());
                                String impendingTimeStr = DateToConverter.getDateAddOrSub(12, taskTime, taskInfo.getExecutionPhaseEndTime());
                                Date impendingTime = DateToConverter.parseDate(impendingTimeStr, 5);
                                taskInfo.setImpendingPeriodSendTime(impendingTime);
                                //添加zset
                                redisService5.zAdd("ImpendingTime", taskInfo.getId().toString(), impendingTime.getTime());
                            }
                        }
                        //20220731
                        if (appointUserflag) {
                            taskInfo.setPoolOrder(2);
                        }
                        setUploadManagerUser(taskInfo, new ArrayList<>(choseUser));

                        for (Long userId : choseUser) {
                            User user = userService.getById(userId);
                            if (user==null) {
								continue;
							}
                            createTaskUser(date, taskInfo, user);
                            stringBuilder.append(user.getName()).append(" ").append(user.getMobile()).append(",");
                            acceptUserName.append(user.getName()).append(",");
                        }
                        //推送
                        setTaskPushQueue(taskInfo);

                        //任务派单人员赋值
                        if (acceptUserName.length() > 0) {
                            String acceptUserNameStr = acceptUserName.toString().substring(0, acceptUserName.length() - 1);

                            taskInfo.setTaskDistributiUser(acceptUserName.substring(0, acceptUserName.length() - 1));
                            UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);

                            if (taskInfo.getStatus() == 3) {
                                updateWrapper.set("task_accept_user", acceptUserNameStr);
                                taskInfo.setTaskAcceptUser(acceptUserName.substring(0, acceptUserName.length() - 1));
                            }
                            updateWrapper.eq("task_id", taskInfo.getId());
                            updateWrapper.set("task_distributi_user", acceptUserNameStr);
                            taskUserService.update(updateWrapper);
                        } else {
                            taskInfo.setTaskDistributiUser("");
                        }
//                    if (taskInfo.getStatus() == 3) {
//                        taskInfo.setTaskAcceptUser(acceptUserName.substring(0, acceptUserName.length() - 1));
//                    }
                        //任务状态变更日志
                        if (stringBuilder.length() > 0) {
                            setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), stringBuilder.substring(0, stringBuilder.length() - 1));
                        } else {
                            setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "");
                        }

                        //today_dynamic
                        redisService4.lPush("IntellectualTaskIdList", taskInfo.getId().toString());

                    } else {
                        setTaskStatusLog(date, taskInfo, -1, "任务派单池已满，等待下次派单匹配");
                    }

//20221011
                }
            } else {
                //未匹配到人员
                setTaskStatusLog(date, taskInfo, -1, "任务派单筛未找到符合人员(全逻辑)，等待下次派单匹配");
            }

            taskInfoService.updateById(taskInfo);
            taskCommand = redisService4.rightPop("taskUserQueue");

        }
    }


    /**
     * 2
     * 任务过期状态变更
     */
//    @XxlJob("systemExpireTask")
    @Scheduled(cron = "0 * * * * ?")
    public void systemExpireTask() {
        Set<String> taskIdSet = redisService5.rangeByScore("TaskExprieQueue", 0, System.currentTimeMillis());
        Date date = new Date();
        if (taskIdSet != null && !taskIdSet.isEmpty()) {
            for (String taskId : taskIdSet) {
                log.info("【systemExpireTask】任务过期：" + taskId);
                TaskInfo taskInfo = taskInfoService.getById(taskId);

                if (taskInfo == null) {
                    log.info("【systemExpireTask】任务过期：" + taskId + "任务未找到");
                    redisService5.lPush("FinishTaskQueue", taskId);
                    continue;
                }
                if (taskInfo.getStatus() > 4) {
                    log.info("【systemExpireTask】任务过期：" + taskId + "任务已终结");
                    redisService5.lPush("FinishTaskQueue", taskId);
                    continue;
                }
                if(taskInfo.getPreFinishTime()!=null&&taskInfo.getPreFinishTime().getTime()>date.getTime()){
                    log.info("【systemExpireTask】任务过期：" + taskId + "");
                    continue;
                }
                String memo = null;
                //20221013 区分过期类型（是否派发过）
                if (taskInfo.getStatus() <= 1) {
                    taskInfo.setStatus(-4);
                    memo = "派发失败系统过期";
                    taskInfo.setModifyName(memo);

                } else {
                    taskInfo.setStatus(9);
                    memo = "系统过期";
                    taskInfo.setModifyName(memo);
                }
                taskInfo.setModifyTime(date);
//                taskInfo.setModifyName("系统过期");
                taskInfo.setModifyId(0L);
//                taskIds.add(taskInfo.getId());
                taskInfoService.updateById(taskInfo);
                //重置计次
                resetTaskActionCountAndFinishPlan(taskInfo);
                setTaskStatusLog(date, taskInfo, 9, memo);
//                redisService5.zRemove("TaskExprieQueue", taskId);//移除过期监控
                redisService5.lPush("FinishTaskQueue", taskId);


                //卡片过期
                UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                updateWrapper.eq("task_id", taskId);
                updateWrapper.lt("status", 5);
                updateWrapper.set("status", taskInfo.getStatus());
                updateWrapper.set("modify_time", date);
                updateWrapper.set("modify_name", memo);
                taskUserService.update(updateWrapper);
                //场景过期
                UpdateWrapper<TaskScenes> updateScenesWrapper = WrapperUtils.getUpdateWrapper(false);
                updateScenesWrapper.eq("task_id", taskId);
                updateScenesWrapper.lt("status", 5);
                updateScenesWrapper.set("status", taskInfo.getStatus());
                updateScenesWrapper.set("modify_time", date);
                updateScenesWrapper.set("modify_name", memo);
                taskScenesService.update(updateScenesWrapper);
            }

        }
    }

    /**
     * 3任务完成后逻辑处理
     */
    @Scheduled(cron = "* * * * * ?")
    public void finishTask() {
        String taskId = redisService5.leftPop("FinishTaskQueue");
        while (taskId != null) {
            log.info("【finishTask】"+taskId);
            TaskInfo taskInfo = taskInfoService.getById(taskId);
            if (taskInfo != null) {

                resetTaskActionCountAndFinishPlan(taskInfo);
            }
            redisService5.zRemove("TaskExprieQueue", taskId);//移除过期监控
            taskId = redisService5.leftPop("FinishTaskQueue");

        }
    }

    /**
     * 5任务状态变更临期队列去除
     */
    @Scheduled(cron = "* * * * * ?")
    public void confirmTaskTask() {
        String taskId = redisService5.leftPop("ConfirmTaskQueue");
        while (taskId != null) {

            redisService5.zRemove("ImpendingTime", taskId);//移除过期监控
            taskId = redisService5.leftPop("ConfirmTaskQueue");
        }
    }

    /**
     * 6
     * 临期处理 任务临期变更
     */
    @Scheduled(cron = "0 * * * * ?")
    public void impendingTask() {
        Set<String> taskIdSet = redisService5.rangeByScore("ImpendingTime", 0, System.currentTimeMillis());
        if (taskIdSet != null && !taskIdSet.isEmpty()) {
            Date date = new Date();
            for (String taskId : taskIdSet) {
                TaskInfo taskInfo = taskInfoService.getById(taskId);
                if (taskInfo != null && taskInfo.getPoolOrder() == 3) {
                    taskInfo.setPoolOrder(2);
                    taskInfoService.updateById(taskInfo);
                    setTaskStatusLog(date, taskInfo, -1, "临期任务优先级变更");

                    UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                    updateWrapper.eq("task_id", taskId);
                    updateWrapper.set("pool_order", 2);
                    taskUserService.update(updateWrapper);
                    //任务重派发
                    if (taskInfo.getStatus() == 0) {
                        TaskPlanEntity taskPlanEntity = new TaskPlanEntity();
                        taskPlanEntity.setTaskInfo(taskInfo);
                        Plan plan = planService.getById(taskInfo.getPlanId());
                        taskPlanEntity.setPlan(plan);
                        redisService4.lPush("taskUserQueue", JSONObject.toJSONString(taskPlanEntity));
                    }

                }
                redisService5.zRemove("ImpendingTime", taskId);//移除过期监控
            }
        }
    }


    /**
     * 4
     * 任务重推送
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskRepeatAppoint() {
        //RepeatTaskQueue set去重
        String districtId = redisService5.setPop("RepeatTaskQueue");
        while (districtId != null) {
            log.info("【taskRepeatAppoint】任务重推送districtId:" + districtId);
            QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
            //未派发任务重新派发
            //20221011 重派发增加待抢单任务
            wrapper.in("status", 0, 1, 2);

            wrapper.eq("district_id", districtId);
            wrapper.orderByAsc("pool_order,group_order,task_order");
            List<TaskInfo> tasklist = taskInfoService.list(wrapper);
            for (TaskInfo taskInfo : tasklist) {


                //0803 用户上报和巡检任务增加重匹配
                TaskPlanEntity taskPlanEntity = new TaskPlanEntity();
                taskPlanEntity.setTaskInfo(taskInfo);

                if (taskInfo.getTaskType() < 3) {
                    Plan plan = planService.getById(taskInfo.getPlanId());
                    taskPlanEntity.setPlan(plan);
                    redisService4.lPush("taskUserQueue", JSONObject.toJSONString(taskPlanEntity));
                    //用户上报，巡检上报
                } else if (taskInfo.getTaskType() == 3 || taskInfo.getTaskType() == 4) {
                    redisService4.lPush("taskReportQueue", JSONObject.toJSONString(taskPlanEntity));

                    //巡检
                } else if (taskInfo.getTaskType() == 5) {
                    Plan plan = planService.getById(taskInfo.getPlanId());
                    taskPlanEntity.setPlan(plan);
                    redisService4.lPush("inspectTaskUserQueue", JSONObject.toJSONString(taskPlanEntity));
                }
            }
            districtId = redisService5.setPop("RepeatTaskQueue");
        }
    }

    /**
     * 8
     * 上报任务人员派单
     * 执行人员派单-上报
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskReportQueue() {
        String taskCommand = redisService4.rightPop("taskReportQueue");
        while (taskCommand != null) {
            log.info("【taskReportQueue】taskCommand：" + taskCommand);
            Date date = new Date();
            TaskPlanEntity taskPlanEntity = JSONObject.parseObject(taskCommand, TaskPlanEntity.class);
            //数据同步
            TaskInfo taskInfo = taskPlanEntity.getTaskInfo();
            taskInfo = taskInfoService.getById(taskInfo.getId());
//            taskInfo.setManualAllocation(1);

            if (taskInfo.getManualAllocation() == null || taskInfo.getManualAllocation() == 0) {
                log.info("【taskReportQueue】上报任务系统匹配");

                QueryWrapper<TaskScenes> wrapperTS = WrapperUtils.getWrapper(false);
                wrapperTS.eq("task_id", taskInfo.getId());
                wrapperTS.last("limit 1");
                TaskScenes taskScenes = taskScenesService.getOne(wrapperTS);
                List<Long> userIds = new ArrayList<>();
                StringBuilder appointStr = new StringBuilder();
                //场景匹配
                if (taskScenes != null) {
                    if (taskScenes.getScenesId() != null && taskScenes.getScenesId() > 0) {
                        QueryWrapper<UserToServiceArea> wrapperUTSA = WrapperUtils.getWrapper(false);
                        wrapperUTSA.eq("service_type", 1);
                        wrapperUTSA.eq("district_id", taskInfo.getDistrictId());
                        wrapperUTSA.eq("service_area_id", taskScenes.getScenesId());
                        wrapperUTSA.eq("grid_scenes_level", taskScenes.getScenesLevel());
                        List<UserToServiceArea> userList = userToServiceAreaService.list(wrapperUTSA);
                        userIds = userList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
                        appointStr.append("场景").append("-->");
                    } else {
                        QueryWrapper<UserToServiceArea> wrapperUTSA = WrapperUtils.getWrapper(false);
                        wrapperUTSA.eq("service_type", 0);
                        wrapperUTSA.eq("district_id", taskInfo.getDistrictId());
                        wrapperUTSA.eq("grid_scenes_level", taskScenes.getGridLevel());
                        switch (taskScenes.getGridLevel()) {
                            case 1:
                                wrapperUTSA.eq("service_area_id", taskScenes.getBuildingId());
                                break;
                            case 2:
                                wrapperUTSA.eq("service_area_id", taskScenes.getFloorId());
                                break;
                            case 3:
                                wrapperUTSA.eq("service_area_id", taskScenes.getMultistageGridId());
                                break;
                        }
                        List<UserToServiceArea> userList = userToServiceAreaService.list(wrapperUTSA);
                        userIds = userList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
                        appointStr.append("网格").append("-->");
                    }

                }
//            //事项匹配
//            if (taskPlanEntity.getMatterId() != null && userIds != null && !userIds.isEmpty()) {
//                QueryWrapper<UserToMatter> wrapperUTM = WrapperUtils.getWrapper(false);
//                wrapperUTM.in("user_id", userIds);
//                wrapperUTM.eq("matter_id", taskPlanEntity.getMatterId());
//                List<UserToMatter> userList = userToMatterService.list(wrapperUTM);
//                userIds = userList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
//                appointStr.append("事项").append("-->");
//            }
                //上下班匹配
                if (userIds != null && !userIds.isEmpty()) {
//                    QueryWrapper<User> wrapperUser = WrapperUtils.getWrapper(false);
//                    wrapperUser.eq("work_status", 0);
//                    //排除休息
//                    wrapperUser.notIn("work_at_status", 3);
//                    wrapperUser.in("id", userIds);
//                    List<User> userlist = userService.list(wrapperUser);
                    ArrayList<Long> userlist = new ArrayList<>(userIds);
                    for (Long userId : userIds) {
                        UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(taskInfo.getDistrictId(), userId);
                        if (userDistrictAttendance.getWorkStatus() == 0 && userDistrictAttendance.getWorkAtStatus() != 3) {
                            userlist.add(userId);
                        }
                    }
                    userIds = userlist;
                    appointStr.append("考勤").append("-->");
                }

                //20221011 二次匹配
                if (taskInfo.getStatus() == 2) {
                    if (userIds != null && !userIds.isEmpty()) {
                        taskInfo.setSendTime(date);
                        QueryWrapper<TaskUser> wrapperTaskUser = WrapperUtils.getWrapper(false);
                        wrapperTaskUser.eq("task_id", taskInfo.getId());
                        List<TaskUser> list = taskUserService.list(wrapperTaskUser);
                        List<Long> confirmUserIds = list.stream().map(p -> p.getUserId()).collect(Collectors.toList());
                        userIds.removeAll(confirmUserIds);
                        Set<Long> choseUser = getUserIds(taskInfo, userIds);
                        StringBuilder stringBuilder = new StringBuilder();
                        StringBuilder acceptUserName = new StringBuilder();
                        for (Long userId : choseUser) {
                            User user = userService.getById(userId);
                            createTaskUser(date, taskInfo, user);
                            stringBuilder.append(user.getName()).append(" ").append(user.getMobile()).append("、");
                            acceptUserName.append(user.getName()).append(",");
                        }
                        //推送
                        setTaskPushQueue(taskInfo);
                        if (stringBuilder.length() > 0) {
                            setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "上报任务补充派单：" + stringBuilder.substring(0, stringBuilder.length() - 1));
                        }
                        if (acceptUserName.length() > 0) {
                            String distributiUser = acceptUserName.toString().substring(0, acceptUserName.length() - 1);
                            taskInfo.setTaskDistributiUser(taskInfo.getTaskDistributiUser() + "," + distributiUser);

                            UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                            updateWrapper.eq("task_id", taskInfo.getId());
                            updateWrapper.set("task_distributi_user", taskInfo.getTaskDistributiUser());
                            updateWrapper.set("send_time", date);
                            taskUserService.update(updateWrapper);
                        }
                        choseUser.addAll(confirmUserIds);
                        setUploadManagerUser(taskInfo, new ArrayList<>(choseUser));
                    }
                } else {
                    //原匹配逻辑，现初次人员


                    if (userIds != null && !userIds.isEmpty()) {
                        //匹配到人员，选择班组长
                        Set<Long> choseUser = getUserIds(taskInfo, userIds);
//                setUploadManagerUser(taskInfo, userIds);

//                appointStr.append("任务池").append("-->");
                        if (!choseUser.isEmpty()) {
                            setUploadManagerUser(taskInfo, new ArrayList<>(choseUser));
                            taskInfo.setStatus(2);
                            taskInfo.setSendTime(date);
                            taskInfo.setMatchTime(date);
                            StringBuilder managerListStr = getManageUserName(taskInfo, taskScenes);

                            if (managerListStr.length() > 0) {
                                taskInfo.setReportManageUser(managerListStr.substring(0, managerListStr.length() - 1));
                            } else {
                                taskInfo.setReportManageUser("");
                            }


                            StringBuilder stringBuilder = new StringBuilder();
                            StringBuilder acceptUserName = new StringBuilder();
                            for (Long userId : choseUser) {
                                User user = userService.getById(userId);
                                createTaskUser(date, taskInfo, user);
                                stringBuilder.append(user.getName()).append(" ").append(user.getMobile()).append("、");
                                acceptUserName.append(user.getName()).append(",");
                            }
                            //推送
                            setTaskPushQueue(taskInfo);
                            if (stringBuilder.length() > 0) {
                                setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "上报任务派单：" + stringBuilder.substring(0, stringBuilder.length() - 1));
                            } else {
                                setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), "上报任务派单：");
                            }
                            if (acceptUserName.length() > 0) {
                                String distributiUser = acceptUserName.toString().substring(0, acceptUserName.length() - 1);
                                taskInfo.setTaskDistributiUser(distributiUser);
                                UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                                updateWrapper.eq("task_id", taskInfo.getId());
                                updateWrapper.set("task_distributi_user", distributiUser);
                                taskUserService.update(updateWrapper);
                            }

                        } else {
                            taskInfo.setStatus(1);
                            //没匹配到人员，上报管理人
                            StringBuilder managerListStr = getManageUserName(taskInfo, taskScenes);

                            if (managerListStr.length() > 0) {
                                taskInfo.setReportManageUser(managerListStr.substring(0, managerListStr.length() - 1));
//                            taskInfo.setUploadManageUser(managerListStr.substring(0, managerListStr.length() - 1));
                            } else {
                                taskInfo.setReportManageUser("");
                            }
                            createTaskUser(date, taskInfo, null);

                            setTaskStatusLog(date, taskInfo, -1, "上报任务派单：" + appointStr.toString());
                        }

                    } else {
                        taskInfo.setStatus(1);
                        //没匹配到人员，上报管理人
                        StringBuilder managerListStr = getManageUserName(taskInfo, taskScenes);

                        if (managerListStr.length() > 0) {
                            taskInfo.setReportManageUser(managerListStr.substring(0, managerListStr.length() - 1));
                        } else {
                            taskInfo.setReportManageUser("");
                        }
                        createTaskUser(date, taskInfo, null);

                        setTaskStatusLog(date, taskInfo, -1, "上报任务派单：" + appointStr.toString());
                    }
                    taskInfo.setManualAllocation(0);
                }


                taskInfoService.updateById(taskInfo);
                redisService4.lPush("IntellectualTaskIdList", taskInfo.getId().toString());
//                }
            } else if (taskInfo.getManualAllocation() == 1) {
                //指派匹配失败再派发 0804，如任务池满，任务不可见，已需求确认先不处理
                log.info("【taskReportQueue】上报任务指派后--重派发");

                //班组指派
                if (taskInfo.getUserType() == 2) {
                    String uploadManageUser = taskInfo.getUploadManageUser();
                    if (uploadManageUser == null || uploadManageUser.trim().equals("")) {
                        log.info("【taskReportQueue】班组id异常：" + uploadManageUser);
                        taskCommand = redisService4.rightPop("taskReportQueue");
                        continue;
                    }
                    String[] groupId = uploadManageUser.split(",");

                    StringBuilder manageNameStr = new StringBuilder();

                    QueryWrapper<WorkGroupToPrincipal> wrapperWGTP = WrapperUtils.getWrapper(false);
                    wrapperWGTP.in("work_group_id", groupId);
                    wrapperWGTP.eq("district_id", taskInfo.getDistrictId());
                    wrapperWGTP.orderByDesc("principal_flag");
                    wrapperWGTP.groupBy("user_id");
                    List<WorkGroupToPrincipal> list = workGroupToPrincipalService.list(wrapperWGTP);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (WorkGroupToPrincipal workGroupToPrincipal : list) {
//                    createTaskUser(date, taskInfo, workGroupToPrincipal,user);
                        if (workGroupToPrincipal.getPrincipalFlag() == 1) {
                            manageNameStr.append(workGroupToPrincipal.getUserName()).append(",");
                        }
                    }


                    List<Long> userIds = list.stream().map(p -> p.getUserId()).collect(Collectors.toList());
                    Set<Long> chooseUserIds = getUserIds(taskInfo, userIds);
                    if (!chooseUserIds.isEmpty()) {
                        for (Long userId : chooseUserIds) {
                            User curuser = userService.getById(userId);
                            createTaskUser(date, taskInfo, curuser);
                            stringBuilder.append(curuser.getName()).append(",");
                        }
                        //推送
                        setTaskPushQueue(taskInfo);
                        taskInfo.setStatus(2);
                        if (manageNameStr.length() > 0) {
                            taskInfo.setUploadManageUser(manageNameStr.substring(0, manageNameStr.length() - 1));
                        } else {
                            taskInfo.setUploadManageUser("");

                        }
                        taskInfo.setTaskDistributiUser(stringBuilder.toString());
                    } else {
                        String idString = userIds.stream().map(i -> i.toString()).collect(Collectors.joining(","));
                        taskInfo.setUploadManageUser(idString);
                        setTaskStatusLog(date, taskInfo, -1, "已指派班组，再次未匹配到符合条件的人员");
                    }

                } else if (taskInfo.getUserType() == 1) {
                    //人员指派
                    String uploadManageUser = taskInfo.getUploadManageUser();
                    if (uploadManageUser == null || uploadManageUser.trim().equals("")) {
                        log.info("【taskReportQueue】人员id异常：" + uploadManageUser);
                        taskCommand = redisService4.rightPop("taskReportQueue");
                        continue;
                    }
                    StringBuilder appointuser = new StringBuilder();
                    String[] userIdstr = uploadManageUser.split(",");
                    List<Long> userIds = Arrays.stream(userIdstr).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());

                    Set<Long> chooseUserIds = getUserIds(taskInfo, userIds);
                    if (!chooseUserIds.isEmpty()) {

                        taskInfo.setStatus(3);
                        StringBuilder acceptUserName = new StringBuilder();
                        for (Long userId : chooseUserIds) {
                            User curuser = userService.getById(userId);
                            createTaskUser(date, taskInfo, curuser);
                            acceptUserName.append(curuser.getName()).append(",");
                            appointuser.append(curuser.getName()).append(" ").append(curuser.getMobile()).append(",");
                        }
                        //推送
                        setTaskPushQueue(taskInfo);

                        if (acceptUserName.length() > 0) {
                            String acceptUserNameStr = acceptUserName.toString().substring(0, acceptUserName.length() - 1);
                            taskInfo.setTaskAcceptUser(acceptUserNameStr);
                            UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                            updateWrapper.eq("task_id", taskInfo.getId());
                            updateWrapper.set("task_accept_user", acceptUserNameStr);
                            taskUserService.update(updateWrapper);
                        }

                        // 组长看组员
                        QueryWrapper<WorkGroupToPrincipal> wrapperWGTP = WrapperUtils.getWrapper(false);
                        wrapperWGTP.in("user_id", userIds);
                        wrapperWGTP.groupBy("work_group_id");
                        List<WorkGroupToPrincipal> listWgtp = workGroupToPrincipalService.list(wrapperWGTP);
                        if (!listWgtp.isEmpty()) {
                            List<Long> groupIds = listWgtp.stream().map(p -> p.getWorkGroupId()).collect(Collectors.toList());

                            QueryWrapper<WorkGroupToPrincipal> wrapperWGTP2 = WrapperUtils.getWrapper(false);
                            wrapperWGTP2.in("work_group_id", groupIds);
                            wrapperWGTP2.eq("principal_flag", 1);
                            wrapperWGTP2.groupBy("user_id");
                            List<WorkGroupToPrincipal> listWgtp2 = workGroupToPrincipalService.list(wrapperWGTP2);
                            StringBuilder manageUser = new StringBuilder();
                            for (WorkGroupToPrincipal workGroupToPrincipal : listWgtp2) {
                                manageUser.append(workGroupToPrincipal.getUserName()).append(",");
                            }
                            taskInfo.setUploadManageUser(manageUser.toString());
                        }

                        //人员接单日志
                        if (appointuser.length() > 0) {
                            setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), appointuser.substring(0, appointuser.lastIndexOf(",")));
                        }
                    } else {
                        String idString = userIds.stream().map(i -> i.toString()).collect(Collectors.joining(","));
                        taskInfo.setUploadManageUser(idString);
                        setTaskStatusLog(date, taskInfo, -1, "已指派人员，再次未匹配到符合条件的人员");
                    }
                }


                //匹配成功
                if (taskInfo.getStatus() > 1) {
                    taskInfo.setModifyTime(date);
                    taskInfoService.updateById(taskInfo);
                }

            }


            taskCommand = redisService4.rightPop("taskReportQueue");
        }
    }

    /**
     * 7
     * 执行人员派单-巡检
     */
    @Scheduled(cron = "* * * * * ?")
    public void inspectTaskUserCreate() {
        String taskCommand = redisService4.rightPop("inspectTaskUserQueue");
        while (taskCommand != null) {
            log.info("【inspectTaskUserCreate】"+taskCommand);
            Date date = new Date();
            TaskPlanEntity taskPlanEntity = JSONObject.parseObject(taskCommand, TaskPlanEntity.class);
            TaskInfo taskInfo = taskPlanEntity.getTaskInfo();
            Plan plan = taskPlanEntity.getPlan();
            List<Long> userIds = null;

            switch (plan.getUserType()) {
//                case 0:
//                    QueryWrapper<UserProper> wrapperUP = WrapperUtils.getWrapper(false);
//                    wrapperUP.eq("district_id", plan.getDistrictId());
//                    wrapperUP.in("type", 0, 1);// 保洁和物业
//                    List<UserProper> userPropers = userProperService.list(wrapperUP);
//                    userIds = userPropers.stream().map(p -> p.getUserId()).collect(Collectors.toList());
//
//
//                    break;
                case 1:
                    QueryWrapper<PlanUser> wrapperPU = WrapperUtils.getWrapper(false);
                    wrapperPU.eq("plan_id", plan.getId());
                    List<PlanUser> planUserList = planUserService.list(wrapperPU);
                    userIds = planUserList.stream().map(PlanUser::getUserId).collect(Collectors.toList());
                    break;
                case 2:
                    QueryWrapper<PlanWorkGroup> wrapperPWG = WrapperUtils.getWrapper(false);
                    wrapperPWG.eq("plan_id", plan.getId());
                    List<PlanWorkGroup> planWorkGroupList = planWorkGroupService.list(wrapperPWG);
                    if (!planWorkGroupList.isEmpty()) {
                        List<Long> groupIds = planWorkGroupList.stream().map(PlanWorkGroup::getWorkGroupId).collect(Collectors.toList());
                        QueryWrapper<WorkGroupToPrincipal> wrapperWGP = WrapperUtils.getWrapper(false);
                        wrapperWGP.in("work_group_id", groupIds);
                        wrapperWGP.orderByDesc("principal_flag");
                        wrapperWGP.groupBy("user_id");
                        List<WorkGroupToPrincipal> workGroupToPrincipals = workGroupToPrincipalService.list(wrapperWGP);
//                        List<Long> curUserIdList = new ArrayList<>();


                        userIds = workGroupToPrincipals.stream().map(WorkGroupToPrincipal::getUserId).collect(Collectors.toList());
                    }
                    break;
                default:
                    break;
            }
            //20220804
            Set<Long> chooseUserIds = getUserIds(taskInfo, userIds);

            if (!chooseUserIds.isEmpty()) {

                //20220801
                setUploadManagerUser(taskInfo, userIds);

                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder acceptUserName = new StringBuilder();
                //巡检计划生成即进行
                taskInfo.setStatus(4);
                taskInfo.setSendTime(date);
                taskInfo.setMatchTime(date);
                taskInfo.setActionTime(date);
                for (Long userId : userIds) {
                    User user = userService.getById(userId);

                    createTaskUser(date, taskInfo, user);
                    stringBuilder.append(user.getName()).append(" ").append(user.getMobile()).append(",");
                    acceptUserName.append(user.getName()).append(",");
                }
                //推送
                setTaskPushQueue(taskInfo);
                if (acceptUserName.length() > 0) {
                    String substring = acceptUserName.substring(0, acceptUserName.length() - 1);
                    taskInfo.setTaskDistributiUser(substring);
                    UpdateWrapper<TaskUser> updateWrapper = WrapperUtils.getUpdateWrapper(false);
                    updateWrapper.eq("task_id", taskInfo.getId());
                    updateWrapper.set("task_distributi_user", substring);
                    taskUserService.update(updateWrapper);
                } else {
                    taskInfo.setTaskDistributiUser("");
                }
                taskInfoService.updateById(taskInfo);
                setTaskStatusLog(date, taskInfo, taskInfo.getStatus(), stringBuilder.substring(0, stringBuilder.length() - 1));
                redisService4.lPush("IntellectualTaskIdList", taskInfo.getId().toString());

            } else {
                setTaskStatusLog(date, taskInfo, -1, "巡检任务，再次未匹配到符合条件的人员");
            }
            taskCommand = redisService4.rightPop("inspectTaskUserQueue");
        }
    }

    private void setUploadManagerUser(TaskInfo taskInfo, List<Long> userIds) {
        QueryWrapper<WorkGroupToPrincipal> wrapperWGTP = WrapperUtils.getWrapper(false);
        wrapperWGTP.in("user_id", userIds);
        wrapperWGTP.groupBy("work_group_id");
        List<WorkGroupToPrincipal> list = workGroupToPrincipalService.list(wrapperWGTP);
        List<Long> groupIds = list.stream().map(WorkGroupToPrincipal::getWorkGroupId).collect(Collectors.toList());
        if (!groupIds.isEmpty()) {
            QueryWrapper<WorkGroupToPrincipal> wrapperWGTP2 = WrapperUtils.getWrapper(false);
            wrapperWGTP2.in("work_group_id", groupIds);
            wrapperWGTP2.eq("principal_flag", 1);
            wrapperWGTP2.groupBy("user_id");
            List<WorkGroupToPrincipal> list2 = workGroupToPrincipalService.list(wrapperWGTP2);

            StringBuilder principalName = new StringBuilder();
            for (WorkGroupToPrincipal workGroupToPrincipal : list2) {
//                            curUserIdList.add(workGroupToPrincipal.getUserId());
                principalName.append(workGroupToPrincipal.getUserName()).append(",");
            }
            if (principalName.length() > 0) {
                taskInfo.setUploadManageUser(principalName.substring(0, principalName.length() - 1));
            }
        }

    }

    private StringBuilder getManageUserName(TaskInfo taskInfo, TaskScenes taskScenes) {
        List<Long> manageIds = null;
        StringBuilder managerListStr = new StringBuilder();
        QueryWrapper<EscalationServiceArea> wrapperESA = WrapperUtils.getWrapper(false);
        wrapperESA.eq("district_id", taskInfo.getDistrictId());
        if (taskScenes.getScenesId() > 0) {
            wrapperESA.eq("service_area_id", taskScenes.getScenesId());
            wrapperESA.eq("grid_scenes_level", taskScenes.getScenesLevel());
            wrapperESA.eq("service_type", 1);
        } else {
            wrapperESA.eq("service_type", 0);
            wrapperESA.eq("grid_scenes_level", taskScenes.getGridLevel());
            switch (taskScenes.getGridLevel()) {
                case 1:
                    wrapperESA.eq("service_area_id", taskScenes.getBuildingId());

                    break;
                case 2:
                    wrapperESA.eq("service_area_id", taskScenes.getFloorId());

                    break;
                case 3:
                    wrapperESA.eq("service_area_id", taskScenes.getMultistageGridId());
                    break;
                default:
                    break;
            }
        }

        wrapperESA.groupBy("user_id");
        List<EscalationServiceArea> areaList = escalationServiceAreaService.list(wrapperESA);
        manageIds = areaList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
        if (manageIds.isEmpty()) {
//            QueryWrapper<EscalationUser> wrapperEU = WrapperUtils.getWrapper(false);
//            wrapperEU.eq("district_id", taskInfo.getDistrictId());
//            List<EscalationUser> eulist = escalationUserService.list(wrapperEU);
//            for (EscalationUser escalationUser : eulist) {
//                managerListStr.append(escalationUser.getUserName()).append(",");
//            }
        } else {
            QueryWrapper<User> wrapperUser = WrapperUtils.getWrapper(false);
            wrapperUser.in("id", manageIds);
            List<User> userlist = userService.list(wrapperUser);
            for (User user : userlist) {
                managerListStr.append(user.getName()).append(",");
            }
        }
        return managerListStr;
    }


    private void setTaskStatusLog(Date date, TaskInfo taskInfo, Integer status, String content) {
        TaskStatusLog taskStatusLog = new TaskStatusLog();
        taskStatusLog.setAgentId(taskInfo.getAgentId());
        taskStatusLog.setPropertyId(taskInfo.getPropertyId());
        taskStatusLog.setDistrictId(taskInfo.getDistrictId());
        taskStatusLog.setDistrictName(taskInfo.getDistrictName());
        taskStatusLog.setAgentName(taskInfo.getAgentName());
        taskStatusLog.setPropertyName(taskInfo.getPropertyName());
        taskStatusLog.setTaskId(taskInfo.getId());
        taskStatusLog.setPlanId(taskInfo.getPlanId());
        taskStatusLog.setTaskStatus(status);
        taskStatusLog.setContent(content);
        taskStatusLog.setCreateTime(date);
        taskStatusLogService.save(taskStatusLog);
    }

    private TaskUser createTaskUser(Date date, TaskInfo taskInfo, User user) {
        TaskUser taskUser = new TaskUser();
        taskUser.setId(null);
        try {

            if (user == null) {
                taskUser.setUserId(0L);
                taskUser.setUserName("");
                taskUser.setMobile("");
            } else {
                taskUser.setUserId(user.getId());
                taskUser.setUserName(user.getName());
                taskUser.setMobile(user.getMobile());
            }

            taskUser.setSendTime(date);
            taskUser.setTaskId(taskInfo.getId());
            taskUser.setPlanId(taskInfo.getPlanId());
            taskUser.setStatus(taskInfo.getStatus());
            taskUser.setName(taskInfo.getName());
            taskUser.setNo(taskInfo.getNo());
            taskUser.setTaskType(taskInfo.getTaskType());
            taskUser.setTaskAcceptUser(taskInfo.getTaskAcceptUser());
            taskUser.setContent(taskInfo.getContent());
            taskUser.setTaskDistributiUser(taskInfo.getTaskDistributiUser());
            taskUser.setExpireType(taskInfo.getExpireType());
            taskUser.setExpireTime(taskInfo.getExpireTime());
            taskUser.setTiming(taskInfo.getTiming());
            taskUser.setTaskPosition(taskInfo.getTaskPosition());
            taskUser.setDistrictId(taskInfo.getDistrictId());
            taskUser.setPoolOrder(taskInfo.getPoolOrder());
            taskUser.setGroupOrder(taskInfo.getGroupOrder());
            taskUser.setTaskOrder(taskInfo.getTaskOrder());
            taskUser.setUploadManageUser(taskInfo.getUploadManageUser());
            taskUser.setTaskPosition(taskInfo.getTaskPosition());
            taskUser.setCreateName(taskInfo.getCreateName());
            taskUser.setCreateId(taskInfo.getCreateId());
            taskUser.setReportManageUser(taskInfo.getReportManageUser());
            if (taskInfo.getStatus() == 3) {
                taskUser.setConfirmTime(date);

                if (user.getWorkAtStatus() == 2) {
                    user.setWorkAtStatus(1);
                    user.setModifyTime(new Date());
                    userService.updateById(user);
                }
            }


//            extracted(taskInfo);


        } catch (Exception e) {
            e.printStackTrace();
        }
        taskUserService.save(taskUser);
        if (taskUser.getUserId() > 0) {
            redisService4.lPush("WatchTaskUserList", taskUser.getId().toString());
        }

        return taskUser;
    }

    private void setTaskPushQueue(TaskInfo taskInfo) {
        if (taskInfo.getStatus() == 2 || taskInfo.getStatus() == 3) {
            MessageNotification taskPushInfo = new MessageNotification();
            taskPushInfo.setTaskId(taskInfo.getId());
            taskPushInfo.setStatus(taskInfo.getStatus());
            taskPushInfo.setTaskName(taskInfo.getName());
            taskPushInfo.setDistrictId(taskInfo.getDistrictId());
            redisService4.lPush("taskPushQueue", JSONObject.toJSONString(taskPushInfo));
        }
    }


    /**
     * 重置计划次数
     */
    private void resetTaskActionCountAndFinishPlan(TaskInfo taskInfo) {
        log.info("【resetTaskActionCountAndFinishPlan】taskid:"+taskInfo.getId()+",planid:"+taskInfo.getPlanId());
        Plan plan = planService.getById(taskInfo.getPlanId());
        if (plan == null) {
            return;
        }
        if (taskInfo.getTaskCreateType() == 1) {

            if (plan.getStatus() == 0) {
                QueryWrapper<PlanScenes> wrapperPS = WrapperUtils.getWrapper(false);
                wrapperPS.eq("plan_id", plan.getId());
                List<PlanScenes> planScenesList = planScenesService.list(wrapperPS);
                for (PlanScenes planScenes : planScenesList) {
                    if (planScenes.getScenesLevel() == 1) {
                        redisService4.set("UserCount:t:" + planScenes.getScenesId() + ":" + plan.getId(), plan.getActionCount().toString());
                        redisService4.add("UserCount:t:" + planScenes.getScenesId(), plan.getId().toString());
                    } else if (planScenes.getScenesLevel() == 2) {
                        redisService4.set("UserCount:p:" + planScenes.getScenesId() + ":" + plan.getId(), plan.getActionCount().toString());
                        redisService4.add("UserCount:p:" + planScenes.getScenesId(), plan.getId().toString());
                    }
                }
            }
        }

        try {
            if (plan.getEndTime() != null) {
                Date date = new Date();
                //当前时间大于结束时间
                if (date.getTime() > plan.getEndTime().getTime()) {
                    plan.setStatus(2);
                    plan.setModifyTime(date);
                    planService.updateById(plan);
                } else {
                    if (taskInfo.getStatus() == 5) {
                        if (DateToConverter.getFormattedDate(date, 0).equals(DateToConverter.getFormattedDate(plan.getEndTime(), 0))) {
                            plan.setStatus(2);
                            plan.setModifyTime(date);
                            planService.updateById(plan);
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }


    /**
     * @param taskInfo
     * @param userIds
     * @return
     */
    private Set<Long> getUserIds(TaskInfo taskInfo, List<Long> userIds) {
        if (taskInfo.getStatus() == 0) {
            taskInfo.setStatus(1);
        }
        Integer count = 99;
        String countLine = redisService4.get("PoolOrderCount:" + taskInfo.getPoolOrder() + ":" + taskInfo.getDistrictId());
        if (countLine != null) {
            count = Integer.parseInt(countLine);
        }
        Set<Long> choseUser = new HashSet<>();

        if (userIds == null || userIds.size() == 0) {
            return choseUser;
        }
        QueryWrapper<TaskUser> wrapperTU = WrapperUtils.getWrapper(false);
        wrapperTU.in("user_id", userIds);
        //20221009  增加待抢单
        wrapperTU.in("status", "2", "3", "4");
        wrapperTU.eq("pool_order", taskInfo.getPoolOrder());
        wrapperTU.select("user_id,count(user_id) timing,user_name");
        wrapperTU.groupBy("user_id");
        List<TaskUser> taskUsers = taskUserService.list(wrapperTU);
        if (taskUsers != null && !taskUsers.isEmpty() && taskUsers.get(0).getUserId() != null) {
            Map<Long, TaskUser> maps = taskUsers.stream().collect(Collectors.toMap(TaskUser::getUserId, Function.identity(), (key1, key2) -> key2));
            for (Long userid : userIds) {
                if (maps.containsKey(userid)) {
                    TaskUser taskUser = maps.get(userid);
                    if (taskUser.getUserId() != null && taskUser.getTiming() < count) {
                        choseUser.add(taskUser.getUserId());
                    }
                } else {
                    choseUser.add(userid);
                }
            }

        } else {
            choseUser = new HashSet<>(userIds);
        }
        return choseUser;
    }


    /*************
     * 9,设备维护类任务自动完成
     * 220519，贾剑王恒通知取消自动完成
     * 221017,1.1.1 开启自动完成
     * 221121,1.1.3 增加自动完成开关
     */
    @Scheduled(cron = "* * * * * ?")
    public void taskFinishCommandHandle() {
        String taskCommandJson = redisService5.rightPop("taskFinishCommand");
        while (taskCommandJson != null) {
            TaskCommandInfo taskCommandInfo = JSONObject.parseObject(taskCommandJson, new TypeReference<TaskCommandInfo>() {
            });

            log.info("【taskFinishCommandHandle】" + taskCommandJson);
            TaskType taskType = taskTypeService.getById(taskCommandInfo.getTaskTypeId());
            User user = null;
            if (taskCommandInfo.getUserId() != null) {
                user = userService.getById(taskCommandInfo.getUserId());
            }
            boolean devOpsFlag = redisService5.isMember("OperateAssignmentTypes", taskCommandInfo.getTaskTypeId().toString());
            if (devOpsFlag) {
                QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
                wrapper.lt("status", 5);
                wrapper.eq("sn_code", taskCommandInfo.getSnCode());
                wrapper.eq("type_id", taskCommandInfo.getTaskTypeId());
                wrapper.eq("task_type", 1);
                List<TaskInfo> list = taskInfoService.list(wrapper);
                Date curTime = new Date();
                if (list.isEmpty()) {
                    log.info("【taskFinishCommandHandle】任务未找到:" + taskCommandJson);
                    taskCommandJson = redisService5.rightPop("taskFinishCommand");
                    continue;
                } else {
                    for (TaskInfo taskInfo : list) {
                        if(taskInfo.getClockFlag()!=null&&taskInfo.getClockFlag()!=0){
                            //20221121
                            setTaskStatusLog(new Date(), taskInfo, -3, "任务打卡强制任务开关开启，不自动完成");
                            continue;
                        }
                        Date createTime = taskInfo.getCreateTime();
                        String finishTimeStr = DateToConverter.getDateAddOrSub(12, taskInfo.getTiming(), createTime);
                        Date date = DateToConverter.parseDate(finishTimeStr, 5);
                        if (date.getTime() > curTime.getTime()) {
                            taskInfo.setStatus(5);
                        } else {
                            taskInfo.setStatus(6);
                        }
                        taskInfo.setFinishTime(curTime);
                        taskInfoService.updateById(taskInfo);

                        QueryWrapper<TaskUser> updateWrapper = WrapperUtils.getWrapper(false);
                        updateWrapper.eq("task_id", taskInfo.getId());
                        List<TaskUser> taskUserList = taskUserService.list(updateWrapper);
                        if (taskUserList.isEmpty()) {
                            supplementTaskUser(user, taskInfo);
                        } else {
                            Boolean userFlag = false;
                            for (TaskUser taskUser : taskUserList) {

                                //20221021 蓝湖中新增设备维护任务自动完成说明：
                                //1.未抢单：任务完成后，不记录完成人员
                                //2.已接单：任务完成后，完成人员为接单人员

//                                if (taskUser.getUserId() == taskCommandInfo.getUserId() || taskUser.getUserId() == 0) {
                                if (taskUser.getStatus() >= 3) {
                                    userFlag = true;
                                    taskUser.setStatus(taskInfo.getStatus());
                                    taskUser.setFinishTime(curTime);
                                    taskUser.setUserId(taskCommandInfo.getUserId());
                                    if (user != null) {
                                        taskUser.setUserName(user.getName());
                                        taskUser.setMobile(user.getMobile());
                                    }
                                } else if (taskInfo.getUserStatus() == 0) {
                                    taskUser.setSoftDelete(1);
                                } else {
                                    taskUser.setStatus(taskInfo.getStatus());
                                    taskUser.setFinishTime(curTime);
                                }
                                taskUser.setModifyTime(curTime);
                                taskUserService.updateById(taskUser);
                            }
                            //计划外人员完成
//                            if (!userFlag) {
//                                supplementTaskUser(user, taskInfo);
//                            }
                        }
                    }
                }
            }
            taskCommandJson = redisService5.rightPop("taskFinishCommand");
        }
    }

    private void supplementTaskUser(User curUser, TaskInfo taskInfo) {
        TaskUser taskUser = createTaskUser(new Date(), taskInfo, null);
        taskUser.setStatus(taskInfo.getStatus());
        if (curUser != null) {
            taskUser.setUserId(curUser.getId());
            taskUser.setUserName(curUser.getName());
            taskUser.setMobile(curUser.getMobile());
        }
        taskUser.setModifyTime(new Date());
        taskUserService.updateById(taskUser);
    }
}
