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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Sets;
import com.google.common.base.Joiner;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.supervision.business.constants.XJConstant;
import com.yeejoin.amos.supervision.business.dao.mapper.PlanMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.PlanTaskDetailMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.PointMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.RoutePointItemMapper;
import com.yeejoin.amos.supervision.business.dao.repository.*;
import com.yeejoin.amos.supervision.business.dto.OrgUsrFormDto;
import com.yeejoin.amos.supervision.business.entity.mybatis.CheckChkExListBo;
import com.yeejoin.amos.supervision.business.entity.mybatis.PointCheckDetailBo;
import com.yeejoin.amos.supervision.business.feign.Business;
import com.yeejoin.amos.supervision.business.feign.EquipFeign;
import com.yeejoin.amos.supervision.business.feign.JCSFeignClient;
import com.yeejoin.amos.supervision.business.param.CheckPtListPageParam;
import com.yeejoin.amos.supervision.business.param.PlanTaskPageParam;
import com.yeejoin.amos.supervision.business.service.intfc.ICheckService;
import com.yeejoin.amos.supervision.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.supervision.business.util.PlanTaskUtil;
import com.yeejoin.amos.supervision.business.util.Toke;
import com.yeejoin.amos.supervision.business.vo.CalDateVo;
import com.yeejoin.amos.supervision.business.vo.CodeOrderVo;
import com.yeejoin.amos.supervision.business.vo.LeavePlanTaskVo;
import com.yeejoin.amos.supervision.business.vo.PlanTaskVo;
import com.yeejoin.amos.supervision.common.enums.PlanStatusEnum;
import com.yeejoin.amos.supervision.common.enums.PlanTaskDetailIsFinishEnum;
import com.yeejoin.amos.supervision.common.enums.PlanTaskFinishStatusEnum;
import com.yeejoin.amos.boot.biz.common.enums.RuleTypeEnum;
import com.yeejoin.amos.supervision.core.common.request.CommonPageable;
import com.yeejoin.amos.supervision.core.common.response.AppCheckInputRespone;
import com.yeejoin.amos.supervision.core.common.response.AppPointCheckRespone;
import com.yeejoin.amos.supervision.core.util.DateUtil;
import com.yeejoin.amos.supervision.core.util.StringUtil;
import com.yeejoin.amos.supervision.dao.entity.Check;
import com.yeejoin.amos.supervision.dao.entity.Plan;
import com.yeejoin.amos.supervision.dao.entity.PlanTask;
import com.yeejoin.amos.supervision.dao.entity.PlanTaskDetail;
import com.yeejoin.amos.supervision.dao.entity.Point;
import com.yeejoin.amos.supervision.exception.YeeException;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import com.yeejoin.amos.supervision.quartz.IJobService;
import org.apache.commons.collections.CollectionUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
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 IPointInputItemDao pointInputItemDao;

	@Autowired
	private RoutePointItemMapper routePointItemMapper;

	@Autowired
	private RulePlanService rulePlanService;

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	PointMapper pointMapper;

	@Autowired
	private JCSFeignClient jcsFeignClient;

	// 防火监督检查负责人角色名称
	@Value("${supervision.person.charger.role:Person_charge_unit_fire_protection_supervision_inspection}")
	private String supervisionPersonChargerRole;

	@Override
	public Page<HashMap<String, Object>> getPlanTaskInfo(PlanTaskPageParam params) {
		long total = planTaskMapper.countPlanTask(params);
		List<HashMap<String, Object>> content = planTaskMapper.getPlanTaskInfo(params);
		return new PageImpl<>(content, params, total);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void reGenPlanTask(HashMap<String, Object> param) throws ParseException {
		// 1.公共参数准备
		String planId = param.get("planId").toString();// 重做的计划编号id
		String strBeginDate = 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 (StringUtil.isNotEmpty(plan.getUserId())) {
			// 2.数据必输校验，不满足直接return，不再向下进行
			Boolean fileFlag = PlanTaskUtil.checkMustFile(plan);
			if (!fileFlag) {
				return;
			}

			// 3.计算生成数据的日期区间（前10位：yyyy-MM-dd）
			CalDateVo vo = PlanTaskUtil.reGenPlanTaskData(plan, strBeginDate, 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(strBeginDate, strEndDate, plan.getUserId(), plan.getOrgCode());
		}
	}

	@Override
	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");// 下一天
		// 根据计划状态5，6和next_gen_date查询需要生成任务的计划
		List<Plan> planList = iplanDao.queryScheduledPlan(strDate,
				String.valueOf(PlanStatusEnum.EXAMINE_DEVELOPED.getValue()),
				String.valueOf(PlanStatusEnum.IN_EXECUTION.getValue()));
		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 = 7,已完成
			if (!vo.getIsGenData()) {
				paramMap.put("status", PlanStatusEnum.COMPLETED.getValue());
				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);
		}
	}

	/*
	 * 用于隐患导入之后的任务生成，不能使用时间获取所有的任务，而是当前时间的任务
	 * 
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean taskExecutionImportPlan(Long id) {
		Optional<Plan> planList = iplanDao.findById(id);
		Plan plan=planList.get();
		Date now = new Date();// 今天
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String tomorrow = DateUtil.getIntervalDateStr(now, 1, "yyyy-MM-dd");// 下一天
		if (planList == null ) {
			log.info(" 暂无待生成执行数据的计划");
			return false;
		}
		// 2.循环遍历执行
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
			if (StringUtils.isEmpty(plan.getUserId()))
				return false;
			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);// 更新为明天
				return true;
			}
			// 2.2.计算生成数据的日期区间
			CalDateVo vo = PlanTaskUtil.reGenPlanTaskData(plan, tomorrow, tomorrow);

			// 计划未开始，则更新生成时间为明天
			if (null == vo) {
				paramMap.put("next_gen_date", tomorrow);
				planMapper.updPlanStatusOrGenDate(paramMap);// 更新为明天
				return true;
			}
			// 计划已过期,则更新status = 7,已完成
			if (!vo.getIsGenData()) {
				paramMap.put("status", PlanStatusEnum.COMPLETED.getValue());
				planMapper.updPlanStatusOrGenDate(paramMap);
				return true;
			}

			// 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);// 更新为明天
				return true;
			} else if (XJConstant.UPD_PLAN_STATUS.equals(vo.getUpdFlag())) {
				paramMap.put("status", XJConstant.PLAN_STATUS_STOP);
				planMapper.updPlanStatusOrGenDate(paramMap);// 更新status = 1,停用
				return true;
			}

			// 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);
			return true;
	}

	/**
	 * 删除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.生成含有人员信息的日期执行数据
		return PlanTaskUtil.genWholeExeData(timeList, plan);
	}

	/**
	 * 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);
		}
		try {
			// 是否固定日期
			String isFixDate = plan.getIsFixedDate();
			List<Long> pointIdList = iRoutePointDao.queryRoutePointIds(plan.getRouteId());
			int pointNum = iRoutePointDao.countRoutePoint(plan.getRouteId());
			long batchNo = now.getTime();
			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 userName = list.get(i).get("USER_NAME") == null ? "" : list.get(i).get("USER_NAME").toString();
				PlanTask planTask = iplanTaskDao.findByUserIdAndBeginTimeAndEndTimeAndPlanIdAndRouteId(userId,
						startTime, endTime, plan.getId(), plan.getRouteId());
				if (planTask != null) {
					continue;
				}
				planTask = new PlanTask();
				planTask.setOrgCode(plan.getOrgCode());
				planTask.setUserName(userName);
				planTask.setPlanId(plan.getId());
				planTask.setBatchNo(batchNo);
				planTask.setRouteId(plan.getRouteId());
				planTask.setInOrder(plan.getInOrder());
				planTask.setUserId(userId);
				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);
				long planId = planTask.getId();
				for (Number pointId : pointIdList) {
					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");
					}

					// 查询点下检查项的个数
//                    List<PointInputItem> pointInputItemByPointId = pointInputItemDao.getPointInputItemByPointId(pointId.longValue());
					Long routeId = plan.getRouteId();
					int itemCount = routePointItemMapper.getPointItemCount(routeId, pointId.longValue());
					planTaskDetailInstance.setItemNum(itemCount);

					// 2.保存执行数据明细表
					planTaskDetail.saveAndFlush(planTaskDetailInstance);

				}
				sendMessage(plan);
				// 定时任务监控
				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);
		}
	}

	public void sendMessage(Plan plan) throws Exception {
		// 查询检查对象对应防火监督负责人id
		List<String> extraUserIds = Lists.newArrayList();
		List<Point> pointList = pointMapper.getPointByPlanId(String.valueOf(plan.getId()));
		if (!ValidationUtil.isEmpty(pointList)) {
			List<String> originalIdList = Lists.transform(pointList, Point::getOriginalId);
			List<OrgUsrFormDto> personList = jcsFeignClient
					.getPersonListByCompanyIdList(Joiner.on(",").join(originalIdList)).getResult();
			List<String> personIdList = Lists.transform(personList, OrgUsrFormDto::getAmosOrgId);
			List<RoleModel> roleList = Privilege.roleClient.queryRoleList(supervisionPersonChargerRole, null)
					.getResult();
			if (!ValidationUtil.isEmpty(roleList)) {
				List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient
						.queryByRoleId(String.valueOf(roleList.get(0).getSequenceNbr()), null).getResult();
				if (!ValidationUtil.isEmpty(agencyUserModelList)) {
					agencyUserModelList.forEach(userModel -> {
						if (personIdList.contains(userModel.getUserId())) {
							extraUserIds.add(userModel.getUserId());
						}
					});
				}
			}
		}
		log.info(String.format("计划对象：%s", JSON.toJSON(plan)));
		// 规则推送消息
		rulePlanService.addPlanRule(plan, null, RuleTypeEnum.消息型计划生成, extraUserIds);// 根据bug4150 将此处的计划生成的枚举值变成了消息，既TASK ->
																					// NOTIFY
		String userIdString = plan.getUserId();
		FeignClientResult amosIdListByUserIds = jcsFeignClient.getAmosIdListByUserIds(userIdString);
		List<String> result = (List<String>) amosIdListByUserIds.getResult();

		if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(result)) {
		//	String[] userIdArr = userIdString.split(",");
		//	 List<String>  userIdList =	Arrays.asList(userIdArr);
			// 规则推送消息
				rulePlanService.addPlanRule(plan, null, RuleTypeEnum.任务型计划生成, result);
				// 根据bug5569 
		}
	}

	@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<HashMap<String, Object>> getPlanTasks(HashMap<String, Object> params, CommonPageable pageParam) {
		List<HashMap<String, Object>> content = Lists.newArrayList();
		ReginParams reginParam = JSON.parseObject(redisUtils
				.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(),
				ReginParams.class);
		params.put("loginUserId", reginParam.getPersonIdentity().getPersonSeq());
		long total = planTaskMapper.getPlanTasksCount(params);
		if (total == 0) {
			return new PageImpl<>(content, pageParam, total);
		}
		params.put("offset", pageParam.getOffset());
		params.put("pageSize", pageParam.getPageSize());
		content = planTaskMapper.getPlanTasks(params);
		content.forEach(c -> {
			if (c.containsKey("finishStatus")) {
				String finishStatusDesc = PlanTaskFinishStatusEnum
						.getName(Integer.parseInt(c.get("finishStatus").toString()));
				c.put("finishStatusDesc", finishStatusDesc);
			}
		});
		return new PageImpl<>(content, pageParam, total);
	}

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

	@Override
	public Map queryPlanTaskById(Long planTaskId) {
		Map map = new HashMap();
		map = planTaskMapper.queryPlanTaskById(planTaskId);
		if (map.containsKey("finishStatus")) {
			String finishStatusDesc = PlanTaskFinishStatusEnum
					.getName(Integer.parseInt(map.get("finishStatus").toString()));
			map.put("finishStatusDesc", finishStatusDesc);
		}
		return map;
	}

	@Override
	public Page<Map<String, Object>> getPlanTaskPoints(HashMap<String, Object> params, CommonPageable pageable) {
		List<Map<String, Object>> content = Lists.newArrayList();
		long total = planTaskMapper.getPlanTaskPointsCount(params);
		if (total == 0) {
			return new PageImpl<>(content, pageable, total);
		}
		params.put("offset", pageable.getOffset());
		params.put("pageSize", pageable.getPageSize());
		List<Map<String, Object>> result = planTaskMapper.getPlanTaskPoints(params);
		result.forEach(r -> {
			if (r.containsKey("finish")) {
				String isFinishDesc = PlanTaskDetailIsFinishEnum.getName(Integer.parseInt(r.get("finish").toString()));
				r.put("isFinishDesc", isFinishDesc);
			}
		});
		return new PageImpl<>(result, pageable, total);
//        return result;
	}

	@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;
	}
}
