package com.yeejoin.amos.patrol.business.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.yeejoin.amos.boot.biz.common.constants.RuleConstant;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanTaskDetailMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.patrol.business.dao.repository.ICheckDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanTaskDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanTaskDetailDao;
import com.yeejoin.amos.patrol.business.dao.repository.IRoutePointDao;
import com.yeejoin.amos.patrol.business.dto.MsgRo;
import com.yeejoin.amos.patrol.business.entity.mybatis.CheckChkExListBo;
import com.yeejoin.amos.patrol.business.entity.mybatis.PointCheckDetailBo;
import com.yeejoin.amos.patrol.business.feign.Business;
import com.yeejoin.amos.patrol.business.feign.EquipFeign;
import com.yeejoin.amos.patrol.business.param.CheckPtListPageParam;
import com.yeejoin.amos.patrol.business.param.PlanTaskPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.ICheckService;
import com.yeejoin.amos.patrol.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.patrol.business.util.PlanTaskUtil;
import com.yeejoin.amos.patrol.business.util.Toke;
import com.yeejoin.amos.patrol.business.vo.CalDateVo;
import com.yeejoin.amos.patrol.business.vo.CodeOrderVo;
import com.yeejoin.amos.patrol.business.vo.LeavePlanTaskVo;
import com.yeejoin.amos.patrol.business.vo.PlanTaskVo;
import com.yeejoin.amos.patrol.common.enums.NotifyBusinessTypeEum;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.response.AppCheckInputRespone;
import com.yeejoin.amos.patrol.core.common.response.AppPointCheckRespone;
import com.yeejoin.amos.patrol.core.util.DateUtil;
import com.yeejoin.amos.patrol.core.util.StringUtil;
import com.yeejoin.amos.patrol.dao.entity.Check;
import com.yeejoin.amos.patrol.dao.entity.Plan;
import com.yeejoin.amos.patrol.dao.entity.PlanTask;
import com.yeejoin.amos.patrol.dao.entity.PlanTaskDetail;
import com.yeejoin.amos.patrol.exception.YeeException;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;
import com.yeejoin.amos.patrol.quartz.IJobService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.compress.utils.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("planTaskService")
public class PlanTaskServiceImpl implements IPlanTaskService {
    private final Logger log = LoggerFactory.getLogger(PlanTaskServiceImpl.class);
    @Autowired
    PlanTaskMapper planTaskMapper;
    @Autowired
    PlanTaskDetailMapper planTaskDetailMapper;
    @Autowired
    PlanMapper planMapper;
    @Autowired
    IPlanTaskDao iplanTaskDao;
    @Autowired
    IPlanDao iplanDao;
    @Autowired
    private ICheckDao checkDao;
    @Autowired
    private RemoteSecurityService remoteSecurityService;
    @Autowired
    private IPlanTaskDetailDao planTaskDetail;
    @Autowired
    IRoutePointDao iRoutePointDao;

    @Autowired
    IJobService jobService;

    @Autowired
    private ICheckService checkService;

    @Autowired
    private Business business;

    @Autowired
    private EquipFeign equipFeign;

    @Autowired
    private RulePlanService rulePlanService;

    @Autowired
    private RuleTrigger ruleTrigger;

    private final String packageId = "消息/addCheckRule";
    private final String msgType = "patrolSystem";
    private final String APP = "APP";
    private final String WEB = "WEB";
    private final String APP_WEB = "APP/WEB";
    private static final String TAB = "\r\n";


    @Override
    public Page<HashMap<String, Object>> getPlanTaskInfo(String toke, String product, String appKey, PlanTaskPageParam params) {
        long total = planTaskMapper.countPlanTask(params);
        List<HashMap<String, Object>> content = planTaskMapper.getPlanTaskInfo(params);

        String userIds = "";
        String deptIds = "";
        Set<String> set = new HashSet<>();
        Set<String> userDeptSet = new HashSet<>();
        content.forEach(s -> {
            if (s.containsKey("userName")) {
                set.add(s.get("userName").toString());
            }
            if (s.containsKey("userDept")) {
                userDeptSet.add(s.get("userDept").toString());
            }
        });

        List<String> userList = new ArrayList<>(set);
        List<String> userDeptList = new ArrayList<>(userDeptSet);

        Map<String, String> LoginName = new HashMap<>();
        Map<String, String> userMap = new HashMap<>();
        Map<String, String> depMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userList)) {
            userIds = String.join(",", userList);
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);
            userMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
            for (AgencyUserModel agencyUserModel : userModelList) {
                LoginName.put(agencyUserModel.getUserId(), agencyUserModel.getMobile() != null ? agencyUserModel.getMobile() : agencyUserModel.getLandlinePhone());
            }
        }
        if (!CollectionUtils.isEmpty(userDeptList)) {
            StringBuilder strBuilder = new StringBuilder();
            for (String str : userDeptList) {
                if (!StringUtils.isEmpty(str)) {
                    String[] userDeptArr = str.split("@");
                    if (strBuilder.length() < 1) {
                        strBuilder.append(userDeptArr[1]);
                    } else {
                        strBuilder.append(",");
                        strBuilder.append(userDeptArr[1]);
                    }
                }
            }
//          String depts = String.join(",", userDeptList);
//          List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey,strBuilder.toString());


            //新安全
            content.forEach(s -> {
                if (s.get("userDept").toString().indexOf("@") > 0) {
                    String[] dept = s.get("userDept").toString().split(",");
                    Arrays.asList(dept).stream().forEach(x -> {
                        String[] deptTemp = x.split("@");
                        List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, deptTemp[1]);
                        if (deptL.size() > 0) {
                            s.put("userDept", deptTemp[0] + "(" + deptL.get(0).get("departmentName") + ")");
                            depMap.put(deptTemp[0], deptL.get(0).get("departmentName").toString());
                        } else {
                            s.put("userDept", deptTemp[0] + "()");
                            depMap.put(deptTemp[0], "其他");
                        }

                    });
                } else {
                    String[] deptTemp = s.get("userDept").toString().split("@");
                    List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, deptTemp[1]);
                    if (deptL.size() > 0) {
                        s.put("userDept", deptTemp[0] + "(" + deptL.get(0).get("departmentName") + ")");
                        depMap.put(deptTemp[0], deptL.get(0).get("departmentName").toString());
                    } else {
                        s.put("userDept", deptTemp[0] + "()");
                        depMap.put(deptTemp[0], "其他");
                    }

                }

//                deptL.forEach(s1 -> {
//                    String[] deptTemp = s.get("userDept").toString().split("@");
//                    if (deptTemp[1].equals(s1.get("sequenceNbr")+"")) {
//                        s.put("deptName",s1.get("departmentName")+"");
//                        s.put("userDept", deptTemp[0] + "("+ s1.get("departmentName") +")" );
//                    }
//                });

            });

        }

        Map<String, String> finalUserMap = userMap;
        Map<String, String> finalDeptMap = LoginName;

        content.forEach(c -> {
            StringBuilder userNames = new StringBuilder("");
            List<String> userIdsList = Arrays.asList(c.get("userName").toString().split(","));
//            String userDept = c.get("userDept").toString();

            for (String userId : userIdsList) {
                userNames.append(finalUserMap.get(userId) + "(" + depMap.get(userId) + ")");
                userNames.append(",");

            }
            String deptTemp = c.get("userDept").toString();
            deptTemp = deptTemp.replace(c.get("userName").toString(), "");
            c.put("userName", userNames.substring(0, userNames.lastIndexOf(",")));
            c.put("userDept", userNames.substring(0, userNames.lastIndexOf(",")) + deptTemp);
            if (c.get("userName") != null)

                if (c.get("realName") != null)
                    c.put("LoginName", finalDeptMap.get(c.get("realName")));

        });

        Page<HashMap<String, Object>> result = new PageImpl<HashMap<String, Object>>(content, params, total);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reGenPlanTask(HashMap<String, Object> param) throws ParseException {
        //1.公共参数准备
        String planId = param.get("planId").toString();//重做的计划编号id
        String strBginDate = param.get("beginDate").toString();//开始日期（yyyy-MM-dd）
        String strEndDate = param.get("endDate").toString();//结束日期（yyyy-MM-dd）
        String flag = param.get("changeFlag").toString();//是否记为合格标记：0-否，1-是
        Plan plan = iplanDao.findById(Long.parseLong(planId)).get();//
        if (plan == null) {
            throw new YeeException("计划不存在");
        }

        if (StringUtil.isNotEmpty(plan.getUserId())) {
            //2.数据必输校验，不满足直接return，不再向下进行
            Boolean fileFlag = PlanTaskUtil.checkMustFile(plan);
            if (!fileFlag) {
                return;
            }

            //3.计算生成数据的日期区间（前10位：yyyy-MM-dd）
            CalDateVo vo = PlanTaskUtil.reGenPlanTaskData(plan, strBginDate, strEndDate);

            if (null == vo) {//计划未开始,则结束
                return;
            }


            if (!vo.getIsGenData()) {//日期不符合条件直接结束
                return;
            }

            //3.删除planTask表，按照计划id+日期
            deletePlanTaskAndDet(param);

            //5.执行数据生成（具体时间 + 人员）
            List<HashMap<String, Object>> list = genAllExeDate(plan, vo, XJConstant.REGEN_FLAG);

            //6.插入planTask及planTaskDetail
            insertPlanTaskAndDet(list, plan, flag, new Date());

            //7.重新统计计划
            if (ObjectUtils.isEmpty(plan.getUserId())) {
                return;
            }

            reformStatisticsPlanTask(strBginDate, strEndDate, plan.getUserId(), plan.getOrgCode());
            //8.通知3d数据统计进行更新（换流站全景监控）
            this.notifyBusinessRefresh(NotifyBusinessTypeEum.planTask.getCode());
        }


    }

    private void notifyBusinessRefresh(String type) {
        try {
            business.planTaskInsertToB(type);
        } catch (Exception e) {
            log.error("通知业务进行数据刷新失败->" + type);
        }
    }


    public void reformStatisticsPlanTask(String strBginDate, String strEndDate, String userId, String orgCode) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date startTime = sdf.parse(strBginDate);
        Date endTime = sdf.parse(strEndDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        Date currentDate = new Date();
        String strCurrentDate = sdf.format(currentDate);
        long abortTime = endTime.getTime();
        if (endTime.getTime() >= sdf.parse(strCurrentDate).getTime()) {
            abortTime = sdf.parse(strCurrentDate).getTime();
        }
        String[] ids = userId.split(",");
//        StringBuffer orgCodeBuffer = new StringBuffer();
//        Map<String,String> deptMap =new HashMap<>();
//        Set<Object> userIds =new HashSet<>();
//        for (int i = 0; i <ids.length ; i++) {
//            userIds.add(ids[i].toString());
//        }
//        Map<String,AgencyUserModel> agencyUserModelMap = remoteSecurityService.getUsersMap(toke.getToke(),toke.getProduct(),toke.getAppKey(),userIds);
//        List<Map<String, String>> idOrgCodeList = new ArrayList<>();
//        for(Map.Entry<String, AgencyUserModel> entry : agencyUserModelMap.entrySet()){
//            String id = entry.getKey();
//            AgencyUserModel agencyUserModels = entry.getValue();
//            StringBuffer agencyUserOrgcode = new StringBuffer();
//            if(agencyUserModelMap.size() > 0){
//                agencyUserModels.getCompanys().forEach(companyModel -> {
//                    agencyUserOrgcode.append(companyModel.getOrgCode()).append(",");
//                });
//            }
//            Map<String,String> map = new HashMap<>();
//            map.put(id,agencyUserOrgcode.toString().substring(0,agencyUserOrgcode.length()-1));
//        }
//
//        Map<String, String> userIdOrgCodeMap = new HashMap<>(ids.length);
//        if (!CollectionUtils.isEmpty(idOrgCodeList)) {
//            userIdOrgCodeMap = idOrgCodeList.stream().collect(Collectors.toMap(x-> String.valueOf(x.get(
//                    "id")),    x->x.get("org_code")));
//        }
        while (cal.getTime().getTime() <= abortTime) {
            String refDate = sdf.format(cal.getTime());
            for (String id : ids) {
                if (!ObjectUtils.isEmpty(id)) {
                    planTaskMapper.reformStatistics(id, refDate, orgCode);
//                    planTaskMapper.reformStatistics(id, refDate, userIdOrgCodeMap.get(id));

                }
            }
            cal.add(Calendar.DATE, 1);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void planTaskDet(String[] strArry) {
        if (strArry.length <= 0) {
            throw new YeeException("删除数据内容不能为空");
        }
        Set<Long> taskNos = new HashSet<>();
        for (String id : strArry) {
            PlanTaskDetail planTkDet = planTaskDetail.findById(Long.parseLong(id)).get();
            if (null != planTkDet) {
                taskNos.add(planTkDet.getTaskNo());
            }
        }
        planTaskMapper.planTaskDet(strArry);// 删除数据
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("IDS", new ArrayList<>(taskNos));
        param.put("FINISH_YES", XJConstant.PLAN_TASK_DET_FINISH_YES);
        planTaskMapper.updatePlanTaskPtInfo(param);// 更新主表，点数量，完成数量
    }

    @Override
    public List<PlanTaskVo> planTaskReport(String toke, String product, String appKey, PlanTaskPageParam param) {
        List<PlanTaskVo> content = planTaskMapper.getPlanTaskInfoList(param);

        String userIds = "";
        String deptIds = "";
        Set<String> set = new HashSet<>();
        Set<String> deptIdSet = new HashSet<>();
        content.forEach(s -> {
            if (s.getUserName() != null) {
                set.add(s.getUserName());
            }
            if (s.getDeptId() > 0) {
                deptIdSet.add(s.getDeptId() + "");
            }
        });

        List<String> userList = new ArrayList<>(set);
        List<String> deptList = new ArrayList<>(deptIdSet);

        Map<String, String> LoginName = new HashMap<>();
        Map<String, String> userMap = new HashMap<>();
        Map<String, String> depMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userList)) {
            userIds = String.join(",", userList);
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);
            userMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
            for (AgencyUserModel agencyUserModel : userModelList) {
                LoginName.put(agencyUserModel.getUserId(), agencyUserModel.getMobile() != null ? agencyUserModel.getMobile() : agencyUserModel.getLandlinePhone());
            }
        }
//        if(!CollectionUtils.isEmpty(deptList)){
//        String	dept = String.join(",", deptList);
//            List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey,dept);
//            if(deptL!=null&&deptL.size()>0){
//            	  //新安全
//            	content.forEach(s -> {
//            		deptL.forEach(s1 -> {
//                        if ((s.getDeptId()+"").equals(s1.get("sequenceNbr")+"")) {
//                            s.setDeptName(s1.get("departmentName")+"");
//                        }
//                    });
//
//                });
//            }
//        }
        //新安全
        content.forEach(s -> {
            StringBuffer buffer = new StringBuffer();
            if (s.getUserDept().indexOf("@") > 0) {
                String[] dept = s.getUserDept().split(",");
                Arrays.asList(dept).stream().forEach(x -> {
                    String[] deptTemp = x.split("@");
                    List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, deptTemp[1]);
                    if (deptL.size() > 0) {
                        buffer.append(deptL.get(0).get("departmentName")).append(",");
                    } else {
                        buffer.append("其他").append(",");
                    }

                });
            } else {
                String[] deptTemp = s.getUserDept().split(",");
                List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, deptTemp[1]);
                if (deptL.size() > 0) {
                    buffer.append(deptL.get(0).get("departmentName")).append(",");
                } else {
                    buffer.append("其他").append(",");
                }

            }
            s.setDeptName(buffer.substring(0, buffer.length() - 1));
        });
        Map<String, String> finalUserMap = userMap;
        content.forEach(c -> {
            StringBuilder userNames = new StringBuilder("");
            List<String> userIdsList = Arrays.asList(c.getUserName().split(","));
            for (String userId : userIdsList) {
                userNames.append(finalUserMap.get(userId));
                userNames.append(",");
            }
            c.setUserName(userNames.toString());
        });


        return content;
    }

    /**
     * 自动任务执行
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void taskExecution(String runDate) {
        //1.扫描plan表查询，需要生成执行数据的任务信息，无则return
        Date now = new Date();//今天
        if (runDate != null) {//上送则已上送的为准
            now = DateUtil.str2Date(runDate, "yyyyMMdd");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = df.format(now);
        String tomorrow = DateUtil.getIntervalDateStr(now, 1, "yyyy-MM-dd");//下一天
        List<Plan> planList = iplanDao.queryScheduledPlan(strDate, XJConstant.PLAN_STATUS_START);
        if (planList == null || planList.size() <= 0) {
            log.info(strDate + " " + " 暂无待生成执行数据的计划");
            return;
        }
        //2.循环遍历执行
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        for (Plan plan : planList) {
            if (StringUtils.isEmpty(plan.getUserId()))
                continue;
            paramMap.clear();
            paramMap.put("id", plan.getId());
            //2.1计划数据合法性校验
            Boolean fileFlag = PlanTaskUtil.checkMustFile(plan);
            if (!fileFlag) {
                paramMap.put("next_gen_date", tomorrow);
                planMapper.updPlanStatusOrGenDate(paramMap);//更新为明天
                continue;
            }
            //2.2.计算生成数据的日期区间
            CalDateVo vo = PlanTaskUtil.reGenPlanTaskData(plan, tomorrow, tomorrow);

            //计划未开始，则更新生成时间为明天
            if (null == vo) {
                paramMap.put("next_gen_date", tomorrow);
                planMapper.updPlanStatusOrGenDate(paramMap);//更新为明天
                continue;
            }
            //计划已过期,则更新status = 1,停用
            if (!vo.getIsGenData()) {
                paramMap.put("status", XJConstant.PLAN_STATUS_STOP);
                planMapper.updPlanStatusOrGenDate(paramMap);
                continue;
            }

            //2.3.执行数据生成（具体时间 + 人员）
            List<HashMap<String, Object>> list = genAllExeDate(plan, vo, XJConstant.SCHED_FLAG);

            if (XJConstant.UPD_PLAN_GEN_DATE.equals(vo.getUpdFlag())) {
                paramMap.put("next_gen_date", tomorrow);
                planMapper.updPlanStatusOrGenDate(paramMap);//更新为明天
                continue;
            } else if (XJConstant.UPD_PLAN_STATUS.equals(vo.getUpdFlag())) {
                paramMap.put("status", XJConstant.PLAN_STATUS_STOP);
                planMapper.updPlanStatusOrGenDate(paramMap);//更新status = 1,停用
                continue;
            }

            //2.4.删除今天可能重做生成的数据（计划重做后进行了计划的编辑）
            if (iplanTaskDao.findById(plan.getPlanTaskId()) != null && plan.getFirstFlag() == XJConstant.PLAN_FIRST_STATUS_YES)
                if (iplanTaskDao.existsById(plan.getPlanTaskId())) {
                    iplanTaskDao.deleteById(plan.getPlanTaskId());
                }

            //2.5.插入planTask及planTaskDetail
            insertPlanTaskAndDet(list, plan, XJConstant.SCHED_FLAG, now);

        }
    }

    /**
     * 删除plantask及det
     *
     * @param param
     */
    public void deletePlanTaskAndDet(HashMap<String, Object> param) {
        param.put("beginDate", param.get("beginDate") + " " + "00:00:00");
        param.put("endDate", param.get("endDate") + " " + "23:59:59");
        List<Long> ids = planTaskMapper.getGenPlanTask(param);
        for (long id : ids) {
            iplanTaskDao.deleteById(id);
            ;
        }

    }

    /**
     * 执行数据生成
     *
     * @param plan
     * @param vo
     * @return
     */
    public List<HashMap<String, Object>> genAllExeDate(Plan plan, CalDateVo vo, String flag) {
        //1.生成前8位日期（yyyy-MM-dd）
        List<HashMap<String, Date>> list = PlanTaskUtil.genExeDate(plan, vo, flag);
        if (list == null || list.size() <= 0) {
            vo.setUpdFlag(XJConstant.UPD_PLAN_GEN_DATE);
            return null;
        }
        //2.生成完整时间（yyyy-MM-dd HH:mm:ss）
        List<HashMap<String, Object>> timeList = PlanTaskUtil.genWholeExeDate(list, plan);
        if (timeList == null || timeList.size() <= 0) {
            vo.setUpdFlag(XJConstant.UPD_PLAN_STATUS);
        }
        //3.生成含有人员信息的日期执行数据
        List<HashMap<String, Object>> dataList = PlanTaskUtil.genWholeExeData(timeList, plan);
        return dataList;
    }


    /**
     * plantask及det入库
     *
     * @param list
     * @param plan
     * @param flag 是否初始状态0-初始 1-非初始
     */
    public void insertPlanTaskAndDet(List<HashMap<String, Object>> list, Plan plan, String flag, Date now) {
        if (list == null || list.size() <= 0) {
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("id", plan.getId());
            paramMap.put("next_gen_date", DateUtil.formatDatrToStr(now, "yyyy-MM-dd"));
            planMapper.updPlanStatusOrGenDate(paramMap);// 更新下次任务生成日期
        }
        Toke toke = remoteSecurityService.getServerToken();
        Map<String, String> deptMap = new HashMap<>();
        Map<String, Object> nameMap = new HashMap<>();
        try {
            String isFixDate = plan.getIsFixedDate();// 是否固定日期
            List<Long> pointIdList = iRoutePointDao.queryRoutePointIds(plan.getRouteId());
            int pointNum = iRoutePointDao.countRoutePoint(plan.getRouteId());
            long batchNo = now.getTime();

            List<AgencyUserModel> agencyUserModels = remoteSecurityService.listUserByUserIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), plan.getUserId());
            for (int i = 0; i < agencyUserModels.size(); i++) {
                //遍历获取orgcode
                nameMap.put(agencyUserModels.get(i).getUserId(), agencyUserModels.get(i).getRealName());
            }
            Set<String> departmentIds = new HashSet<>();
            List<String> depts = Arrays.asList(plan.getUserDept().split(","));
            depts.stream().forEach(dept -> {
                deptMap.put(dept.substring(0, dept.indexOf("@")), dept.substring(dept.indexOf("@") + 1));
            });
            for (String entry : deptMap.keySet()) {
                String entryValue = deptMap.get(entry);
                departmentIds.add(entryValue);
            }

            StringBuffer departmentIdBuffer = new StringBuffer();
            Iterator<String> it = departmentIds.iterator();
            while (it.hasNext()) {
                departmentIdBuffer.append(it.next()).append(",");
            }
            Map<String, String> orgCodeMap = new HashMap<>();

            if (departmentIds.size() > 0) {
                List<DepartmentModel> departmentModels = remoteSecurityService.getlistDepartmentByDeptIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), departmentIdBuffer.toString().substring(0, departmentIdBuffer.toString().length() - 1));
                for (String key : deptMap.keySet()) {
                    String entryValue = deptMap.get(key);
                    if ("-1".equals(entryValue)) {
                        orgCodeMap.put(key, plan.getOrgCode());
                        continue;
                    }
                    for (DepartmentModel departmentModel : departmentModels) {
                        if (entryValue.equals(departmentModel.getSequenceNbr().toString())) {
                            orgCodeMap.put(key, departmentModel.getOrgCode());
                        }
                    }
                }
            }

            for (int i = 0; i < list.size(); i++) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String startTime = list.get(i).get("BEGIN_TIME").toString();
                String endTime = list.get(i).get("END_TIME").toString();
                String userId = list.get(i).get("USER_ID") == null ? "-1" : list.get(i).get("USER_ID").toString();
                String userDept = list.get(i).get("USER_DEPT") == null ? "-1" : list.get(i).get("USER_DEPT").toString();
                PlanTask planTask = iplanTaskDao.findByUserIdAndBeginTimeAndEndTimeAndPlanIdAndRouteId(userId, startTime, endTime, plan.getId(), plan.getRouteId());
                if (planTask != null) {
                    continue;
                }
                planTask = new PlanTask();

                //修改巡检p_plan_task orgcode为执行人的org_code  -- add by wujunkai 20201216
                if (plan.getUserDept().indexOf(",") > 0 && plan.getIsSingleExecution() != true) {

                    Set<String> orgCodes = new HashSet<>();
                    StringBuffer nameBuffer = new StringBuffer();
                    orgCodeMap.forEach((key, entryValue) -> {
                        orgCodes.add(entryValue);
                    });
                    for (Map.Entry<String, Object> entry : nameMap.entrySet()) {
                        String entryValue = entry.getValue().toString();
                        nameBuffer.append(entryValue).append(",");
                    }
                    planTask.setOrgCode(orgCodes.toString().substring(1, orgCodes.toString().length() - 1));
                    planTask.setUserName(nameBuffer.toString().substring(0, nameBuffer.toString().length() - 1));

                } else {
                    planTask.setOrgCode(orgCodeMap.get(userId));
                    planTask.setUserName(nameMap.get(userId).toString());
                }

                planTask.setPlanId(plan.getId());
                planTask.setBatchNo(batchNo);
                planTask.setRouteId(plan.getRouteId());
                planTask.setInOrder(plan.getInOrder());
                planTask.setUserId(userId);
                planTask.setUserDept(userDept);
                planTask.setPointNum(pointNum);
                if (XJConstant.FIX_DATE_NO.equals(isFixDate)) {
                    if (sdf.parse(startTime).getTime() <= now.getTime() && sdf.parse(endTime).getTime() >= now.getTime()) {
                        planTask.setFinishStatus(XJConstant.TASK_STATUS_DEAL);
                        planTask.setFinishNum(0);
                    } else {
                        if (sdf.parse(endTime).getTime() < now.getTime()) {
                            planTask.setFinishStatus(XJConstant.TASK_STATUS_TIMEOUT);
                            planTask.setFinishNum(0);
                        }
                    }
                } else {
                    if (sdf.parse(startTime).getTime() <= now.getTime() && sdf.parse(endTime).getTime() >= now.getTime()) {
                        planTask.setFinishStatus(XJConstant.TASK_STATUS_DEAL);
                        planTask.setFinishNum(0);
                    }
                    if (sdf.parse(endTime).getTime() < now.getTime()) {
                        planTask.setFinishStatus(XJConstant.TASK_STATUS_TIMEOUT);
                        planTask.setFinishNum(0);
                    }
                }
                if (XJConstant.CHECK_CHANGE_YES.equals(flag)) {
                    planTask.setFinishStatus(XJConstant.TASK_STATUS_FINISH);
                    planTask.setFinishNum(pointNum);
                }
                if (XJConstant.FIX_DATE_YES.equals(isFixDate) || (XJConstant.FIX_DATE_NO.equals(isFixDate)
                        && XJConstant.PLAN_TYPE_DAY.equals(plan.getPlanType()))) {
                    planTask.setCheckDate(list.get(i).get("BEGIN_TIME").toString().substring(0, 10));
                }
                planTask.setBeginTime(startTime);
                planTask.setEndTime(endTime);
                // 1.保存执行数据主表
                iplanTaskDao.saveAndFlush(planTask);
                // 发送APP待办消息
                sendMessage(plan, planTask);
                String executorId = planTask.getUserId();
                long planId = planTask.getId();
                for (int i1 = 0; i1 < pointIdList.size(); i1++) {
                    Number pointId = pointIdList.get(i1);
                    PlanTaskDetail planTaskDetailInstance = new PlanTaskDetail();
                    planTaskDetailInstance.setPointId(pointId.longValue());
                    planTaskDetailInstance.setTaskNo(planId);
                    planTaskDetailInstance.setStatus("0");
                    if (XJConstant.TASK_STATUS_TIMEOUT == planTask.getFinishStatus()) {
                        planTaskDetailInstance.setIsFinish(Integer.parseInt(XJConstant.PLAN_TASK_DET_FINISH_OUT));
                        planTaskDetailInstance.setStatus("3");
                    }
                    if (XJConstant.CHECK_CHANGE_YES.equals(flag)) {
                        planTaskDetailInstance.setIsFinish(Integer.parseInt(XJConstant.PLAN_TASK_DET_FINISH_YES));
                        planTaskDetailInstance.setStatus("1");
                    }
                    // 2.保存执行数据明细表
                    planTaskDetail.saveAndFlush(planTaskDetailInstance);
                }
                // 定时任务监控
                jobService.planTaskAddJob(planTask);
            }

            // 3.如果为自动任务调用,则更新id，如果重做或且下次时间大于等于明天，则更新planTaskId到plan表
            Date genDate = DateUtil.str2Date(list.get(list.size() - 1).get("NEXT_GEN_DATE").toString(), "yyyy-MM-dd");//下次生成日期
            Date tomorrow = DateUtil.getIntervalDate(now, 1);//明天
            String strGenDate = list.get(list.size() - 1).get("NEXT_GEN_DATE").toString().substring(0, 10);
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("id", plan.getId());
            paramMap.put("next_gen_date", strGenDate);
            if (XJConstant.SCHED_FLAG.equals(flag)) {
                paramMap.put("plan_task_id", 0);//修改为初始值
                paramMap.put("first_flag", XJConstant.PLAN_FIRST_STATUS_NO);
            } else if (!XJConstant.SCHED_FLAG.equals(flag) && (genDate.getTime() - tomorrow.getTime() >= 0) && XJConstant.FIX_DATE_NO.equals(plan.getIsFixedDate())) {//更新日期及plantaskId到plan表
                long planTaskId = iplanTaskDao.findMaxIdByBatchNo(batchNo);
                paramMap.put("plan_task_id", planTaskId);// 更新新的任务id到plan
                paramMap.put("first_flag", XJConstant.PLAN_FIRST_STATUS_NO);
            }
            if (DateUtil.str2Date(strGenDate, "yyyy-MM-dd").getTime() - now.getTime() < 0 || org.apache.commons.lang.StringUtils.isBlank(strGenDate)) {
                paramMap.put("next_gen_date", DateUtil.formatDatrToStr(now, "yyyy-MM-dd"));
            }
            planMapper.updPlanStatusOrGenDate(paramMap);// 更新下次任务生成日期

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
//        return deptMap;
    }


    public void sendMessage(Plan plan, PlanTask planTask) throws Exception {
        MsgRo msgRo = new MsgRo();
        // 标题
        msgRo.setName(plan.getName());
        // 内容
        String body = "";
        body += "待执行巡检任务" + TAB;
        body += "巡检任务名称：" + plan.getName() + TAB;
        body += "执行时间：" + planTask.getBeginTime() + "-" + planTask.getEndTime();
        msgRo.setContent(body);
        // 接收人
        ArrayList<String> userIdList = new ArrayList<>();
        userIdList.add(planTask.getUserId());
        msgRo.setRecivers(userIdList);
        msgRo.setMsgType(msgType);
        msgRo.setTerminal(APP_WEB);
        msgRo.setSendTime(DateTime.now().toString());
        // 关联id
        msgRo.setRelationId(String.valueOf(plan.getId()));
        // 扩展参数
        HashMap<String, String> extras = new HashMap<>();
        extras.put("type", msgType);
        extras.put("planId", String.valueOf(plan.getId()));
        extras.put("planTaskId", String.valueOf(planTask.getId()));
        msgRo.setExtras(extras);
        msgRo.setIsSendApp(true);
        msgRo.setIsSendWeb(true);
        msgRo.setCategory(RuleConstant.TASK);
//        PushMsgParam pushMsgParam = new PushMsgParam();
//        rulePlanService.sendRule(pushMsgParam);
        log.info("巡检待办任务：%s {}", JSON.toJSON(msgRo));
        //触发规则
        ruleTrigger.publish(msgRo, packageId, new String[0]);
    }

    @Override
    public List<PlanTask> getPlanTaskByRouteId(Long routeId) {
        List<PlanTask> planTaskList = planTaskMapper.getPlanTaskByRouteId(routeId);
        return planTaskList;
    }

    @Override
    public void disablePlanTask(Long[] planTaskIds) {
        // planTask表中status字段置为1
        for (long planTaskId : planTaskIds) {
            List<PlanTask> planTaskList = getPlanTaskByRouteId(planTaskId);
            for (PlanTask planTask : planTaskList) {
                planTask.setStatus((byte) 1);
                iplanTaskDao.save(planTask);
            }
        }
    }

    @Override
    public List getPlanTaskInfo(HashMap<String, Object> param) {
        return planTaskMapper.getPlanTaskByPointId(param);
    }

    @Override
    public Map findPlanTaskByTaskIdAndPointId(long plantaskId, long pointId) {
        return planTaskDetailMapper.findPlanTaskByTaskIdAndPointId(plantaskId, pointId);
    }

    @Override
    public Page<Map<String, Object>> getPlanTasks(String toke, String product, String appKey, HashMap<String, Object> params) {
        CommonPageable pageParam = new CommonPageable();
        List<Map<String, Object>> content = Lists.newArrayList();
        long total = planTaskMapper.getPlanTasksCount(params);
        if (total == 0) {
            return new PageImpl<>(content, pageParam, total);
        }
        content = planTaskMapper.getPlanTasks(params);
        if (!CollectionUtils.isEmpty(content)) {
            Set<String> userIds = Sets.newHashSet();
            content.forEach(e -> {
                String userId = e.get("userId").toString();
                if (StringUtil.isNotEmpty(userId)) {
                    userIds.add(userId);
                }
            });
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, Joiner.on(",").join(userIds));
            Map<String, String> userModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
            List<String> userNames = new ArrayList<>();
            content.forEach(e -> {
                userNames.clear();
                String[] userIds1 = e.get("userId").toString().split(",");
                for (String userId : userIds1) {
                    if (!ObjectUtils.isEmpty(userModelMap.get(userId))) {
                        userNames.add(userModelMap.get(userId));
                    }
                }
                if (userNames.size() > 0) {
                    e.put("executiveName", Joiner.on(",").join(userNames));
                } else {
                    e.put("executiveName", " ");
                }
            });
            return new PageImpl<>(content, pageParam, total);
        }
        return new PageImpl<>(new ArrayList<>(), pageParam, 0);
    }

    @Override
    public Map queryPlanTaskById(Long planTaskId) {
        return planTaskMapper.queryPlanTaskById(planTaskId);
    }

    @Override
    public List getPlanTaskPoints(Long planTaskId) {
        return planTaskMapper.getPlanTaskPoints(planTaskId);
    }

    @Override
    public int getCurrentPlanTaskCount(String userId) {
        return planTaskMapper.getCurrentPlanTaskCount(userId);
    }

    @Override
    public List<PlanTaskVo> getPlanTaskListByIds(String toke, String product, String appKey, Long[] ids) {
        List<PlanTaskVo> content = planTaskMapper.getPlanTaskListByIds(ids);

        String userIds = "";
        String deptIds = "";
        Set<String> set = new HashSet<>();
        Set<String> deptIdSet = new HashSet<>();
        Map<Long, Set<String>> deptMap = new HashMap<>();
        content.forEach(s -> {
            String userDept = s.getUserDept();
            if (!ValidationUtil.isEmpty(userDept)) {
                String[] udStrs = userDept.split(",");
                for (String udStr : udStrs) {
                    try {
                        String[] split = udStr.split("@");
                        set.add(split[0]);
                        if (split.length > 1) {
                            if (!"-1".equals(split[1])) {
                                deptIdSet.add(split[1]);
                            }
                            if (!deptMap.containsKey(s.getId())) {
                                deptMap.put(s.getId(), new HashSet<>());
                            }
                            deptMap.get(s.getId()).add(split[1]);
                        }
                    } catch (Exception e) {
                    }
                }
            }
        });
        List<String> userList = new ArrayList<>(set);
        List<String> deptList = new ArrayList<>(deptIdSet);

        Map<String, String> LoginName = new HashMap<>();
        Map<String, String> userMap = new HashMap<>();
        Map<String, String> depMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userList)) {
            userIds = String.join(",", userList);
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);
            userMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
            for (AgencyUserModel agencyUserModel : userModelList) {
                LoginName.put(agencyUserModel.getUserId(), agencyUserModel.getMobile() != null ? agencyUserModel.getMobile() : agencyUserModel.getLandlinePhone());
            }
        }
        if (!CollectionUtils.isEmpty(deptList)) {
            String dept = String.join(",", deptList);
            List<LinkedHashMap> deptL = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, dept);
            if (deptL != null && deptL.size() > 0) {
                //新安全
                content.forEach(s -> {
                    Set<String> set1 = deptMap.get(s.getId());
                    if (!ValidationUtil.isEmpty(set1)) {
                        deptL.forEach(s1 -> {
                            if (set1.contains(s1.get("sequenceNbr"))) {
                                if (!ValidationUtil.isEmpty(s.getDeptName())) {
                                    s.setDeptName(s.getDeptName() + "," + s1.get("departmentName"));
                                } else {
                                    s.setDeptName(s1.get("departmentName").toString());
                                }
                            }
                        });
                        if (set1.contains("-1")) {
                            if (!ValidationUtil.isEmpty(s.getDeptName())) {
                                s.setDeptName(s.getDeptName() + "," + "其他");
                            } else {
                                s.setDeptName("其他");
                            }
                        }
                    }
                });
            }
        }
        Map<String, String> finalUserMap = userMap;
        content.forEach(c -> {
            StringBuilder userNames = new StringBuilder("");
            List<String> userIdsList = Arrays.asList(c.getUserName().split(","));
            for (String userId : userIdsList) {
                userNames.append(finalUserMap.get(userId));
                userNames.append(",");
            }
            c.setUserName(userNames.toString());
        });
        return content;
    }

    @Override
    public Page<CheckChkExListBo> getChkExList(String toke, String product, String appKey, CheckPtListPageParam param) {
        long total = planTaskMapper.countChkExListData(param);
        List<CheckChkExListBo> content = planTaskMapper.getChkExList(param);

        //获取用户联系方式
        String userIds = "";
        Set<String> set = new HashSet<>();
        content.forEach(s -> {
            if (s.getRealName() != null) {
                String[] sArr = s.getRealName().split(",");
                set.addAll(Arrays.asList(sArr));
            }
        });
        List<String> userList = new ArrayList<>(set);
        Map<String, AgencyUserModel> agencyUserModelMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userList)) {
            userIds = String.join(",", userList);
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);
            agencyUserModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, Function.identity()));
        }
        for (CheckChkExListBo bo : content) {
            ArrayList<String> names = new ArrayList<>();
            ArrayList<String> mobiles = new ArrayList<>();
            String nameStrings = String.join(",", names);

            String[] realNames = bo.getRealName().split(",");
            if (realNames.length > 1) {
                System.out.println("asd");
            }
            for (int i = 0; i < realNames.length; i++) {
                if (agencyUserModelMap.containsKey(realNames[i])) {
                    AgencyUserModel agencyUserModel = agencyUserModelMap.get(realNames[i]);
                    names.add(agencyUserModel.getRealName());
                    if (StringUtil.isNotEmpty(agencyUserModel.getMobile())) {
                        mobiles.add(agencyUserModel.getMobile());
                    }
                }

            }
            bo.setRealName(String.join(",", names));
            if (mobiles.size() > 0) {
                bo.setLoginName(String.join(",", mobiles));
            }
        }
        Page<CheckChkExListBo> result = new PageImpl<CheckChkExListBo>(content, param, total);
        return result;
    }

    @Override
    public Map<String, Object> getPlanTaskStatisticsForApp(HashMap<String, Object> params) {
        return planTaskMapper.getPlanTaskStatisticsForApp(params);
    }

    @Override
    public AppPointCheckRespone queryPointPlanTaskDetail(String toke, String product, String appKey, Long planTaskId, Long pointId) {
        AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
        Check check = checkDao.findByPlanTaskIdAndPointId(planTaskId, pointId);
        if (check != null) {
            pointCheckRespone = checkService.queryCheckPointDetail(toke, product, appKey, check.getId());
        } else {
            PointCheckDetailBo planPointInfo = planTaskMapper.getPointPlanTaskInfo(planTaskId, pointId);


            if (planPointInfo != null) {
                List<String> userIds = Arrays.asList(planPointInfo.getUsername().split(","));
                List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, planPointInfo.getUsername());
                Map<String, String> userModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
                if (userModelMap != null) {
                    List<String> userNameList = new ArrayList<>();
                    for (String userId : userIds) {
                        userNameList.add(userModelMap.get(userId));
                    }
                    userNameList.remove("");
                    userNameList.remove(null);
                    pointCheckRespone.setUsername(Joiner.on(",").join(userNameList));
                }
                DepartmentModel departmentBo = remoteSecurityService.getDepartmentByDeptId(toke, product, appKey, planPointInfo.getUsername());
                if (departmentBo != null) {
                    pointCheckRespone.setDepartmentName(departmentBo.getDepartmentName());
                }
                pointCheckRespone.setPointId(pointId);
                pointCheckRespone.setPointName(planPointInfo.getPointName());
                pointCheckRespone.setPointNo(planPointInfo.getPointNo());
                pointCheckRespone.setPointStatus("0");
                pointCheckRespone.setPlanName(planPointInfo.getPlanName());
                List<PointCheckDetailBo> pointInputs = planTaskMapper.getPointInputByRouteIdAndPointId(planPointInfo.getRouteId(), planPointInfo.getPointId());
                JSONObject appResponeMap = new JSONObject();
                pointInputs.forEach(action -> {
                    AppCheckInputRespone input = new AppCheckInputRespone();
                    input.setInputName(action.getInputName());
                    input.setCheckInputId(action.getCheckInputId());
                    input.setDataJson(action.getDataJson());
                    input.setIsMultiline(action.getIsMultiline());
                    input.setIsMust(action.getIsMust());
                    input.setItemType(action.getItemType());
                    input.setOrderNo(action.getOrderNo());
                    input.setPictureJson(action.getPictureJson());
                    input.setClassifyId(action.getClassifyId());
                    input.setClassifyName(action.getClassifyName());
                    String key = ObjectUtils.isEmpty(action.getClassifyName()) ? "其他" : action.getClassifyName();
                    if (appResponeMap.containsKey(key)) {
                        appResponeMap.getJSONArray(key).add(input);
                    } else {
                        List<AppCheckInputRespone> appCheckInputResponeList = new ArrayList<AppCheckInputRespone>();
                        appCheckInputResponeList.add(input);
                        appResponeMap.put(key, appCheckInputResponeList);
                    }
                });
                pointCheckRespone.setAppCheckInput(appResponeMap);
            } else {
                return null;
            }
        }

        return pointCheckRespone;
    }

    @Override
    public AppPointCheckRespone queryPointPlanTaskDetailInVersion2(String toke, String product, String appKey, Long planTaskId, Long pointId) {
        AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
        Check check = checkDao.findByPlanTaskIdAndPointId(planTaskId, pointId);
        if (check != null) {
            pointCheckRespone = checkService.queryCheckPointDetailInVersion2(toke, product, appKey, check.getId());
        } else {
            PointCheckDetailBo planPointInfo = planTaskMapper.getPointPlanTaskInfo(planTaskId, pointId);

            if (planPointInfo != null) {
                pointCheckRespone.setPointId(pointId);
                pointCheckRespone.setPointName(planPointInfo.getPointName());
                pointCheckRespone.setPointNo(planPointInfo.getPointNo());
                pointCheckRespone.setPointStatus("0");
                pointCheckRespone.setPlanName(planPointInfo.getPlanName());
                List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke, product, appKey, planPointInfo.getUserId());
                for (AgencyUserModel userModel : userModelList) {
                    pointCheckRespone.setUsername(userModel.getRealName());
                }
//                DepartmentModel departmentModel= remoteSecurityService.getDepartmentByDeptId(toke, product, appKey,planPointInfo.getCheckDepartmentId());
                DepartmentModel departmentModel = new DepartmentModel();
                pointCheckRespone.setDepartmentName(departmentModel.getDepartmentName());
                List<PointCheckDetailBo> pointInputs = planTaskMapper.getPointInputByRouteIdAndPointId(planPointInfo.getRouteId(), planPointInfo.getPointId());

                JSONObject appResponeMap = new JSONObject();
                pointInputs.forEach(action -> {
                    AppCheckInputRespone input = new AppCheckInputRespone();
                    input.setInputName(action.getInputName());
                    input.setCheckInputId(action.getCheckInputId());
                    input.setDataJson(action.getDataJson());
                    input.setIsMultiline(action.getIsMultiline());
                    input.setIsMust(action.getIsMust());
                    input.setItemType(action.getItemType());
                    input.setOrderNo(action.getOrderNo());
                    input.setPictureJson(action.getPictureJson());
                    input.setClassifyId(action.getClassifyId());
                    input.setClassifyName(action.getClassifyName());
                    String classifyName = action.getClassifyName();
                    if (!StringUtil.isNotEmpty(classifyName)) {
                        classifyName = "其他";
                    }
                    String riskDesc = action.getRiskDesc();
                    if (!StringUtil.isNotEmpty(riskDesc)) {
                        riskDesc = XJConstant.DEFAULT_RISKDESC;
                    }
                    JSONObject classifyJson;
                    if (appResponeMap.containsKey(classifyName)) {
                        classifyJson = appResponeMap.getJSONObject(classifyName);
                    } else {
                        classifyJson = new JSONObject();
                    }
                    JSONArray riskDescArr;
                    if (classifyJson.containsKey(riskDesc)) {
                        riskDescArr = classifyJson.getJSONArray(riskDesc);
                    } else {
                        riskDescArr = new JSONArray();
                    }
                    riskDescArr.add(action);
                    classifyJson.put(riskDesc, riskDescArr);
                    appResponeMap.put(classifyName, classifyJson);
                });
                pointCheckRespone.setAppCheckInput(appResponeMap);
            } else {
                return null;
            }
        }
        return pointCheckRespone;
    }

    @Override
    public String getCumulativePlanCountByOrgCode(String loginOrgCode) {
        return planTaskMapper.getCumulativePlanCountByOrgCode(loginOrgCode);
    }

    @Override
    public List<LeavePlanTaskVo> queryLeavePlanTask(HashMap<String, Object> params) {
        return planTaskMapper.queryLeavePlanTask(params);
    }

    @Override
    public List<CodeOrderVo> queryCodeOrderVo(HashMap<String, Object> params) {
        return planTaskMapper.queryCodeOrderVo(params);
    }

    @Override
    public PlanTask selectPlanTaskStatus(Long id) {
        // TODO Auto-generated method stub
        if (iplanTaskDao.existsById(id)) {
            return iplanTaskDao.findById(id).get();
        }
        return null;
    }

    @Override
    public void initPlanStatusOrGenDate() {
        planMapper.initUpdatePlanStatus();
        planMapper.initUpdatePlanNextGenDate();
    }

    @Override
    public List<Map<String, Object>> queryPlanTaskTimeAxis(Long userId, Integer createDate) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        String endTime = DateUtil.getShortCurrentDate();
        ;
        String beginTime = "";
        if (createDate != null && createDate == 7) {
            beginTime = DateUtil.getIntervalDateStr(new Date(), -7, "yyyy-MM-dd");
        } else if (createDate != null && createDate == 30) {
            beginTime = DateUtil.getIntervalDateStr(new Date(), -30, "yyyy-MM-dd");
        } else {
            beginTime = DateUtil.getShortCurrentDate();
        }

        params.put("beginTime", beginTime + " 00:00:00");
        params.put("endTime", endTime + " 23:59:59");
        List<Map<String, Object>> content = planTaskMapper.queryPlanTaskTimeAxis(params);
        if (!CollectionUtils.isEmpty(content)) {
            Set<String> userIds = Sets.newHashSet();
            content.forEach(e -> {

                String id = e.get("userId").toString();
                if (StringUtil.isNotEmpty(id)) {
                    userIds.add(id);
                }
            });
            Toke toke = remoteSecurityService.getServerToken();
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), Joiner.on(",").join(userIds));
            Map<String, String> userModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));

            content.forEach(e -> {
                StringBuffer userNames = new StringBuffer();
                List<String> userIds1 = Arrays.asList(e.get("userId").toString().split(","));
                for (String userId1 : userIds1) {
                    userNames.append(userModelMap.get(userId1)).append(",");
                }
                e.put("userName", userNames.substring(0, userNames.length() - 1));
                e.put("beginTime", DateUtil.formatDatrToStr((Date) e.get("beginTime"), DateUtil.LONG_PATTERN));
                e.put("endTime", DateUtil.formatDatrToStr((Date) e.get("endTime"), DateUtil.LONG_PATTERN));
            });
        }
        return content;
    }

    @Override
    public List<Map<String, Object>> queryTimeAxis(Long userId, Integer createDate) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        String endTime = DateUtil.getShortCurrentDate();
        ;
        String beginTime = "";
        if (createDate != null && createDate == 7) {
            beginTime = DateUtil.getIntervalDateStr(new Date(), -7, "yyyy-MM-dd");
        } else if (createDate != null && createDate == 30) {
            beginTime = DateUtil.getIntervalDateStr(new Date(), -30, "yyyy-MM-dd");
        } else {
            beginTime = DateUtil.getShortCurrentDate();
        }

        params.put("beginTime", beginTime + " 00:00:00");
        params.put("endTime", endTime + " 23:59:59");
        String structListString = equipFeign.getStructureNameAll();
        JSONObject jsonObject = JSONObject.parseObject(structListString);
        JSONArray structList = jsonObject.getJSONArray("result");
        List<Map<String, Object>> result = new ArrayList<>();

        List<Map<String, Object>> content = planTaskMapper.queryTimeAxis(params);
        if (!CollectionUtils.isEmpty(content)) {
            Set<String> userIds = Sets.newHashSet();
            content.forEach(e -> {

                String id = e.get("userId").toString();
                if (StringUtil.isNotEmpty(id)) {
                    userIds.add(id);
                }
            });
            Toke toke = remoteSecurityService.getServerToken();
            List<AgencyUserModel> userModelList = remoteSecurityService.listUserByUserIds(toke.getToke(), toke.getProduct(), toke.getAppKey(), Joiner.on(",").join(userIds));
            Map<String, String> userModelMap = userModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));

            content.forEach(e -> {
                StringBuffer userNames = new StringBuffer();
                List<String> userIds1 = Arrays.asList(e.get("userId").toString().split(","));
                for (String userId1 : userIds1) {
                    userNames.append(userModelMap.get(userId1)).append(",");
                }
                HashMap<String, Object> map = new HashMap();
                map.put("userName", userNames.substring(0, userNames.length() - 1));
                map.put("beginTime", DateUtil.formatDatrToStr((Date) e.get("beginTime"), DateUtil.LONG_PATTERN));
                map.put("endTime", DateUtil.formatDatrToStr((Date) e.get("endTime"), DateUtil.LONG_PATTERN));
                map.put("leftName", "巡检点");
                map.put("titleName", userNames.substring(0, userNames.length() - 1) + "-" + e.get("name").toString() + "-" + e.get("STATUS").toString());
                String structName = "";
                if (!StringUtils.isEmpty(e.get("risk_source_id"))) {
                    for (int i = 0; i < structList.size(); i++) {
                        if (structList.getJSONObject(i).get("id").equals(e.get("risk_source_id"))) {
                            structName = structList.getJSONObject(i).get("name").toString();
                        }
                    }
                } else {
                    structName = "无";
                }

                if (!StringUtils.isEmpty(e.get("executorDate"))) {
                    map.put("firstPropsValue", structName + "-" + e.get("executorDate"));
                } else {
                    map.put("firstPropsValue", structName + "-无");
                }

                result.add(map);
            });
        }
        return result;
    }
}
