package com.yeejoin.precontrol.common.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.Timer;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.module.common.api.dto.CreatExamDto;
import com.yeejoin.amos.boot.module.common.api.feign.AmosTrainingFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.KnowledgebaseFeignClient;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.InputItemDto;
import com.yeejoin.precontrol.common.dto.TaskRiskControlDto;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.CompanyEvaluationLog;
import com.yeejoin.precontrol.common.entity.HazardousWork;
import com.yeejoin.precontrol.common.entity.HazardousWorkResult;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.RiskWork;
import com.yeejoin.precontrol.common.entity.RiskWorkHazadousWork;
import com.yeejoin.precontrol.common.entity.RiskWorkMeasure;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskPersonFile;
import com.yeejoin.precontrol.common.entity.TaskRiskControl;
import com.yeejoin.precontrol.common.entity.TaskRiskControlPrePerson;
import com.yeejoin.precontrol.common.entity.TaskRiskControlTech;
import com.yeejoin.precontrol.common.entity.TaskRiskWorkMeasureResult;
import com.yeejoin.precontrol.common.entity.TaskTimedTask;
import com.yeejoin.precontrol.common.entity.UserEvaluationLog;
import com.yeejoin.precontrol.common.entity.publics.CommonPageable;
import com.yeejoin.precontrol.common.enums.InRiskRegionEnum;
import com.yeejoin.precontrol.common.enums.MessageAttributeEnum;
import com.yeejoin.precontrol.common.enums.MessageSubTypeEnum;
import com.yeejoin.precontrol.common.enums.MessageTypeEnum;
import com.yeejoin.precontrol.common.enums.SmallProPageEnum;
import com.yeejoin.precontrol.common.enums.SmallProQrColorEum;
import com.yeejoin.precontrol.common.enums.StatusEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonFileEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskControlStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskControlTechTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskStageEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskTechStageEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskTrajectoryStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskTimedTaskTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.WeChatMsgTemplateTypeEum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.exception.CommonException;
import com.yeejoin.precontrol.common.mapper.TaskRiskControlMapper;
import com.yeejoin.precontrol.common.param.RiskWorkParam;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import com.yeejoin.precontrol.common.service.ICompanyEvaluationLogService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IHazardousWorkRefInputItemService;
import com.yeejoin.precontrol.common.service.IHazardousWorkResultService;
import com.yeejoin.precontrol.common.service.IHazardousWorkService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IRiskWorkHazadousWorkService;
import com.yeejoin.precontrol.common.service.IRiskWorkMeasureService;
import com.yeejoin.precontrol.common.service.IRiskWorkService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.ITaskPersonFileService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlPrePersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlTechService;
import com.yeejoin.precontrol.common.service.ITaskRiskWorkMeasureResultService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.service.ITaskTimedTaskService;
import com.yeejoin.precontrol.common.service.IUserEvaluationLogService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.task.RiskTimerTask;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.PersonUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.BadCompanyVo;
import com.yeejoin.precontrol.common.vo.CompanyEvaluationLogVo;
import com.yeejoin.precontrol.common.vo.HazardousWorkVo;
import com.yeejoin.precontrol.common.vo.TaskFileVo;
import com.yeejoin.precontrol.common.vo.TaskPersonAndImageInfo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlAppVo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlDetailVo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlPrePersonVo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlTechVo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlVo;
import com.yeejoin.precontrol.common.vo.TaskWorkPersonVo;
import com.yeejoin.precontrol.common.vo.UserEvaluationLogVo;

import sun.misc.BASE64Encoder;

/**
 * 风险管控任务表 服务实现类
 *
 * @author duanwei
 * @date 2021-01-28
 */
@Service
public class TaskRiskControlServiceImpl extends ServiceImpl<TaskRiskControlMapper, TaskRiskControl>
		implements ITaskRiskControlService {

	@Autowired
	TaskRiskControlMapper taskRiskControlMapper;

	@Autowired
	ITaskService iTaskService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	ITaskPersonService iTaskPersonService;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	ITaskRiskControlPrePersonService iTaskRiskControlPrePersonService;

	@Autowired
	IRiskWorkHazadousWorkService iRiskWorkHazadousWorkService;

	@Autowired
	IHazardousWorkRefInputItemService IHazardousWorkRefInputItemService;

	@Autowired
	IHazardousWorkService iHazardousWorkService;

	@Autowired
	IHazardousWorkResultService iHazardousWorkResultService;

	@Autowired
	ITaskPersonFileService iTaskPersonFileService;

	@Autowired
	IUserEvaluationLogService iUserEvaluationLogService;

	@Autowired
	ICompanyEvaluationLogService iCompanyEvaluationLogService;

	@Autowired
	IRiskWorkService iRiskWorkService;

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	IRiskWorkMeasureService iRiskWorkMeasureService;

	@Autowired
	ITaskRiskWorkMeasureResultService iTaskRiskWorkMeasureResultService;

	@Autowired
	ITaskRiskControlTechService iTaskRiskControlTechService;

	/**
	 * 小程序服务
	 */
	@Autowired
	SmallProService smallProService;

	@Autowired
	AmosTrainingFeignClient examFeign;

	@Autowired
	MessageEventPublish messageEventPublish;

	@Value("${app.riskWork.list.size}")
	Integer riskWorkSize;

	/**
	 * 文件服务器地址
	 */
	@Value("${fileserver.domain}")
	String fileServerUrl;

	@Autowired
	ITaskTimedTaskService iTaskTimedTaskService;

	@Autowired
	IStatisticsService statisticsService;

	@Autowired
	PersonUtils personUtils;

	@Autowired
	KnowledgebaseFeignClient knowledgeBaseFeign;

	/**
	 * 3级安全考试,数据来源平台字典行业类型，约定写死
	 */
	private final String THREE_LEVEL_EXAM = "THREE_LEVEL_EXAM";

	@Override
	@Transactional
	public TaskRiskControlVo create(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());
		if (taskRiskControl.getTaskId() != null) {
			return taskRiskControlVo;
		}
		if (taskRiskControlVo.getCompanyId() != null) {
			taskRiskControl.setCompanyId(taskRiskControlVo.getCompanyId());
		}
		BeanUtils.copyProperties(taskRiskControl, taskRiskControlVo);
		Task task = new Task();
		task.setType(TaskTypeEnum.RISK.getValue());
		Person person = iPersonService.getById(taskRiskControlVo.getSecPersonId());
		task.setCreatePersonId(taskRiskControlVo.getCreatePersonId());
		task.setStatus(TaskStatusEnum.UNCOMPLETED.getLongType());

		Long projectId = taskRiskControlVo.getProjectId();
		task.setProjectId(projectId);
		Project project = iProjectService.getById(projectId);
		if (project == null) {
			throw new BaseException("所选项目不存在");
		}
		task.setOrgCode(project.getOrgCode());
		task.setProjectName(project.getName());
		task.setStatus(StatusEnum.UNFINISHED.getValue());
		task.setTaskNo(DateUtils.getTimeStamp());
		task.setName(taskRiskControl.getName());
		iTaskService.save(task);

		taskRiskControl.setStage(TaskRiskStageEnum.SELECT_WORKER.getValue());
		taskRiskControl.setTaskId(task.getId());
		this.saveOrUpdate(taskRiskControl);

		TaskPerson taskPerson = new TaskPerson();
		taskPerson.setPersonId(taskRiskControl.getSecPersonId());
		taskPerson.setPersonName(person.getName());
		taskPerson.setReadStatus(0L);
		taskPerson.setType(TaskPersonTypeEnum.CREATEPERSON.getValue());
		taskPerson.setTaskId(task.getId());
		iTaskPersonService.save(taskPerson);

		Person companyperson = iPersonService.getById(taskRiskControlVo.getCompanyPersonId());
		TaskPerson companyPerson = new TaskPerson();
		companyPerson.setPersonId(taskRiskControlVo.getCompanyPersonId());
		companyPerson.setPersonName(companyperson.getName());
		companyPerson.setReadStatus(0L);
		companyPerson.setType(TaskPersonTypeEnum.DIRECTOR.getValue());
		companyPerson.setTaskId(task.getId());
		iTaskPersonService.save(companyPerson);

		taskRiskControlVo.setTaskId(taskRiskControl.getTaskId());
		taskRiskControlVo.setStage(taskRiskControl.getStage());
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo nextStage(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());
		int stage = taskRiskControl.getStage();
		TaskRiskStageEnum nextEnum = TaskRiskStageEnum.next(taskRiskControl.getStage());
		int nextStage = nextEnum.getValue();
		taskRiskControlVo.setStage(nextStage);
		if (TaskRiskStageEnum.SELECT_WORKER.getValue() == stage) {
			List<Long> workIdList = new ArrayList<>();
			RiskWork riskWork = iRiskWorkService.getById(taskRiskControl.getRiskWorkId());
			List<TaskRiskControlPrePerson> prolist = new ArrayList<TaskRiskControlPrePerson>();
			if (taskRiskControlVo.getPreProPersonList() != null) {
				taskRiskControlVo.getPreProPersonList().stream().forEach(i -> {
					TaskRiskControlPrePerson taskRiskControlPrePerson = new TaskRiskControlPrePerson();
					i.setTaskId(taskRiskControl.getTaskId());
					i.setType(TaskPersonTypeEnum.PRO_WORKER.getValue());
					BeanUtils.copyProperties(i, taskRiskControlPrePerson);
					prolist.add(taskRiskControlPrePerson);
					workIdList.add(i.getPersonId());
				});
			}
			List<TaskRiskControlPrePerson> assistlist = new ArrayList<TaskRiskControlPrePerson>();
			if (taskRiskControlVo.getPreAssistPersonList() != null) {
				taskRiskControlVo.getPreAssistPersonList().stream().forEach(i -> {
					TaskRiskControlPrePerson taskRiskControlPrePerson = new TaskRiskControlPrePerson();
					i.setTaskId(taskRiskControl.getTaskId());
					i.setType(TaskPersonTypeEnum.ASSIST_WORKER.getValue());
					BeanUtils.copyProperties(i, taskRiskControlPrePerson);
					assistlist.add(taskRiskControlPrePerson);
					workIdList.add(i.getPersonId());
				});
			}
			// 校验重复
			Set<Long> workIdSet = new HashSet<>(workIdList);
			if (workIdSet.size() != workIdList.size()) {
				throw new BaseException("专业人员和辅助人员不能重复");
			}
			// 校验不能分包商负责人
			TaskPerson taskPerson = iTaskPersonService
					.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.DIRECTOR.getValue()));
			if (workIdSet.contains(taskPerson.getPersonId())) {
				throw new BaseException("专业人员和辅助人员不能是作业管理人");
			}
			iTaskRiskControlPrePersonService.remove(new LambdaQueryWrapper<TaskRiskControlPrePerson>()
					.eq(TaskRiskControlPrePerson::getTaskId, taskRiskControl.getTaskId()));
			iTaskRiskControlPrePersonService.saveBatch(prolist);
			iTaskRiskControlPrePersonService.saveBatch(assistlist);
			updateReadStatus(taskRiskControl.getTaskId(), TaskPersonTypeEnum.DIRECTOR.getValue(), 1L);
			// 项目安全负责人小红点赋值
			TaskPerson secPerson = iTaskPersonService
					.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.CREATEPERSON.getValue()));
			secPerson.setFirstRead(false);
			iTaskPersonService.updateById(secPerson);
			// 消息通知--给项目安全负责人发送
			taskRiskNotice(taskRiskControlVo, taskRiskControl.getSecPersonId());

			// 微信服务通知
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
					.in(Person::getId, Arrays.asList(taskRiskControl.getSecPersonId())).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(smallProService.getName());
			messages.add(taskRiskControl.getName());
			messages.add("请及时执行风险作业管控任务，保障项目安全管理");
			messages.add(DateUtils.getDateNowString());
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		} else if (TaskRiskStageEnum.SELECT_EXAM_KNOWLEDGE.getValue() == stage) {
			List<TaskPerson> taskPersonlist = new ArrayList<TaskPerson>();
			Long[] worktypes = { TaskPersonTypeEnum.PRO_WORKER.getValue(),
					TaskPersonTypeEnum.ASSIST_WORKER.getValue() };

			// 添加考试的人员
			List<TaskPerson> list = taskRiskControlVo.getExamPersonList();
			StringBuffer userIds = new StringBuffer();
			if (taskRiskControlVo.getIsExam() != null && taskRiskControlVo.getIsExam() && list != null) {
				// 查询上一次的模板id
				List<TaskPerson> oldExamPersonList = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
						.eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
						.in(TaskPerson::getType, Arrays.asList(worktypes)).isNotNull(TaskPerson::getExamTemplateId));
				List<Long> oldExamIds = oldExamPersonList.stream().map(TaskPerson::getPersonId)
						.collect(Collectors.toList());
				Long examTemplateId = oldExamPersonList != null && oldExamPersonList.size() > 0
						? (oldExamPersonList.get(0) != null ? oldExamPersonList.get(0).getExamTemplateId() : null)
						: null;
				String examName = oldExamPersonList != null && oldExamPersonList.size() > 0
						? (oldExamPersonList.get(0) != null ? oldExamPersonList.get(0).getExamName() : null)
						: null;
				Date expireDate = oldExamPersonList != null && oldExamPersonList.size() > 0
						? (oldExamPersonList.get(0) != null ? oldExamPersonList.get(0).getExpireDate() : null)
						: null;
				List<TaskPerson> examList = list.stream().filter(i -> !oldExamIds.contains(i.getPersonId()))
						.collect(Collectors.toList());
				examList.forEach(i -> {
					Person person = iPersonService.getById(i.getPersonId());
					userIds.append(person.getUserId() + ",");
					TaskPerson oldTaskPerson = iTaskPersonService
							.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getPersonId, person.getId())
									.eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
									.in(TaskPerson::getType, Arrays.asList(worktypes)));
					TaskPerson taskPerson = new TaskPerson();
					if (oldTaskPerson != null) {
						taskPerson = oldTaskPerson;
						taskPerson.setExpireDate(
								taskRiskControlVo.getExpireDate() != null ? taskRiskControlVo.getExpireDate()
										: expireDate);
						taskPerson.setExamName(taskRiskControlVo.getExamTemplateName() != null
								? taskRiskControlVo.getExamTemplateName()
								: examName);
						taskPerson.setExamTemplateId(
								taskRiskControlVo.getExamTemplateId() != null ? taskRiskControlVo.getExamTemplateId()
										: examTemplateId);
						taskPerson.setReadStatus(0L);
					} else {
						taskPerson.setPersonId(person.getId());
						taskPerson.setTaskId(taskRiskControl.getTaskId());
						taskPerson.setPersonName(person.getName());
						taskPerson.setFirstRead(false);
						taskPerson.setReadStatus(0L);
						taskPerson.setExpireDate(
								taskRiskControlVo.getExpireDate() != null ? taskRiskControlVo.getExpireDate()
										: expireDate);
						taskPerson.setExamName(taskRiskControlVo.getExamTemplateName() != null
								? taskRiskControlVo.getExamTemplateName()
								: examName);
						taskPerson.setExamTemplateId(
								taskRiskControlVo.getExamTemplateId() != null ? taskRiskControlVo.getExamTemplateId()
										: examTemplateId);
						TaskRiskControlPrePerson controlPrePerson = iTaskRiskControlPrePersonService
								.getOne(new LambdaQueryWrapper<TaskRiskControlPrePerson>()
										.eq(TaskRiskControlPrePerson::getPersonId, person.getId())
										.eq(TaskRiskControlPrePerson::getTaskId, taskRiskControl.getTaskId()));
						taskPerson.setType(controlPrePerson.getType());
					}
					taskPersonlist.add(taskPerson);
				});
				if (userIds.toString().length() > 0) {
					// 发送考试
					CreatExamDto creatExamDto = new CreatExamDto();
					creatExamDto.setBusinessKey(taskRiskControl.getTaskId().toString());
					creatExamDto
							.setId(taskRiskControlVo.getExamTemplateId() != null ? taskRiskControlVo.getExamTemplateId()
									: examTemplateId);
					creatExamDto.setIsAgain(1);
					creatExamDto.setUserIds(userIds.toString().substring(0, userIds.toString().length() - 1));
					creatExamDto.setIsMiniApp(false);
					creatExamDto.setEndTime(taskRiskControlVo.getExpireDate() != null ? taskRiskControlVo.getExpireDate()
							: expireDate);
					ResponseModel<Long> response = examFeign.doTemplateExam(creatExamDto);
					// 获取考试id
					Long examId = response.getResult();
					if (examId == null) {
						throw new BaseException("获取考试id失败");
					}
					taskPersonlist.forEach(i -> {
						i.setExamId(examId);
					});
				}
			}

			if (taskRiskControlVo.getIsKnowledge() != null && taskRiskControlVo.getIsKnowledge()) {// 添加知识的人员 所有人发知识
				List<TaskPerson> list2 = taskRiskControlVo.getKnowledgePersonList();
				List<TaskPerson> oldKnowPersonList = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
						.eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
						.in(TaskPerson::getType, Arrays.asList(worktypes)).isNotNull(TaskPerson::getKnowledgeId));
				List<Long> oldKnowIds = oldKnowPersonList.stream().map(TaskPerson::getPersonId)
						.collect(Collectors.toList());
				List<TaskPerson> knowlist = list2.stream().filter(i -> !oldKnowIds.contains(i.getPersonId()))
						.collect(Collectors.toList());
				for (TaskPerson i : knowlist) {
					TaskPerson ltaskPerson = getTaskPersonByPersonId(taskPersonlist, i.getPersonId());
					Long knowledgeId = oldKnowPersonList != null && oldKnowPersonList.size() > 0
							? (oldKnowPersonList.get(0) != null ? oldKnowPersonList.get(0).getKnowledgeId() : null)
							: null;
					Long knowledgeCategoryId = oldKnowPersonList != null && oldKnowPersonList.size() > 0
							? (oldKnowPersonList.get(0) != null ? oldKnowPersonList.get(0).getKnowledgeCategoryId()
									: null)
							: null;
					String knowledgeName = oldKnowPersonList != null && oldKnowPersonList.size() > 0
							? (oldKnowPersonList.get(0) != null ? oldKnowPersonList.get(0).getKnowledgeName() : null)
							: null;
					// 如果之前添加过这个人 只更新知识id
					if (ltaskPerson != null) {
						ltaskPerson.setKnowledgeId(taskRiskControlVo.getKnowledgeDocumentId() != null
								? taskRiskControlVo.getKnowledgeDocumentId()
								: knowledgeId);
						ltaskPerson.setKnowledgeName(taskRiskControlVo.getKnowledgeDocumentName() != null
								? taskRiskControlVo.getKnowledgeDocumentName()
								: knowledgeName);
						ltaskPerson.setKnowledgeCategoryId(taskRiskControlVo.getKnowledgeCategoryId() != null
								? taskRiskControlVo.getKnowledgeCategoryId()
								: knowledgeCategoryId);
						ltaskPerson.setReadStatus(0L);
					} else {
						Person person = iPersonService.getById(i.getPersonId());
						TaskPerson oldTaskPerson = iTaskPersonService
								.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getPersonId, person.getId())
										.eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
										.in(TaskPerson::getType, Arrays.asList(worktypes)));
						TaskPerson taskPerson = new TaskPerson();
						if (oldTaskPerson != null) {
							taskPerson = oldTaskPerson;
							taskPerson.setKnowledgeId(taskRiskControlVo.getKnowledgeDocumentId() != null
									? taskRiskControlVo.getKnowledgeDocumentId()
									: knowledgeId);
							taskPerson.setKnowledgeName(taskRiskControlVo.getKnowledgeDocumentName() != null
									? taskRiskControlVo.getKnowledgeDocumentName()
									: knowledgeName);
							taskPerson.setKnowledgeCategoryId(taskRiskControlVo.getKnowledgeCategoryId() != null
									? taskRiskControlVo.getKnowledgeCategoryId()
									: knowledgeCategoryId);
							taskPerson.setReadStatus(0L);
						} else {
							taskPerson.setPersonId(person.getId());
							taskPerson.setTaskId(taskRiskControl.getTaskId());
							taskPerson.setPersonName(person.getName());
							taskPerson.setKnowledgeId(taskRiskControlVo.getKnowledgeDocumentId() != null
									? taskRiskControlVo.getKnowledgeDocumentId()
									: knowledgeId);
							taskPerson.setKnowledgeName(taskRiskControlVo.getKnowledgeDocumentName() != null
									? taskRiskControlVo.getKnowledgeDocumentName()
									: knowledgeName);
							taskPerson.setKnowledgeCategoryId(taskRiskControlVo.getKnowledgeCategoryId() != null
									? taskRiskControlVo.getKnowledgeCategoryId()
									: knowledgeCategoryId);
							taskPerson.setFirstRead(false);
							taskPerson.setReadStatus(0L);
							taskPerson.setExpireDate(taskRiskControlVo.getExpireDate());
							TaskRiskControlPrePerson controlPrePerson = iTaskRiskControlPrePersonService
									.getOne(new LambdaQueryWrapper<TaskRiskControlPrePerson>()
											.eq(TaskRiskControlPrePerson::getPersonId, person.getId())
											.eq(TaskRiskControlPrePerson::getTaskId, taskRiskControl.getTaskId()));
							taskPerson.setType(controlPrePerson.getType());
						}

						taskPersonlist.add(taskPerson);
					}
				}
			}
			// 添加剩余的人
			List<TaskPerson> oldTaskPersonList = iTaskPersonService
					.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.in(TaskPerson::getType, Arrays.asList(worktypes)));
			List<Long> oldIds = oldTaskPersonList.stream().map(TaskPerson::getPersonId).collect(Collectors.toList());
			List<Long> taskPeopleIds = Lists.transform(taskPersonlist, TaskPerson::getPersonId);
			LambdaQueryWrapper<TaskRiskControlPrePerson> wrapper = new LambdaQueryWrapper<TaskRiskControlPrePerson>()
					.eq(TaskRiskControlPrePerson::getTaskId, taskRiskControl.getTaskId())
					.in(TaskRiskControlPrePerson::getType, Arrays.asList(worktypes));
			if (taskPeopleIds != null && !taskPeopleIds.isEmpty()) {
				wrapper.notIn(TaskRiskControlPrePerson::getPersonId, taskPeopleIds);
			}
			if (oldIds != null && !oldIds.isEmpty()) {
				wrapper.notIn(TaskRiskControlPrePerson::getPersonId, oldIds);
			}
			List<TaskRiskControlPrePerson> remainlist = iTaskRiskControlPrePersonService.list(wrapper);
			for (TaskRiskControlPrePerson taskRiskControlPrePerson : remainlist) {
				Person person = iPersonService.getById(taskRiskControlPrePerson.getPersonId());
				TaskPerson taskPerson = new TaskPerson();
				taskPerson.setPersonId(person.getId());
				taskPerson.setTaskId(taskRiskControl.getTaskId());
				taskPerson.setPersonName(person.getName());
				taskPerson.setFirstRead(false);
				taskPerson.setReadStatus(1L);
				taskPerson.setType(taskRiskControlPrePerson.getType());
				taskPersonlist.add(taskPerson);
			}
			taskRiskControl.setIsExam(taskRiskControlVo.getIsExam());
			taskRiskControl.setIsKnowledge(taskRiskControlVo.getIsKnowledge());

			if (!StringUtil.isEmpty(taskPersonlist)) {
				iTaskPersonService.saveOrUpdateBatch(taskPersonlist);
			}

			// 更新人为已经使用
			TaskRiskControlPrePerson taskRiskControlPrePerson = new TaskRiskControlPrePerson();
			taskRiskControlPrePerson.setUsed(true);
			iTaskRiskControlPrePersonService.update(taskRiskControlPrePerson,
					new LambdaQueryWrapper<TaskRiskControlPrePerson>().eq(TaskRiskControlPrePerson::getTaskId,
							taskRiskControl.getTaskId()));

			// 创建定时任务-到期提醒
			if (taskRiskControlVo.getExpireDate() != null) {
				RiskTimerTask riskTimerTask = new RiskTimerTask(taskRiskControl.getTaskId());
				new Timer().schedule(riskTimerTask, taskRiskControlVo.getExpireDate());
				// 保存定时任务启动时用
				TaskTimedTask timedTask = new TaskTimedTask();
				timedTask.setExecuteTime(taskRiskControlVo.getExpireDate());
				timedTask.setTaskId(taskRiskControl.getTaskId());
				timedTask.setType(TaskTimedTaskTypeEnum.RISK_EXAM_KNOWLEDGE.getType());
				timedTask.setExecuted(false);
				iTaskTimedTaskService.save(timedTask);
			}

			// 消息通知--给专业和辅助人员发送
			List<Long> personIdList = Lists.transform(taskPersonlist, TaskPerson::getPersonId);
			taskRiskNotice(taskRiskControlVo, personIdList);

			if (!StringUtil.isEmpty(personIdList)) {
				// 微信服务通知
				List<Person> persons = iPersonService.list(
						new LambdaQueryWrapper<Person>().in(Person::getId, personIdList).isNotNull(Person::getOpenId));
				List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
				List<String> messages = new ArrayList<>();
				messages.add(smallProService.getName());
				messages.add(taskRiskControl.getName());
				messages.add("请及时执行风险作业管控任务，保障项目安全管理");
				messages.add(DateUtils.getDateNowString());
				smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
			}
		} else if (TaskRiskStageEnum.DO_EXAM_AND_CHOOSE_SEC.getValue() == stage) {
			// 如果是再次发起不重新生成安全员技术员以及检查项
			int techCount = iTaskPersonService
					.count(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.TECHNICIAN.getValue()));

			if (techCount == 0) {
				List<TaskPerson> taskPersonlist = new ArrayList<TaskPerson>();
				// 生成技术员
				if (!StringUtil.isEmpty(taskRiskControlVo.getTechPersonList())) {
					TaskPerson techPerson = taskRiskControlVo.getTechPersonList().get(0);
					TaskPerson taskPerson = new TaskPerson();
					taskPerson.setPersonId(techPerson.getPersonId());
					taskPerson.setTaskId(taskRiskControl.getTaskId());
					taskPerson.setPersonName(techPerson.getPersonName());
					taskPerson.setFirstRead(false);
					taskPerson.setReadStatus(0L);
					taskPerson.setType(TaskPersonTypeEnum.TECHNICIAN.getValue());
					taskPersonlist.add(taskPerson);
				}
				// 生成安全员
				if (!StringUtil.isEmpty(taskRiskControlVo.getSecPersonList())) {
					TaskPerson secPerson = taskRiskControlVo.getSecPersonList().get(0);
					// 校验安全员是否是发起人
//					if (taskRiskControl.getSecPersonId().equals(secPerson.getPersonId())) {
//						throw new BaseException("安全员和安全负责人不能重复");
//					}
					TaskPerson taskPerson = new TaskPerson();
					taskPerson.setPersonId(secPerson.getPersonId());
					taskPerson.setTaskId(taskRiskControl.getTaskId());
					taskPerson.setPersonName(secPerson.getPersonName());
					taskPerson.setFirstRead(false);
					taskPerson.setReadStatus(0L);
					taskPerson.setType(TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue());
					taskPersonlist.add(taskPerson);

					// 生成检查措施
					List<RiskWorkMeasure> measureList = iRiskWorkMeasureService
							.list(new LambdaQueryWrapper<RiskWorkMeasure>().eq(RiskWorkMeasure::getRiskWorkId,
									taskRiskControl.getRiskWorkId()));
					List<TaskRiskWorkMeasureResult> resultList = new ArrayList<TaskRiskWorkMeasureResult>();
					measureList.forEach(i -> {
						TaskRiskWorkMeasureResult measureResult = new TaskRiskWorkMeasureResult();
						BeanUtils.copyProperties(i, measureResult);
						measureResult.setTaskRiskControlId(taskRiskControl.getId());
						measureResult.setRiskWorkId(taskRiskControl.getRiskWorkId());
						measureResult.setIsOk(StatusEnum.SUCCESS.getValue());
						measureResult.setId(null);
						resultList.add(measureResult);
					});
					iTaskRiskWorkMeasureResultService.saveBatch(resultList);

					// 生成检查项
					List<RiskWorkHazadousWork> riskWorkList = iRiskWorkHazadousWorkService
							.list(new LambdaQueryWrapper<RiskWorkHazadousWork>().eq(RiskWorkHazadousWork::getRiskWorkId,
									taskRiskControl.getRiskWorkId()));
					for (RiskWorkHazadousWork riskWorkHazadousWork : riskWorkList) {
						HazardousWorkVo hazardousWorkVo = iHazardousWorkService
								.getHazardousWorkVo(riskWorkHazadousWork.getHarzadousWorkId());
						List<InputItemDto> inputItemDtos = hazardousWorkVo.getInputItemDtos();
						inputItemDtos.forEach(i -> {
							HazardousWorkResult hazardousWorkResult = new HazardousWorkResult();
							hazardousWorkResult.setTaskId(taskRiskControl.getTaskId());
							// 危险作业的id实际是以前的风险作业id name就是前台传递的名字
							hazardousWorkResult.setHazardousWorkId(riskWorkHazadousWork.getHarzadousWorkId());
							hazardousWorkResult.setHazardousWorkName(riskWorkHazadousWork.getHarzadousWorkName());
							hazardousWorkResult.setInputItemId(i.getId());
							hazardousWorkResult.setInputItemName(i.getName());
							hazardousWorkResult.setValue("");
							hazardousWorkResult.setIsOk(StatusEnum.SUCCESS.getValue());
							hazardousWorkResult.setReason("");
							hazardousWorkResult.setScore(0L);
							hazardousWorkResult.setCpersonId(taskRiskControlVo.getSecPersonList().get(0).getId());
							hazardousWorkResult.setWeight(1L);
							iHazardousWorkResultService.save(hazardousWorkResult);
						});
					}
				}
				iTaskPersonService.saveBatch(taskPersonlist);
				Long[] types = { TaskPersonTypeEnum.PRO_WORKER.getValue(),
						TaskPersonTypeEnum.ASSIST_WORKER.getValue() };
				// 修改考试人员阅读状态
//				List<TaskPerson> workList = iTaskPersonService.list(
//						new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
//								.in(TaskPerson::getType, Arrays.asList(types)));
//				workList.forEach(i -> {
//					i.setReadStatus(0L);
//				});
//				if (StringUtil.isNotEmpty(workList)) {
//					iTaskPersonService.updateBatchById(workList);
//				}

				// 消息通知--给安全员和技术员发送
				List<Long> personIdList = Lists.transform(taskPersonlist, TaskPerson::getPersonId);
				taskRiskNotice(taskRiskControlVo, personIdList);

				// 微信服务通知
				List<Person> persons = iPersonService.list(
						new LambdaQueryWrapper<Person>().in(Person::getId, personIdList).isNotNull(Person::getOpenId));
				List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
				List<String> messages = new ArrayList<>();
				messages.add(smallProService.getName());
				messages.add(taskRiskControl.getName());
				messages.add("请及时执行风险作业管控任务，保障项目安全管理");
				messages.add(DateUtils.getDateNowString());
				smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
			}

			Long[] types = { TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue(),
					TaskPersonTypeEnum.TECHNICIAN.getValue() };
			// 如果技术员和安全员都确认完则直接走到评价
			int count = iTaskPersonService
					.count(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.eq(TaskPerson::getReadStatus, 1L).in(TaskPerson::getType, Arrays.asList(types)));
			if (count == 2) {
				taskRiskControl.setStage(nextStage);
				this.saveOrUpdate(taskRiskControl);
				this.nextStage(taskRiskControlVo);
				// 消息通知--给项目安全员发送
				taskRiskNotice(taskRiskControlVo, taskRiskControl.getSecPersonId());
				return taskRiskControlVo;
			}
		} else if (TaskRiskStageEnum.PHOTO.getValue() == stage) {
//			// 新增人员评价数据
//			Long[] worktypes = { TaskPersonTypeEnum.PRO_WORKER.getValue(),
//					TaskPersonTypeEnum.ASSIST_WORKER.getValue() };
//			List<TaskPerson> personList = iTaskPersonService
//					.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
//							.eq(TaskPerson::getType, Arrays.asList(worktypes)));
//			List<UserEvaluationLog> userEvaList = new ArrayList<>();
//			for (TaskPerson taskPerson : personList) {
//				UserEvaluationLog userEvaluationLog =new UserEvaluationLog();
//				userEvaluationLog.setPersonId(taskPerson.getPersonId());
//				userEvaluationLog.setTaskId(taskRiskControl.getTaskId());
//				userEvaList.add(userEvaluationLog);
//			}
//			// 新增分包商评价数据
//			List<CompanyEvaluationLog> companyEvaList = new ArrayList<>();
//			CompanyEvaluationLog companyEvaluationLog =new CompanyEvaluationLog();
//			companyEvaluationLog.setCompanyId(taskRiskControl.getCompanyId());
//			companyEvaluationLog.setTaskId(taskRiskControl.getTaskId());
//			companyEvaList.add(companyEvaluationLog);
//			iCompanyEvaluationLogService.saveBatch(companyEvaList);
		} else if (TaskRiskStageEnum.EVALUATE.getValue() == stage) {
			// 新增人员评价数据
			List<UserEvaluationLogVo> userEvaVoList = taskRiskControlVo.getUserEvaList();
			List<UserEvaluationLog> userEvaList = new ArrayList<UserEvaluationLog>();
			userEvaVoList.forEach(i -> {
				UserEvaluationLog userEvaluationLog = new UserEvaluationLog();
				i.setTaskId(taskRiskControl.getTaskId());
				BeanUtils.copyProperties(i, userEvaluationLog);
				userEvaList.add(userEvaluationLog);
			});
			iUserEvaluationLogService.saveBatch(userEvaList);
			// 更新人员综合评分
			DecimalFormat df = new DecimalFormat("0.0");// 设置保留位数
			if (!StringUtil.isEmpty(userEvaList)) {
				for (UserEvaluationLog userEvaluationLog : userEvaList) {
					List<UserEvaluationLog> personList = iUserEvaluationLogService
							.list(new LambdaQueryWrapper<UserEvaluationLog>()
									.eq(UserEvaluationLog::getPersonId, userEvaluationLog.getPersonId())
									.ne(UserEvaluationLog::getRate, 0));
					int personTotal = personList.stream().mapToInt(UserEvaluationLog::getRate).sum();
					float personAverage = Float.parseFloat(df.format((float) personTotal / personList.size()));
					Person person = new Person();
					person.setId(userEvaluationLog.getPersonId());
					person.setCompositeScore(personAverage);
					iPersonService.updateById(person);
				}
			}
			// 新增分包商评价数据
			List<CompanyEvaluationLogVo> companyEvaVoList = taskRiskControlVo.getCompanyEvaList();
			List<CompanyEvaluationLog> companyEvaList = new ArrayList<CompanyEvaluationLog>();
			companyEvaVoList.forEach(i -> {
				CompanyEvaluationLog companyEvaluationLog = new CompanyEvaluationLog();
				i.setTaskId(taskRiskControl.getTaskId());
				BeanUtils.copyProperties(i, companyEvaluationLog);
				companyEvaList.add(companyEvaluationLog);
			});
			iCompanyEvaluationLogService.saveBatch(companyEvaList);
			// 更新分包商综合评分
			if (!StringUtil.isEmpty(companyEvaList)) {
				List<CompanyEvaluationLog> companyList = iCompanyEvaluationLogService
						.list(new LambdaQueryWrapper<CompanyEvaluationLog>()
								.eq(CompanyEvaluationLog::getCompanyId, companyEvaVoList.get(0).getCompanyId())
								.ne(CompanyEvaluationLog::getRate, 0));
				int companyTotal = companyList.stream().mapToInt(CompanyEvaluationLog::getRate).sum();
				float companyAverage = Float.parseFloat(df.format((float) companyTotal / companyList.size()));
				Company company = new Company();
				company.setId(companyEvaVoList.get(0).getCompanyId());
				company.setCompositeScore(companyAverage);
				iCompanyService.updateById(company);
			}
			updateReadStatus(taskRiskControl.getTaskId(), TaskPersonTypeEnum.CREATEPERSON.getValue(), 1L);
			Task task = iTaskService.getById(taskRiskControl.getTaskId());
			Date date = new Date();
			task.setEndTime(date);
			task.setStatus(TaskStatusEnum.COMPLETED.getLongType());
			iTaskService.updateById(task);
			taskRiskControl.setTaskEndTime(date);

			// 微信服务通知
			Set<Long> set = personUtils.getDefaultPerson(taskRiskControl.getProjectId());
			Project project = iProjectService.getById(taskRiskControl.getProjectId());
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
					.in(Person::getId, Arrays.asList(set)).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(project.getName());
			messages.add(taskRiskControl.getName());
			messages.add("风险作业");
			messages.add(DateUtils.getDateNowString());
			messages.add("风险作业完成消息通知");
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.SERVICE_COMPLETE.getValue(),
					messages);

		}
//		else if (TaskRiskStageEnum.COMPLETED.getValue() == stage) {
//			updateReadStatus(taskRiskControl.getTaskId(), TaskPersonTypeEnum.CREATEPERSON.getValue(), 1L);
//			Task task = iTaskService.getById(taskRiskControl.getTaskId());
//			Date date = new Date();
//			task.setEndTime(date);
//			task.setStatus(TaskStatusEnum.COMPLETED.getLongType());
//			iTaskService.updateById(task);
//			taskRiskControl.setTaskEndTime(date);
//		}
		taskRiskControl.setStage(nextStage);
		this.saveOrUpdate(taskRiskControl);
		return taskRiskControlVo;
	}

	private void updateReadStatus(Long taskId, Long type, Long status) {
		TaskPerson taskPerson = new TaskPerson();
		taskPerson.setReadStatus(status);
		iTaskPersonService.update(taskPerson,
				new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getType, type));
	}

	private TaskPerson getTaskPersonByPersonId(List<TaskPerson> taskPersonlist, Long personId) {
		for (TaskPerson taskPerson : taskPersonlist) {
			if (personId.longValue() == taskPerson.getPersonId().longValue()) {
				return taskPerson;
			}
		}
		return null;
	}

	@Override
	@Transactional
	public TaskRiskControlVo previousStage(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());
		TaskRiskStageEnum nextEnum = TaskRiskStageEnum.previous(taskRiskControl.getStage());
		int stage = nextEnum.getValue();
		taskRiskControl.setStage(stage);
		this.saveOrUpdate(taskRiskControl);
		if (stage == TaskRiskStageEnum.SELECT_WORKER.getValue()) {
			updateReadStatus(taskRiskControl.getTaskId(), TaskPersonTypeEnum.DIRECTOR.getValue(), 0L);

			TaskPerson taskPerson = iTaskPersonService
					.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.DIRECTOR.getValue()));
			// 微信服务通知
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
					.in(Person::getId, Arrays.asList(taskPerson.getPersonId())).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(smallProService.getName());
			messages.add(taskRiskControl.getName());
			messages.add("请及时执行风险作业管控任务，保障项目安全管理");
			messages.add(DateUtils.getDateNowString());
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		}
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo doKnowledge(TaskRiskControlVo taskRiskControlVo) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskRiskControlVo.getTaskPersonId());
		taskPerson.setKnowledgeStatus(1);
//		if (taskPerson.getExamId() == null) {
//			taskPerson.setReadStatus(1L);
//		} else if (taskPerson.getExamId() != null && taskPerson.getExamStatus() != 1L) {
//			taskPerson.setReadStatus(1L);
//		}
		iTaskPersonService.updateById(taskPerson);
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo doExam(TaskRiskControlVo taskRiskControlVo, Boolean qualified) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskRiskControlVo.getTaskPersonId());
		taskPerson.setExamStatus(qualified ? 1 : 0);
//		if (taskPerson.getKnowledgeId() == null) {
//			taskPerson.setReadStatus(1L);
//		} else if (taskPerson.getKnowledgeId() != null && taskPerson.getKnowledgeStatus() != 1L) {
//			taskPerson.setReadStatus(1L);
//		}
		iTaskPersonService.updateById(taskPerson);
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo doCheck(TaskRiskControlVo taskRiskControlVo) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskRiskControlVo.getTaskPersonId());
		// 保存照片
		List<TaskPersonAndImageInfo> imageList = taskRiskControlVo.getNewImageList();
		if (StringUtil.isNotEmpty(imageList)) {
			for (TaskPersonAndImageInfo info : imageList) {
				List<TaskFileVo> files = info.getFilePath();
				List<TaskPersonFile> taskPersonFileList = new ArrayList<>();
				for (TaskFileVo TaskFileVo : files) {
					TaskPersonFile taskPersonFile = new TaskPersonFile();
					taskPersonFile.setTaskId(taskPerson.getTaskId());
					taskPersonFile.setPersonId(taskPerson.getPersonId());
					taskPersonFile.setPersonType(TaskPersonFileEnum.IMAGE.getValue());
					taskPersonFile.setFilePath(TaskFileVo.getFilePath());
					taskPersonFileList.add(taskPersonFile);
				}
				iTaskPersonFileService.saveBatch(taskPersonFileList);
			}
		}
		// 保存检查措施
		List<TaskRiskWorkMeasureResult> measureList = taskRiskControlVo.getMeasureResultList();
		if (StringUtil.isNotEmpty(measureList)) {
			iTaskRiskWorkMeasureResultService.updateBatchById(measureList);
		}

		// 保存检查项
		List<HazardousWorkVo> hazardousWorkList = taskRiskControlVo.getHazardWorkList();
		if (StringUtil.isNotEmpty(hazardousWorkList)) {
			for (HazardousWorkVo hazardousWorkVo : hazardousWorkList) {
				List<HazardousWorkResult> hazardousWorkResultList = hazardousWorkVo.getHazardousWorkResultList();
				if (StringUtil.isNotEmpty(hazardousWorkResultList)) {
					hazardousWorkResultList.forEach(hazardousWorkResult -> {
						iHazardousWorkResultService.updateById(hazardousWorkResult);
					});
				}
			}
		}

		// 修改阅读状态
		taskPerson.setReadStatus(1L);
		iTaskPersonService.updateById(taskPerson);

		Long[] types = { TaskPersonTypeEnum.TECHNICIAN.getValue(),
				TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue() };

		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());

		// 如果技术员和安全员都确认完则走到下一步
		int count = iTaskPersonService
				.count(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskPerson.getTaskId())
						.eq(TaskPerson::getReadStatus, 0L).in(TaskPerson::getType, Arrays.asList(types)));
		if (count == 0 && taskRiskControl != null && taskRiskControl.getStage() == TaskRiskStageEnum.PHOTO.getValue()) {
			this.nextStage(taskRiskControlVo);
			// 消息通知--给项目安全员发送
			taskRiskNotice(taskRiskControlVo, taskRiskControl.getSecPersonId());

			// 微信服务通知
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
					.in(Person::getId, Arrays.asList(taskRiskControl.getSecPersonId())).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(smallProService.getName());
			messages.add(taskRiskControl.getName());
			messages.add("请及时执行风险作业管控任务，保障项目安全管理");
			messages.add(DateUtils.getDateNowString());
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		}
		return taskRiskControlVo;
	}

	@Override
	public IPage<TaskRiskControlVo> listByPage(Integer pageNum, Integer pageSize,
			TaskRiskControlDto taskRiskControlDto) {
		if (null == pageNum || null == pageSize) {
			pageNum = 1;
			pageSize = Integer.MAX_VALUE;
		}
		Page<TaskRiskControlVo> pageable = new Page<>();
		pageable.setCurrent(pageNum);
		pageable.setSize(pageSize);
		if (taskRiskControlDto.getStatusCode() != null) {
			TaskRiskControlStatusEnum statusEnum = TaskRiskControlStatusEnum
					.getEnumByCode(taskRiskControlDto.getStatusCode());
			if (null != statusEnum) {
				taskRiskControlDto.setStageList(Arrays.asList(statusEnum.getStage().split(",")));
			}
		}
		return this.baseMapper.listByPage(pageable, taskRiskControlDto);
	}

	@Override
	public TaskRiskControlVo getDetailById(Long id) {
		TaskRiskControlVo taskRiskControlVo = this.baseMapper.getDetailById(id);
		TaskRiskControlTech taskRiskControlTech = iTaskRiskControlTechService.getOne(
				new LambdaQueryWrapper<TaskRiskControlTech>().eq(TaskRiskControlTech::getTaskRiskControlId, id));
		TaskRiskControlTechVo taskRiskControlTechVo = new TaskRiskControlTechVo();
		if (taskRiskControlTech != null) {
			BeanUtils.copyProperties(taskRiskControlTech, taskRiskControlTechVo);
		}else 
		{
			taskRiskControlTechVo.setTechPersonId(taskRiskControlVo.getTechPersonId());
			taskRiskControlTechVo.setConstructDocumentId(taskRiskControlVo.getConstructDocumentId());
		}
		Person techPerson = iPersonService.getById(taskRiskControlTechVo.getTechPersonId());
		taskRiskControlTechVo.setTechPersonName(techPerson != null ? techPerson.getName() : null);
		if(taskRiskControlTechVo.getConstructDocumentId()!=null) 
		{
			ResponseModel<List<Map<String, Object>>> reponse = knowledgeBaseFeign
					.getDocById(taskRiskControlTechVo.getConstructDocumentId());
			if (reponse.getStatus() == 200 && reponse.getResult() != null && reponse.getResult().size() > 0
					&& reponse.getResult().get(0) != null) {
				String name = (String) reponse.getResult().get(0).get("docTitle");
				taskRiskControlTechVo.setConstructDocumentName(name);
			}
		}
		taskRiskControlVo.setRiskControlTechVo(taskRiskControlTechVo);
		return taskRiskControlVo;
	}

	@Override
	public TaskRiskControlVo taskDetail(Long id, Long taskPersonId) {
		TaskRiskControlVo taskRiskControlVo = new TaskRiskControlVo();
		TaskRiskControl taskRiskControl = this
				.getOne(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getId, id));
		BeanUtils.copyProperties(taskRiskControl, taskRiskControlVo);
		// 是否发起任务
		taskRiskControlVo.setIsStart(this.baseMapper.isStart(id));
		// 项目名称
		Project project = iProjectService.getById(taskRiskControl.getProjectId());
		taskRiskControlVo.setProjectName(project.getName());
		// 安全负责人名称
		Person secPerson = iPersonService.getById(taskRiskControl.getSecPersonId());
		taskRiskControlVo.setSecPersonName(secPerson.getName());
		// 风险作业
		RiskWorkParam riskWork = iRiskWorkService.getWithChildById(taskRiskControl.getRiskWorkId());
		taskRiskControlVo.setRiskWork(riskWork);
		// 公司
		Company company = iCompanyService.getById(taskRiskControl.getCompanyId());
		taskRiskControlVo.setCompanyName(company != null ? company.getName() : null);
		// 危险作业名称
		Long taskId = taskRiskControl.getTaskId();
		if (!StringUtil.isNotEmpty(taskId)) {
			return taskRiskControlVo;
		}
		// 实际开始结束时间
		Task task = iTaskService.getById(taskId);
		taskRiskControlVo.setTaskStartTime(task.getCreateDate());
		taskRiskControlVo.setTaskEndTime(task.getEndTime());
		// 添加分包商负责人
		List<TaskPerson> companyPersonList = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getType, TaskPersonTypeEnum.DIRECTOR.getValue()));
		if (!StringUtil.isEmpty(companyPersonList)) {
			taskRiskControlVo.setCompanyPersonId(companyPersonList.get(0).getPersonId());
			taskRiskControlVo.setCompanyPersonName(companyPersonList.get(0).getPersonName());
		}
		// 添加专业施工人员
		TaskRiskControlPrePerson pro = new TaskRiskControlPrePerson();
		pro.setTaskId(taskId);
		pro.setType(TaskPersonTypeEnum.PRO_WORKER.getValue());
		List<TaskRiskControlPrePersonVo> preProPersonList = iTaskRiskControlPrePersonService.listVo(pro);
		taskRiskControlVo.setPreProPersonList(preProPersonList);
		// 添加辅助施工人员
		TaskRiskControlPrePerson assist = new TaskRiskControlPrePerson();
		assist.setTaskId(taskId);
		assist.setType(TaskPersonTypeEnum.ASSIST_WORKER.getValue());
		List<TaskRiskControlPrePersonVo> preAssistPersonList = iTaskRiskControlPrePersonService.listVo(assist);
		taskRiskControlVo.setPreAssistPersonList(preAssistPersonList);
		Long[] worktypes = { TaskPersonTypeEnum.PRO_WORKER.getValue(), TaskPersonTypeEnum.ASSIST_WORKER.getValue() };
		// 添加考试人员列表
		List<TaskPerson> examPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskId)
						.in(TaskPerson::getType, Arrays.asList(worktypes)).isNotNull(TaskPerson::getExamId));
		taskRiskControlVo.setExamPersonList(examPersonList);
		// 考试名称
		if (!StringUtil.isEmpty(examPersonList)) {
			taskRiskControlVo.setExamId(examPersonList.get(0).getExamId());
			taskRiskControlVo.setExamTemplateName(examPersonList.get(0).getExamName());
			taskRiskControlVo.setExamTemplateId(examPersonList.get(0).getExamTemplateId());
			// 添加考试截止时间
			taskRiskControlVo.setExpireDate(examPersonList.get(examPersonList.size() - 1).getExpireDate());
		}
		// 添加知识人员列表
		List<TaskPerson> knowledgePersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskId)
						.in(TaskPerson::getType, Arrays.asList(worktypes)).isNotNull(TaskPerson::getKnowledgeId));
		taskRiskControlVo.setKnowledgePersonList(knowledgePersonList);
		// 知识名称
		if (!StringUtil.isEmpty(knowledgePersonList)) {
			taskRiskControlVo.setKnowledgeDocumentId(knowledgePersonList.get(0).getKnowledgeId());
			taskRiskControlVo.setKnowledgeDocumentName(knowledgePersonList.get(0).getKnowledgeName());
		}
		// 添加检查措施
		List<TaskRiskWorkMeasureResult> measureResultList = iTaskRiskWorkMeasureResultService
				.list(new LambdaQueryWrapper<TaskRiskWorkMeasureResult>()
						.eq(TaskRiskWorkMeasureResult::getRiskWorkId, taskRiskControl.getRiskWorkId())
						.eq(TaskRiskWorkMeasureResult::getTaskRiskControlId, id));
		taskRiskControlVo.setMeasureResultList(measureResultList);
		// 添加检查项
		List<RiskWorkHazadousWork> riskWorkList = iRiskWorkHazadousWorkService
				.list(new LambdaQueryWrapper<RiskWorkHazadousWork>().eq(RiskWorkHazadousWork::getRiskWorkId,
						taskRiskControl.getRiskWorkId()));
		List<HazardousWorkVo> hazardousWorkList = new ArrayList<>();
		for (RiskWorkHazadousWork riskWorkHazadousWork : riskWorkList) {
			HazardousWorkVo hazardousWorkVo = new HazardousWorkVo();
			HazardousWork HazardousWork = iHazardousWorkService.getById(riskWorkHazadousWork.getHarzadousWorkId());
			List<HazardousWorkResult> hazardousWorkResultList = iHazardousWorkResultService
					.list(new LambdaQueryWrapper<HazardousWorkResult>()
							.eq(HazardousWorkResult::getHazardousWorkId, riskWorkHazadousWork.getHarzadousWorkId())
							.eq(HazardousWorkResult::getTaskId, taskId));
			if (HazardousWork != null) {
				BeanUtils.copyProperties(HazardousWork, hazardousWorkVo);
			}
			hazardousWorkVo.setHazardousWorkResultList(hazardousWorkResultList);
			hazardousWorkList.add(hazardousWorkVo);
		}
		taskRiskControlVo.setHazardWorkList(hazardousWorkList);
		// 添加安全员
		List<TaskPerson> secPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskId).in(TaskPerson::getType,
						Arrays.asList(TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue())));
		taskRiskControlVo.setSecPersonList(secPersonList);
		// 添加技术员
		List<TaskPerson> techPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskId).in(TaskPerson::getType,
						Arrays.asList(TaskPersonTypeEnum.TECHNICIAN.getValue())));
		taskRiskControlVo.setTechPersonList(techPersonList);
		// 添加安全员照片
		List<TaskPersonAndImageInfo> imageList = new ArrayList<>();
		if (StringUtil.isNotEmpty(secPersonList)) {
			for (TaskPerson secTaskPerson : secPersonList) {
				TaskPersonAndImageInfo taskPersonAndImageInfo = new TaskPersonAndImageInfo();
				taskPersonAndImageInfo.setTaskId(taskId);
				taskPersonAndImageInfo.setPersonId(secTaskPerson.getPersonId());
				taskPersonAndImageInfo.setPersonName(secTaskPerson.getPersonName());
				taskPersonAndImageInfo.setTaskPersonId(secTaskPerson.getId());
				taskPersonAndImageInfo.setTaskPersonRoleType(secTaskPerson.getType());
				taskPersonAndImageInfo.setTaskPersonRoleTypeName(TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getLabel());
				List<TaskPersonFile> taskPersonFiles = iTaskPersonFileService
						.list(new LambdaQueryWrapper<TaskPersonFile>().eq(TaskPersonFile::getTaskId, taskId)
								.eq(TaskPersonFile::getPersonType, TaskPersonFileEnum.IMAGE.getValue())
								.eq(TaskPersonFile::getPersonId, secTaskPerson.getPersonId())
								.orderByAsc(TaskPersonFile::getCreateDate));
				Map<Date, List<TaskFileVo>> map = new HashMap<>();
				List<TaskFileVo> taskFileVoList = new ArrayList<>();
				taskPersonFiles.forEach(i -> {
					TaskFileVo taskFileVo = new TaskFileVo();
					if (i != null) {
						BeanUtils.copyProperties(i, taskFileVo);
					}
					taskFileVoList.add(taskFileVo);
					if (map.containsKey(taskFileVo.getCreateDate())) {
						List<TaskFileVo> list = map.get(taskFileVo.getCreateDate());
						list.add(taskFileVo);
					} else {
						List<TaskFileVo> list = new ArrayList<>();
						list.add(taskFileVo);
						map.put(taskFileVo.getCreateDate(), list);
					}
				});
				if (!StringUtil.isEmpty(taskFileVoList)) {
					taskPersonAndImageInfo.setCreateTime(taskFileVoList.get(0).getCreateDate());
				}
				taskPersonAndImageInfo.setTimeFilePath(map);
				taskPersonAndImageInfo.setFilePath(taskFileVoList);
				imageList.add(taskPersonAndImageInfo);
			}
		}
		// 添加技术员照片
		if (StringUtil.isNotEmpty(techPersonList)) {
			for (TaskPerson techTaskPerson : techPersonList) {
				TaskPersonAndImageInfo taskPersonAndImageInfo = new TaskPersonAndImageInfo();
				taskPersonAndImageInfo.setTaskId(taskId);
				taskPersonAndImageInfo.setPersonId(techTaskPerson.getPersonId());
				taskPersonAndImageInfo.setPersonName(techTaskPerson.getPersonName());
				taskPersonAndImageInfo.setTaskPersonRoleType(techTaskPerson.getType());
				taskPersonAndImageInfo.setTaskPersonRoleTypeName(TaskPersonTypeEnum.TECHNICIAN.getLabel());
				List<TaskPersonFile> taskPersonFiles = iTaskPersonFileService
						.list(new LambdaQueryWrapper<TaskPersonFile>().eq(TaskPersonFile::getTaskId, taskId)
								.eq(TaskPersonFile::getPersonType, TaskPersonFileEnum.IMAGE.getValue())
								.eq(TaskPersonFile::getPersonId, techTaskPerson.getPersonId())
								.orderByAsc(TaskPersonFile::getCreateDate));
				Map<Date, List<TaskFileVo>> map = new HashMap<>();
				List<TaskFileVo> taskFileVoList = new ArrayList<>();
				taskPersonFiles.forEach(i -> {
					TaskFileVo taskFileVo = new TaskFileVo();
					if (i != null) {
						BeanUtils.copyProperties(i, taskFileVo);
					}
					taskFileVoList.add(taskFileVo);
					if (map.containsKey(taskFileVo.getCreateDate())) {
						List<TaskFileVo> list = map.get(taskFileVo.getCreateDate());
						list.add(taskFileVo);
					} else {
						List<TaskFileVo> list = new ArrayList<>();
						list.add(taskFileVo);
						map.put(taskFileVo.getCreateDate(), list);
					}
				});
				if (!StringUtil.isEmpty(taskFileVoList)) {
					taskPersonAndImageInfo.setCreateTime(taskFileVoList.get(0).getCreateDate());
				}
				taskPersonAndImageInfo.setTimeFilePath(map);
				taskPersonAndImageInfo.setFilePath(taskFileVoList);
				imageList.add(taskPersonAndImageInfo);
			}
		}
		taskRiskControlVo.setImageList(imageList);

		// 添加人员评价
		List<UserEvaluationLog> userEvaList = iUserEvaluationLogService.list(new LambdaQueryWrapper<UserEvaluationLog>()
				.eq(UserEvaluationLog::getTaskId, taskRiskControlVo.getTaskId()));
		List<UserEvaluationLogVo> userEvaVoList = new ArrayList<>();
		if (StringUtil.isEmpty(userEvaList)) {
			List<TaskPerson> personList = iTaskPersonService
					.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
							.in(TaskPerson::getType, Arrays.asList(worktypes)));
			for (TaskPerson taskPerson : personList) {
				Person person = iPersonService.getById(taskPerson.getPersonId());
				UserEvaluationLogVo userEvaluationLogVo = new UserEvaluationLogVo();
				userEvaluationLogVo.setPersonId(taskPerson.getPersonId());
				userEvaluationLogVo.setPersonName(person != null ? person.getName() : null);
				userEvaluationLogVo.setEvaluationUserId(secPerson.getId());
				userEvaluationLogVo.setEvaluationUserName(secPerson.getName());
				userEvaluationLogVo.setPhoto(person != null ? fileServerUrl + person.getHeadPhoto() : null);
				userEvaluationLogVo.setTaskId(taskRiskControl.getTaskId());
				userEvaVoList.add(userEvaluationLogVo);
			}
		} else {
			for (UserEvaluationLog userEvaluationLog : userEvaList) {
				UserEvaluationLogVo userEvaluationLogVo = new UserEvaluationLogVo();
				BeanUtils.copyProperties(userEvaluationLog, userEvaluationLogVo);
				Person person = iPersonService.getById(userEvaluationLog.getPersonId());
				userEvaluationLogVo.setRate(userEvaluationLog.getRate());
				userEvaluationLogVo.setPersonName(person.getName());
				userEvaluationLogVo.setPhoto(fileServerUrl + person.getHeadPhoto());
				userEvaVoList.add(userEvaluationLogVo);
			}
		}
		taskRiskControlVo.setUserEvaList(userEvaVoList);
		// 添加分包商评价
		List<CompanyEvaluationLog> companyEvaList = iCompanyEvaluationLogService
				.list(new LambdaQueryWrapper<CompanyEvaluationLog>().eq(CompanyEvaluationLog::getTaskId,
						taskRiskControlVo.getTaskId()));
		List<CompanyEvaluationLogVo> companyEvaVoList = new ArrayList<>();
		if (StringUtil.isEmpty(companyEvaList)) {
			Company company1 = iCompanyService.getById(company.getId());
			CompanyEvaluationLogVo companyEvaluationLogVo = new CompanyEvaluationLogVo();
			companyEvaluationLogVo.setCompanyId(taskRiskControl.getCompanyId());
			companyEvaluationLogVo.setCompanyName(company1.getName());
			companyEvaluationLogVo.setEvaluationUserId(secPerson.getId());
			companyEvaluationLogVo.setEvaluationUserName(secPerson.getName());
			companyEvaluationLogVo.setPhoto(fileServerUrl + company1.getLogo());
			companyEvaluationLogVo.setTaskId(taskRiskControl.getTaskId());
			companyEvaVoList.add(companyEvaluationLogVo);
		} else {
			CompanyEvaluationLogVo companyEvaluationLogVo = new CompanyEvaluationLogVo();
			CompanyEvaluationLog companyEvaluationLog = companyEvaList.get(0);
			BeanUtils.copyProperties(companyEvaluationLog, companyEvaluationLogVo);
			Company company1 = iCompanyService.getById(company.getId());
			companyEvaluationLogVo.setRate(companyEvaluationLog.getRate());
			companyEvaluationLogVo.setCompanyName(company1.getName());
			companyEvaluationLogVo.setPhoto(fileServerUrl + company1.getLogo());
			companyEvaVoList.add(companyEvaluationLogVo);
		}
		taskRiskControlVo.setCompanyEvaList(companyEvaVoList);
		// 获取当前登录人所扮演的角色
		TaskPerson taskPerson = iTaskPersonService.getOne(new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getId, taskPersonId));
		if (taskPerson != null) {
			taskRiskControlVo.setTaskPersonId(taskPerson.getId());
			taskRiskControlVo.setTaskPersonType(taskPerson.getType());
			taskRiskControlVo.setTaskPersonExamStatus(taskPerson.getExamStatus());
			taskRiskControlVo.setTaskPersonKnowledgeId(taskPerson.getKnowledgeId());
			taskRiskControlVo.setTaskPersonKnowledgeStatus(taskPerson.getKnowledgeStatus());
			taskRiskControlVo.setReadStatus(taskPerson.getReadStatus());
			taskRiskControlVo.setTaskPersonExpireDate(taskPerson.getExpireDate());
			taskRiskControlVo.setTaskPersonExamId(taskPerson.getExamId());
			if (taskPerson.getExamId() != null) {
				taskRiskControlVo.setExamId(taskPerson.getExamId());
			}
		}

		// 获取安全员所扮演的角色
		if (StringUtil.isNotEmpty(secPersonList)) {
			TaskPerson secTaskPerson = iTaskPersonService.getOne(new LambdaQueryWrapper<TaskPerson>()
					.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getPersonId, secPersonList.get(0).getPersonId()).eq(TaskPerson::getType, TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue()));
			taskRiskControlVo.setSecTaskPerson(secTaskPerson);
		}
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo createTask(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = new TaskRiskControl();
		BeanUtils.copyProperties(taskRiskControlVo, taskRiskControl);
		if (taskRiskControlVo.getId() == null) {
			this.save(taskRiskControl);
			taskRiskControlVo.setId(taskRiskControl.getId());
		}
		TaskRiskControlVo newTaskRiskControlVo = this.create(taskRiskControlVo);
		// 更新推送
		statisticsService.initWs(newTaskRiskControlVo.getOrgCode(), Constant.WS_COMPOSITESUM);
		statisticsService.initWs(newTaskRiskControlVo.getOrgCode(), Constant.WS_RISKSTATUS);
		statisticsService.initWs(newTaskRiskControlVo.getOrgCode(), Constant.WS_RISKSUM);

		// 微信服务通知
		List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
				.in(Person::getId, Arrays.asList(newTaskRiskControlVo.getCompanyPersonId()))
				.isNotNull(Person::getOpenId));
		List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
		List<String> messages = new ArrayList<>();
		messages.add(smallProService.getName());
		messages.add(newTaskRiskControlVo.getName());
		messages.add("请及时执行风险作业管控任务，保障项目安全管理");
		messages.add(DateUtils.getDateNowString());
		smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		return newTaskRiskControlVo;
	}

	@Override
	public Map<String, Object> getRiskWorkTrajectory(Long taskRiskControlId, Long personId) {
		Map<String, Object> resultMap = new HashMap<>();
		QueryWrapper<TaskRiskControl> taskRiskControlQueryWrapper = new QueryWrapper<>();
		taskRiskControlQueryWrapper.lambda().eq(TaskRiskControl::getId, taskRiskControlId);
		TaskRiskControl taskRiskControl = this.baseMapper.selectOne(taskRiskControlQueryWrapper);
		Optional.ofNullable(taskRiskControl).orElseThrow(() -> new BadRequest("风险计划不存在"));

		QueryWrapper<TaskPerson> personQueryWrapper = new QueryWrapper<>();
		personQueryWrapper.lambda().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId());

		List<TaskPerson> taskPersonList = iTaskPersonService.list(personQueryWrapper);
		Optional.ofNullable(taskPersonList).orElseThrow(() -> new BadRequest("该人员不在任务下"));
		List<Long> taskPeopleIds = Lists.transform(taskPersonList, TaskPerson::getPersonId);
		// 当前扫码人员
		personQueryWrapper.lambda().eq(TaskPerson::getPersonId, personId);
		List<TaskPerson> tPersons = iTaskPersonService.list(personQueryWrapper);
		TaskPerson tPerson = null;
		if (tPersons.size() > 0) {
			tPerson = tPersons.get(0);
		}
		// 人员二维码颜色
		JSONObject qrCodeColor = SmallProQrColorEum.green.getCode();
		String trajectory = TaskRiskTrajectoryStatusEnum.passed.getDescription();
		String status = TaskRiskTrajectoryStatusEnum.passed.getCode();
		int inRiskRegion = 0;
		Long taskPersonId = null;
		boolean pass_risk = true;
		// 未识别的人员
		if (CollectionUtils.isEmpty(taskPeopleIds)
				|| !CollectionUtils.isEmpty(taskPeopleIds) && !taskPeopleIds.contains(personId)) {
			qrCodeColor = SmallProQrColorEum.red.getCode();
			trajectory = TaskRiskTrajectoryStatusEnum.unknownSec.getDescription();
			status = TaskRiskTrajectoryStatusEnum.unknownSec.getCode();
			pass_risk = false;
		} else if (taskPeopleIds.contains(personId)) {
			if (tPerson.getExamId() != null && (tPerson.getExamStatus() == null || tPerson.getExamStatus() == 0)) {
				// 未开始考试或者考试未通过
				qrCodeColor = SmallProQrColorEum.red.getCode();
				trajectory = TaskRiskTrajectoryStatusEnum.examNotPassed.getDescription();
				status = TaskRiskTrajectoryStatusEnum.examNotPassed.getCode();
			} else if (tPerson.getKnowledgeId() != null
					&& (tPerson.getKnowledgeStatus() == null || tPerson.getKnowledgeStatus() == 0)) {
				// 未阅读知识
				qrCodeColor = SmallProQrColorEum.red.getCode();
				trajectory = TaskRiskTrajectoryStatusEnum.knowledgeNotRead.getDescription();
				status = TaskRiskTrajectoryStatusEnum.knowledgeNotRead.getCode();
			}
			inRiskRegion = tPerson.getInRiskRegion();
			taskPersonId = tPerson.getId();
			pass_risk = false;
		}

		boolean pass = true;
		// 技术交底 风险区域判断
		QueryWrapper<TaskRiskControlTech> taskRiskControlTechQueryWrapper = new QueryWrapper<>();
		taskRiskControlTechQueryWrapper.lambda().eq(TaskRiskControlTech::getTaskRiskControlId, taskRiskControlId);
		TaskRiskControlTech taskRiskControlTech = iTaskRiskControlTechService.getOne(taskRiskControlTechQueryWrapper);
		QueryWrapper<TaskPerson> personQueryWrapper2 = new QueryWrapper<>();
		if (taskRiskControlTech != null
		// &&qrCodeColor.equals(SmallProQrColorEum.green.getCode())
		) {
			personQueryWrapper2.lambda().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId());

			List<TaskPerson> taskPersonList2 = iTaskPersonService.list(personQueryWrapper2);
			Optional.ofNullable(taskPersonList2).orElseThrow(() -> new BadRequest("该人员不在任务下"));
			List<Long> taskPeopleIds2 = Lists.transform(taskPersonList2, TaskPerson::getPersonId);
			// 当前扫码人员
			personQueryWrapper2.lambda().eq(TaskPerson::getPersonId, personId).ne(TaskPerson::getType,
					TaskPersonTypeEnum.CREATEPERSON.getValue());
			;
			List<TaskPerson> tPersons2 = iTaskPersonService.list(personQueryWrapper2);
			TaskPerson tPerson2 = null;
			if (tPersons2.size() > 0) {
				tPerson2 = tPersons2.get(0);
			}
			// 未识别的人员
			if (CollectionUtils.isEmpty(taskPeopleIds2)
					|| !CollectionUtils.isEmpty(taskPeopleIds2) && !taskPeopleIds2.contains(personId)) {
				qrCodeColor = SmallProQrColorEum.red.getCode();
				if (TaskRiskTrajectoryStatusEnum.unknownSec.getDescription().equals(trajectory)) {
					trajectory = TaskRiskTrajectoryStatusEnum.unknown.getDescription();
					status = TaskRiskTrajectoryStatusEnum.unknown.getCode();
				} else {
					trajectory = TaskRiskTrajectoryStatusEnum.unknownTech.getDescription();
					status = TaskRiskTrajectoryStatusEnum.unknownTech.getCode();
				}
				pass = false;
			} else if (taskPeopleIds2.contains(personId)) {
				if (tPerson2.getExamId() != null
						&& (tPerson2.getExamStatus() == null || tPerson2.getExamStatus() == 0)) {
					// 未开始考试或者考试未通过
					if (SmallProQrColorEum.green.getCode().equals(qrCodeColor)) {
						trajectory = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getDescription();
						status = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getCode();
					} else {
						trajectory += "," + TaskRiskTrajectoryStatusEnum.examNotPassedTech.getDescription();
						status += "," + TaskRiskTrajectoryStatusEnum.examNotPassedTech.getCode();
					}
					qrCodeColor = SmallProQrColorEum.red.getCode();
				} else if ((tPerson2.getConstructDocumentId() != null && (tPerson2.getConstructDocumentStatus() == null
						|| tPerson2.getConstructDocumentStatus() == 0))
						|| (tPerson2.getTechDocumentId() != null && (tPerson2.getTechDocumentStatus() == null
								|| tPerson2.getTechDocumentStatus() == 0))) {
					// 未阅读知识
					if (SmallProQrColorEum.green.getCode().equals(qrCodeColor)) {
						trajectory = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getDescription();
						status = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getCode();
					} else {
						trajectory += "," + TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getDescription();
						status += "," + TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getCode();
					}
					qrCodeColor = SmallProQrColorEum.red.getCode();
				}
				pass = false;
				// inRiskRegion = tPerson2.getInRiskRegion();
				// taskPersonId = tPerson2.getId();
			}

			if (TaskRiskTrajectoryStatusEnum.unknown.getDescription().equals(trajectory)
					|| TaskRiskTrajectoryStatusEnum.unknownTech.getDescription().equals(trajectory)
					|| TaskRiskTrajectoryStatusEnum.passed.getDescription().equals(trajectory)) {
				// 技术交底安全 风险区域判断
				QueryWrapper<TaskRiskControlTech> taskRiskControlTechQueryWrapper3 = new QueryWrapper<>();
				taskRiskControlTechQueryWrapper3.lambda().eq(TaskRiskControlTech::getConstructTaskRiskControlTechId,
						taskRiskControlTech.getId());
				List<TaskRiskControlTech> taskRiskControlTechList = iTaskRiskControlTechService
						.list(taskRiskControlTechQueryWrapper3);
				if (!taskRiskControlTechList.isEmpty()) {
					for (TaskRiskControlTech taskRiskControlTech3 : taskRiskControlTechList) {
						QueryWrapper<TaskPerson> personQueryWrapper3 = new QueryWrapper<>();
						personQueryWrapper3.lambda().eq(TaskPerson::getTaskId, taskRiskControlTech3.getTaskId());

						List<TaskPerson> taskPersonList3 = iTaskPersonService.list(personQueryWrapper3);
//						Optional.ofNullable(taskPersonList3).orElseThrow(() -> new BadRequest("该人员不在任务下"));
						List<Long> taskPeopleIds3 = Lists.transform(taskPersonList3, TaskPerson::getPersonId);
						// 当前扫码人员
						personQueryWrapper3.lambda().eq(TaskPerson::getPersonId, personId).ne(TaskPerson::getType,
								TaskPersonTypeEnum.CREATEPERSON.getValue());
						List<TaskPerson> tPersons3 = iTaskPersonService.list(personQueryWrapper3);
						TaskPerson tPerson3 = null;
						if (tPersons3.size() > 0) {
							tPerson3 = tPersons3.get(0);
						} else {
							continue;
						}
						// 未识别的人员
						if (CollectionUtils.isEmpty(taskPeopleIds3)
								|| !CollectionUtils.isEmpty(taskPeopleIds3) && !taskPeopleIds3.contains(personId)) {
							qrCodeColor = SmallProQrColorEum.red.getCode();
							trajectory = TaskRiskTrajectoryStatusEnum.unknownTech.getDescription();
							status = TaskRiskTrajectoryStatusEnum.unknownTech.getCode();
						} else if (taskPeopleIds3.contains(personId)) {
							// 如果已经是未识别人员 由于技术交底存在 则变为安全考核未识别的人员
							if (TaskRiskTrajectoryStatusEnum.unknown.getCode().equals(status)) {
								trajectory = TaskRiskTrajectoryStatusEnum.unknownSec.getDescription();
								status = TaskRiskTrajectoryStatusEnum.unknownSec.getCode();
							}
							if (tPerson3.getExamId() != null
									&& (tPerson3.getExamStatus() == null || tPerson3.getExamStatus() == 0)) {
								// 未开始考试或者考试未通过
								if (SmallProQrColorEum.green.getCode().equals(qrCodeColor)) {
									trajectory = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getDescription();
									status = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getCode();
								} else if (SmallProQrColorEum.red.getCode().equals(qrCodeColor)
										&& (TaskRiskTrajectoryStatusEnum.unknown.getDescription().equals(trajectory)
												|| TaskRiskTrajectoryStatusEnum.unknownTech.getDescription()
														.equals(trajectory))) {
									trajectory = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getDescription();
									status = TaskRiskTrajectoryStatusEnum.examNotPassedTech.getCode();
								} else {
									trajectory += "," + TaskRiskTrajectoryStatusEnum.examNotPassedTech.getDescription();
									status += "," + TaskRiskTrajectoryStatusEnum.examNotPassedTech.getCode();
								}
								qrCodeColor = SmallProQrColorEum.red.getCode();
							} else if ((tPerson3.getConstructDocumentId() != null
									&& (tPerson3.getConstructDocumentStatus() == null
											|| tPerson3.getConstructDocumentStatus() == 0))
									|| (tPerson3.getTechDocumentId() != null
											&& (tPerson3.getTechDocumentStatus() == null
													|| tPerson3.getTechDocumentStatus() == 0))) {
								// 未阅读知识
								if (SmallProQrColorEum.green.getCode().equals(qrCodeColor)) {
									trajectory = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getDescription();
									status = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getCode();
								} else if (SmallProQrColorEum.red.getCode().equals(qrCodeColor)
										&& (TaskRiskTrajectoryStatusEnum.unknown.getDescription().equals(trajectory)
												|| TaskRiskTrajectoryStatusEnum.unknownTech.getDescription()
														.equals(trajectory))) {
									trajectory = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getDescription();
									status = TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getCode();
								} else {
									trajectory += ","
											+ TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getDescription();
									status += "," + TaskRiskTrajectoryStatusEnum.knowledgeNotReadTech.getCode();
								}
								qrCodeColor = SmallProQrColorEum.red.getCode();
							} else {
								if (!pass && pass_risk) {
									qrCodeColor = SmallProQrColorEum.green.getCode();
									trajectory = TaskRiskTrajectoryStatusEnum.passed.getDescription();
									status = TaskRiskTrajectoryStatusEnum.passed.getCode();
								}
							}
						} else {
							if (!pass && pass_risk) {
								qrCodeColor = SmallProQrColorEum.green.getCode();
								trajectory = TaskRiskTrajectoryStatusEnum.passed.getDescription();
								status = TaskRiskTrajectoryStatusEnum.passed.getCode();
							}
						}
					}
				}
			}
		}

		String page = SmallProPageEnum.personDetail.getPath();
		String token = smallProService.getSmallProToken();
		String bizId = personId.toString();
		byte[] qrCode = smallProService.getSmallProQrCodeByte(token, bizId, page, 300L, false, qrCodeColor, false);
		BASE64Encoder encoder = new BASE64Encoder();
		resultMap.put("safetyQrCode", "data:image/png;base64," + encoder.encode(qrCode));
		resultMap.put("trajectory", trajectory);
		resultMap.put("status", status);
		resultMap.put("qrCodeColor", qrCodeColor);
		resultMap.put("inRiskRegion", inRiskRegion);
		resultMap.put("taskPersonId", taskPersonId);
		resultMap.put("taskRiskControlId", taskRiskControlId);

		return resultMap;
	}

	@Override
	public Page<TaskRiskControlVo> myListByPage(CommonPageableDto pageable, Long personId,
			TaskRiskControlDto taskRiskControlDto) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<TaskRiskControlVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Page<TaskRiskControlVo> result = this.baseMapper.myListByPage(page, taskRiskControlDto.getPersonId(),
				taskRiskControlDto);
		for (TaskRiskControlVo taskRiskControlVo : result.getRecords()) {
			List<TaskPerson> taskpersons = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
					.eq(TaskPerson::getTaskId, taskRiskControlVo.getTaskId()).eq(TaskPerson::getPersonId, personId));
//			TaskPerson exectueTaskPerson = getExecuteTaskPerson(taskpersons);
//			taskRiskControlVo
//					.setReadStatus(exectueTaskPerson != null ? exectueTaskPerson.getReadStatus().intValue() : 1L);
			//taskRiskControlVo.setTaskPersonType(exectueTaskPerson != null ? exectueTaskPerson.getType() : null);
			taskRiskControlVo.setTaskPersonRoleTypeName(TaskPersonTypeEnum.getLabelByValue(taskRiskControlVo.getTaskPersonType()));
		}
		return result;
	}

	private TaskPerson getExecuteTaskPerson(List<TaskPerson> taskpersons) {
		if (StringUtil.isEmpty(taskpersons)) {
			return null;
		}
		TaskPerson taskPerson = taskpersons.get(0);
		for (TaskPerson t : taskpersons) {
			if (taskPerson.getReadStatus() == StatusEnum.SUCCESS.getValue()) {
				continue;
			} else {
				return t;
			}
		}
		return taskPerson;
	}

	@Override
	public void entryOrExitRiskRegion(Integer operate, Long taskPersonId, Long taskRiskControlId) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskPersonId);
		Optional.ofNullable(taskPerson).orElseThrow(() -> new BadRequest("作业活动关联人员记录不存在"));
		taskPerson.setInRiskRegion(operate);
		// 人员进场，累加人数
		if (operate == InRiskRegionEnum.inRiskRegion.getStatus()) {
			// 判断存在已经进入的风险作业
			List<TaskPerson> list = iTaskPersonService
					.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getPersonId, taskPerson.getPersonId())
							.eq(TaskPerson::getInRiskRegion, InRiskRegionEnum.inRiskRegion.getStatus())
							.ne(TaskPerson::getTaskId, taskPerson.getTaskId()));
			
			if (list.size() > 0) {
				TaskRiskControl taskRiskControl = this.getOne(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getTaskId, list.get(0).getTaskId()));
				String name = taskRiskControl!=null?taskRiskControl.getName():"";
				throw new BadRequest("存在未退出的风险作业: "+name+"，禁止进入");
			}
			TaskRiskControl taskRiskControl = this.getById(taskRiskControlId);
			Optional.ofNullable(taskRiskControl).orElseThrow(() -> new BadRequest("风险作业计划不存在"));
			int pCount = taskRiskControl.getPersonCount() != null ? taskRiskControl.getPersonCount() : 0;
			taskRiskControl.setPersonCount(pCount + 1);
			this.updateById(taskRiskControl);
		}
		iTaskPersonService.saveOrUpdate(taskPerson);
	}

	@Override
	public Object personStatistics(Long taskRiskControlId) {
		Map<String, Object> result = new HashMap<>(2);
		// 1.总人数：rpm_task_risk_control--->person_count
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlId);
		if (taskRiskControl == null) {
			throw new CommonException(700001, "作业任务不存在");
		}
		result.put("total", taskRiskControl.getPersonCount());

		/*
		 * 2.已入场人数，任务需要开启后，才有记录--->rpm_task_person 统计`in_risk_region` tinyint(1) DEFAULT
		 * '0' COMMENT '是否进入风险区域(0：未进场，1：已进场)',
		 */
		int count = 0;
		List<TaskPerson> taskPersonList = this.getTaskPeople(taskRiskControl);
		long in = taskPersonList.stream().filter(t -> t.getInRiskRegion() != null && t.getInRiskRegion() == 1).count();
		count += in;
		result.put("inRiskRegion", count);
		return result;
	}

	private List<TaskPerson> getTaskPeople(TaskRiskControl taskRiskControl) {
		LambdaQueryWrapper<TaskPerson> wrapper = new LambdaQueryWrapper<>();
		if (taskRiskControl.getTaskId() != null) {
			wrapper.eq(TaskPerson::getTaskId, taskRiskControl.getTaskId());
		}
		QueryWrapper<TaskRiskControlTech> taskRiskControlTechQueryWrapper = new QueryWrapper<>();
		taskRiskControlTechQueryWrapper.lambda().eq(TaskRiskControlTech::getTaskRiskControlId, taskRiskControl.getId());
		TaskRiskControlTech taskRiskControlTech = iTaskRiskControlTechService.getOne(taskRiskControlTechQueryWrapper);
		if (taskRiskControlTech != null && taskRiskControlTech.getTaskId() != null) {
			wrapper.or().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId());
		}
		return iTaskPersonService.list(wrapper);
	}

	@Override
	public List<TaskWorkPersonVo> personListInTaskRisk(Long taskRiskControlId, Integer status) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlId);
		if (taskRiskControl == null) {
			throw new CommonException(700001, "风险作业任务不存在");
		}

		List<TaskWorkPersonVo> list = new ArrayList<>();

		if (taskRiskControl.getTaskId() != null) {
			list.addAll(this.getBaseMapper().listPersonInTask(taskRiskControl.getTaskId(), status, THREE_LEVEL_EXAM));
		}

		QueryWrapper<TaskRiskControlTech> taskRiskControlTechQueryWrapper = new QueryWrapper<>();
		taskRiskControlTechQueryWrapper.lambda().eq(TaskRiskControlTech::getTaskRiskControlId, taskRiskControl.getId());
		TaskRiskControlTech taskRiskControlTech = iTaskRiskControlTechService.getOne(taskRiskControlTechQueryWrapper);
		if (taskRiskControlTech != null && taskRiskControlTech.getTaskId() != null) {
			list.addAll(
					this.getBaseMapper().listPersonInTask(taskRiskControlTech.getTaskId(), status, THREE_LEVEL_EXAM));
		}
		return list;
	}

	@Override
	@Transactional
	public String deleteByIds(List<String> idList) {
		List<TaskRiskControl> taskRiskControls = (List<TaskRiskControl>) this.listByIds(idList);
		List<Long> startList = taskRiskControls.stream().filter(t -> null != t.getTaskId()).map(p -> p.getId())
				.collect(Collectors.toList());
		List<Long> startTaskList = taskRiskControls.stream().filter(t -> null != t.getTaskId()).map(p -> p.getTaskId())
				.collect(Collectors.toList());
		List<Long> unStartList = taskRiskControls.stream().filter(t -> null == t.getTaskId()).map(p -> p.getId())
				.collect(Collectors.toList());
		List<TaskRiskControl> completeList = taskRiskControls.stream().filter(t -> t.getStage() == 99)
				.collect(Collectors.toList());
		// 有已完成不让删除
		if (!StringUtil.isEmpty(completeList)) {
			List<String> taskRiskPlanNames = Lists.transform(completeList, TaskRiskControl::getName);
			throw new BadRequest("【" + Joiner.on(",").join(taskRiskPlanNames) + "】 已完成计划无法删除，请重新选择");
		}
		// 先删除未开始的
		if (!StringUtil.isEmpty(unStartList)) {
			this.removeByIds(unStartList);
		}
		// 再删删除已经开始的任务
		// 1 删除预选人员表
		if (!StringUtil.isEmpty(startTaskList)) {
			iTaskRiskControlPrePersonService.remove(new LambdaQueryWrapper<TaskRiskControlPrePerson>()
					.in(TaskRiskControlPrePerson::getTaskId, startTaskList));
			// 2 删除任务人员表
			iTaskPersonService.remove(new LambdaQueryWrapper<TaskPerson>().in(TaskPerson::getTaskId, startTaskList));

			// 3删除任务表
			iTaskService.remove(new LambdaQueryWrapper<Task>().in(Task::getId, startTaskList));

			// 4删除风险作业
			this.removeByIds(startList);
		}
		return "success";
//		} else {
//			List<String> taskRiskPlanNames = Lists.transform(hasTaskList, TaskRiskControl::getName);
//			throw new BadRequest("【" + Joiner.on(",").join(taskRiskPlanNames) + "】 已关联任务，请核对后删除");
//		}
	}

	@Override
	public List<TaskRiskControlVo> listByConfig(String orgCode) {
		return this.baseMapper.listByConfig(orgCode, riskWorkSize);
	}

	@Override
	public void taskRiskNotice(TaskRiskControlVo riskControlVo, Long companyPersonId) {
		List<Long> personIdList = Lists.newArrayList();
		personIdList.add(companyPersonId);
		taskRiskNotice(riskControlVo, personIdList);
	}

	private void taskRiskNotice(TaskRiskControlVo riskControlVo, List<Long> personIdList) {
		if (!CollectionUtils.isEmpty(personIdList)) {
			JSONArray array = new JSONArray();
			personIdList.forEach(id -> {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.RISK_WORK.getType());
				jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
						MessageSubTypeEnum.RISK_WORK_TODO.getType());
				jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), id);
				jsonObject.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.RISK_WORK_TODO.getTip());
				jsonObject.put(MessageAttributeEnum.TASK_ID.getName(), riskControlVo.getId());
				jsonObject.put(MessageAttributeEnum.PARAM.getName(), riskControlVo.getStage());
				array.add(jsonObject);
			});

			JSONObject data = new JSONObject();
			data.put("param", array);
			messageEventPublish.publish(data);
		}
	}

	@Override
	public Object statisticsByLevel(Map<String, Object> param) {
		return this.baseMapper.statisticsByLevel(param);
	}

	@Override
	public Page<TaskRiskControlAppVo> listTaskByYearPage(CommonPageable pageable, Integer level, String name,
			String status, String beginDate, String endDate, String orgCode) {
		// 注释
		Map<String, Object> param = new LinkedHashMap<>();
		param.put("level", level);
		param.put("name", name);
		param.put("stage", status);
		param.put("beginDate", beginDate);
		param.put("endDate", endDate);
		param.put("orgCode", orgCode);
		Page<TaskRiskControlAppVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		return this.baseMapper.listTaskByYearPage(page, param);
	}

	@Override
	public List<String> listYear(String orgCode, String level) {
		return this.baseMapper.queryBeginDateYear(orgCode, level);
	}

	@Override
	public TaskRiskControlVo read(TaskRiskControlVo taskRiskControlVo) {
		TaskPerson taskPerson = new TaskPerson();
		taskPerson.setReadStatus(1L);
		iTaskPersonService.update(taskPerson,
				new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getId, taskRiskControlVo.getTaskPersonId()));
		return taskRiskControlVo;
	}

	@Override
	@Transactional
	public TaskRiskControlVo createTaskByFbs(TaskRiskControlVo taskRiskControlVo) {
		Person person = iPersonService.getById(taskRiskControlVo.getSecPersonId());
		taskRiskControlVo.setOrgCode(person.getOrgCode());
		taskRiskControlVo.setCreatePersonId(taskRiskControlVo.getCompanyPersonId());
		this.createTask(taskRiskControlVo);
		this.nextStage(taskRiskControlVo);
		return taskRiskControlVo;
	}

	@Override
	public boolean cancel(TaskRiskControlVo taskRiskControlVo) {
		this.removeById(taskRiskControlVo.getId());
		return true;
	}

	@Override
	public TaskRiskControlVo reCreate(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());
		// 保存新增的人员
		List<Long> workIdList = new ArrayList<>();
		List<TaskRiskControlPrePerson> prolist = new ArrayList<TaskRiskControlPrePerson>();
		if (taskRiskControlVo.getPreProPersonList() != null) {
			taskRiskControlVo.getPreProPersonList().stream().forEach(i -> {
				TaskRiskControlPrePerson taskRiskControlPrePerson = new TaskRiskControlPrePerson();
				i.setTaskId(taskRiskControl.getTaskId());
				i.setType(TaskPersonTypeEnum.PRO_WORKER.getValue());
				BeanUtils.copyProperties(i, taskRiskControlPrePerson);
				if (!i.isUsed()) {
					prolist.add(taskRiskControlPrePerson);
				}
				workIdList.add(i.getPersonId());
			});
		}
		List<TaskRiskControlPrePerson> assistlist = new ArrayList<TaskRiskControlPrePerson>();
		if (taskRiskControlVo.getPreAssistPersonList() != null) {
			taskRiskControlVo.getPreAssistPersonList().stream().forEach(i -> {
				TaskRiskControlPrePerson taskRiskControlPrePerson = new TaskRiskControlPrePerson();
				i.setTaskId(taskRiskControl.getTaskId());
				i.setType(TaskPersonTypeEnum.ASSIST_WORKER.getValue());
				BeanUtils.copyProperties(i, taskRiskControlPrePerson);
				if (!i.isUsed()) {
					assistlist.add(taskRiskControlPrePerson);
				}
				workIdList.add(i.getPersonId());
			});
		}
		// 校验重复
		Set<Long> workIdSet = new HashSet<>(workIdList);
		if (workIdSet.size() != workIdList.size()) {
			throw new BaseException("专业人员和辅助人员不能重复");
		}
		// 校验不能分包商负责人
		TaskPerson taskPerson = iTaskPersonService
				.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.DIRECTOR.getValue()));
		if (workIdSet.contains(taskPerson.getPersonId())) {
			throw new BaseException("专业人员和辅助人员不能是作业管理人");
		}
		iTaskRiskControlPrePersonService.saveBatch(prolist);
		iTaskRiskControlPrePersonService.saveBatch(assistlist);
		taskRiskControl.setStage(TaskRiskStageEnum.SELECT_EXAM_KNOWLEDGE.getValue());
		this.updateById(taskRiskControl);
		// 消息通知--给项目安全负责人发送
		taskRiskNotice(taskRiskControlVo, taskRiskControl.getSecPersonId());

		// 微信服务通知
		List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
				.in(Person::getId, Arrays.asList(taskRiskControl.getSecPersonId())).isNotNull(Person::getOpenId));
		List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
		List<String> messages = new ArrayList<>();
		messages.add(smallProService.getName());
		messages.add(taskRiskControl.getName());
		messages.add("请及时执行风险作业管控任务，保障项目安全管理");
		messages.add(DateUtils.getDateNowString());
		smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		return taskRiskControlVo;
	}

	@Override
	public TaskRiskControlVo reCreateBySec(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = this.getById(taskRiskControlVo.getId());
		taskRiskControl.setStage(TaskRiskStageEnum.SELECT_WORKER.getValue());
		this.updateById(taskRiskControl);
		// 消息通知--给分包商负责人发送
		TaskPerson companyPerson = iTaskPersonService
				.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControl.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.DIRECTOR.getValue()));
		taskRiskNotice(taskRiskControlVo, companyPerson.getPersonId());
		return taskRiskControlVo;
	}

	@Override
	public TaskRiskControlDetailVo taskRiskDetail(Long id) {
		return taskRiskControlMapper.taskRiskDetail(id);
	}

	@Override
	public List<TaskWorkPersonVo> riskPersonList(Long id, Long value) {
		return taskRiskControlMapper.riskPersonList(id, value);
	}

	@Override
	public List<TaskRiskControlDetailVo> riskNeedProcessList(String orgCode, Long projectId) {
		return taskRiskControlMapper.riskNeedProcessList(orgCode, projectId);
	}

	@Override
	public IPage<Object> riskWorkPageInfo(CommonPageableDto pageable, String orgCode, Integer status,
			TaskRiskControlVo taskRiskControlVo) {
		Page<BadCompanyVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		return taskRiskControlMapper.riskWorkPageInfo(page, orgCode, status, taskRiskControlVo);
	}

	@Override
	public IPage<Object> antiViolationPageInfo(CommonPageableDto pageable, String orgCode, Integer status,
			Long projectId) {
		Page<BadCompanyVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		return taskRiskControlMapper.antiViolationPageInfo(page, orgCode, status, projectId);
	}

	@Override
	public TaskRiskControlVo save(TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = new TaskRiskControl();
		// 保存风险作业
		BeanUtils.copyProperties(taskRiskControlVo, taskRiskControl);
		nullFiledCheck(taskRiskControl);
		Project project = iProjectService.getById(taskRiskControl.getProjectId());
		taskRiskControl.setOrgCode(project.getOrgCode());
		this.save(taskRiskControl);

		// 保存技术交底
		TaskRiskControlTechVo taskRiskControlTechVo = taskRiskControlVo.getRiskControlTechVo();
		if (taskRiskControlTechVo != null) {
			// 判断是否发技术交底 如果有完整的流程则不发
			// 1 完成过单技术和单安全
			List<TaskRiskControlTech> cList = iTaskRiskControlTechService
					.list(new LambdaQueryWrapper<TaskRiskControlTech>()
							.eq(TaskRiskControlTech::getConstructDocumentId,
									taskRiskControlTechVo.getConstructDocumentId())
							.eq(TaskRiskControlTech::getType, TaskRiskControlTechTypeEnum.ONLY_CONSTRUCT.getCode())
							.eq(TaskRiskControlTech::getStage, TaskRiskControlStatusEnum.finished.getStage()));
			List<Long> cIds = cList.stream().map(i -> i.getId()).collect(Collectors.toList());
			int count1 = 0;
			if(cIds.size()>0) 
			{
				 count1 = iTaskRiskControlTechService.count(new LambdaQueryWrapper<TaskRiskControlTech>()
						.in(TaskRiskControlTech::getConstructTaskRiskControlTechId, cIds)
						.eq(TaskRiskControlTech::getType, TaskRiskControlTechTypeEnum.ONLY_DISCLOSURE.getCode())
						.eq(TaskRiskControlTech::getStage, TaskRiskControlStatusEnum.finished.getStage()));
			}
			//如果不满足1则进行2判断
			if (count1 == 0) {
				// 2完成过组合
				int count2 = iTaskRiskControlTechService.count(new LambdaQueryWrapper<TaskRiskControlTech>()
						.eq(TaskRiskControlTech::getConstructDocumentId, taskRiskControlTechVo.getConstructDocumentId())
						.eq(TaskRiskControlTech::getType, TaskRiskControlTechTypeEnum.BOTH.getCode())
						.eq(TaskRiskControlTech::getStage, TaskRiskControlStatusEnum.finished.getStage()));
				//如果不满足2则发起技术交底
				if (count2 == 0) {
					TaskRiskControlTech taskRiskControlTech = new TaskRiskControlTech();
					taskRiskControlTech.setTaskRiskControlId(taskRiskControl.getId());
					taskRiskControlTech.setName(taskRiskControlVo.getName());
					taskRiskControlTech.setTechPersonId(taskRiskControlTechVo.getTechPersonId());
					taskRiskControlTech.setProjectId(taskRiskControlVo.getProjectId());
					taskRiskControlTech.setOrgCode(project.getOrgCode());
					taskRiskControlTech.setStage(TaskRiskTechStageEnum.UN_START.getValue());
					taskRiskControlTech.setType(TaskRiskControlTechTypeEnum.ONLY_CONSTRUCT.getCode());
					taskRiskControlTech.setConstructDocumentId(taskRiskControlTechVo.getConstructDocumentId());
					iTaskRiskControlTechService.save(taskRiskControlTech);
				}else 
				{
					taskRiskControl.setTechPersonId(taskRiskControlTechVo.getTechPersonId());
					taskRiskControl.setConstructDocumentId(taskRiskControlTechVo.getConstructDocumentId());
					log.debug("满足条件2组合任务:"+taskRiskControlTechVo.getConstructDocumentId());
				}
			}else 
			{
				taskRiskControl.setTechPersonId(taskRiskControlTechVo.getTechPersonId());
				taskRiskControl.setConstructDocumentId(taskRiskControlTechVo.getConstructDocumentId());
				log.debug("满足条件1单技术和单安全:"+taskRiskControlTechVo.getConstructDocumentId());
			}
			this.updateById(taskRiskControl);
		}
		return taskRiskControlVo;
	}

	/**
	 * 字段是否为空校验
	 *
	 * @param taskRiskControl
	 */
	public void nullFiledCheck(@RequestBody TaskRiskControl taskRiskControl) {
		Optional.ofNullable(taskRiskControl.getProjectId()).orElseThrow(() -> new BadRequest("项目名称不能为空"));
		Optional.ofNullable(taskRiskControl.getName()).orElseThrow(() -> new BadRequest("风险作业计划名称不能为空"));
		Optional.ofNullable(taskRiskControl.getRiskWorkId()).orElseThrow(() -> new BadRequest("风险作业不能为空"));
		Optional.ofNullable(taskRiskControl.getStartTime()).orElseThrow(() -> new BadRequest("计划开始时间不能为空"));
		Optional.ofNullable(taskRiskControl.getEndTime()).orElseThrow(() -> new BadRequest("计划结束时间不能为空"));
		// Optional.ofNullable(taskRiskControl.getPreStartTime()).orElseThrow(() -> new
		// BadRequest("提前启动时间不能为空"));
		Optional.ofNullable(taskRiskControl.getSecPersonId()).orElseThrow(() -> new BadRequest("安全责任人不能为空"));
	}
}
