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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
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.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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.TaskRiskControlTechDto;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskCompanyPerson;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskPersonFile;
import com.yeejoin.precontrol.common.entity.TaskPersonKnowledgeAttachment;
import com.yeejoin.precontrol.common.entity.TaskRiskControlTech;
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.StatusEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonFileEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskControlTechTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskTechStageEnum;
import com.yeejoin.precontrol.common.enums.TaskStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.mapper.TaskRiskControlTechMapper;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.ITaskPersonFileService;
import com.yeejoin.precontrol.common.service.ITaskPersonKnowledgeAttachmentService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlTechService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.TaskRiskControlTechVo;

/**
 * 风险管控任务表 服务实现类
 *
 * @author duanwei
 * @date 2021-11-01
 */
@Service
public class TaskRiskControlTechServiceImpl extends ServiceImpl<TaskRiskControlTechMapper, TaskRiskControlTech>
		implements ITaskRiskControlTechService {

	@Autowired
	ITaskService iTaskService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	ITaskPersonService iTaskPersonService;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	ITaskPersonFileService iTaskPersonFileService;

	@Autowired
	IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	ITaskPersonKnowledgeAttachmentService iTaskPersonKnowledgeAttachmentService;

	@Autowired
	AmosTrainingFeignClient examFeign;

	@Autowired
	MessageEventPublish messageEventPublish;

    /**
     * 文件服务器地址
     */
    @Value("${fileserver.domain}")
    String fileServerUrl;
    
    @Autowired
    KnowledgebaseFeignClient 	knowledgeBaseFeign;
	
	
	@Override
	@Transactional
	public TaskRiskControlTechVo createTask(TaskRiskControlTechVo taskRiskControlTechVo) {
		TaskRiskControlTech taskRiskControl = this.getById(taskRiskControlTechVo.getId());
		if (taskRiskControl == null) {
			taskRiskControl = new TaskRiskControlTech();
			taskRiskControl.setTechPersonId(taskRiskControlTechVo.getTechPersonId());
			taskRiskControl.setProjectId(taskRiskControlTechVo.getProjectId());

			Project project = iProjectService.getById(taskRiskControlTechVo.getProjectId());
			taskRiskControl.setOrgCode(project != null ? project.getOrgCode() : null);
			taskRiskControl.setName(taskRiskControlTechVo.getName());
		}
		if (taskRiskControl.getTaskId() != null) {
			return taskRiskControlTechVo;
		}
		Task task = new Task();
		task.setType(TaskTypeEnum.TECH_DISCLOSURE.getValue());
		Person person = iPersonService.getById(taskRiskControlTechVo.getTechPersonId());
		task.setCreatePersonId(taskRiskControlTechVo.getCreatePersonId());
		task.setStatus(TaskStatusEnum.UNCOMPLETED.getLongType());

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

		if (taskRiskControlTechVo.getType() == 1) {
			taskRiskControlTechVo.setConstructDocumentId(null);
		}
		if (taskRiskControl.getConstructDocumentId() == null) {
			taskRiskControl.setConstructDocumentId(taskRiskControlTechVo.getConstructDocumentId());
		}
		if (taskRiskControl.getConstructDisclosureDocumentId() == null) {
			taskRiskControl.setConstructDisclosureDocumentId(taskRiskControlTechVo.getConstructDisclosureDocumentId());
		}
		taskRiskControl.setConstructTaskRiskControlTechId(taskRiskControlTechVo.getConstructTaskRiskControlTechId());
		taskRiskControl.setConstructTaskRiskControlName(taskRiskControlTechVo.getConstructTaskRiskControlName());
		taskRiskControl.setTechDocumentId(taskRiskControlTechVo.getTechDocumentId());
		taskRiskControl.setStage(TaskRiskTechStageEnum.SELECT_PERSON_EXAM_KNOWLEDGE.getValue());
		taskRiskControl.setTaskId(task.getId());
		taskRiskControl.setType(taskRiskControlTechVo.getType());
		this.saveOrUpdate(taskRiskControl);

		PersonAscription ascription = iPersonAscriptionService.getOne(new LambdaQueryWrapper<PersonAscription>()
				.eq(PersonAscription::getPersonId, taskRiskControl.getTechPersonId()));
		TaskPerson taskPerson = new TaskPerson();
		taskPerson.setPersonId(taskRiskControl.getTechPersonId());
		taskPerson.setPersonName(person.getName());
		taskPerson.setCompanyId(ascription.getCompanyId());
		taskPerson.setReadStatus(0L);
		taskPerson.setType(TaskPersonTypeEnum.CREATEPERSON.getValue());
		taskPerson.setTaskId(task.getId());
		iTaskPersonService.save(taskPerson);

		List<TaskPerson> taskPersonList = new ArrayList<TaskPerson>();
		// 项目部人员
		Company company = iCompanyService
				.getOne(new LambdaQueryWrapper<Company>().eq(Company::getTypeKey, TypeKeyEnum.JXDJ.getType()));
		List<TaskPerson> techPersonList = taskRiskControlTechVo.getTechPersonList();
		techPersonList.forEach(i -> {
			i.setTaskId(task.getId());
			i.setCompanyId(company.getId());
			i.setType(TaskPersonTypeEnum.TECHNICIAN.getValue());
			i.setFirstRead(false);
			i.setReadStatus(0L);
//			if (taskRiskControlTechVo.getType() != TaskRiskControlTechTypeEnum.ONLY_DISCLOSURE.getCode()) {
//				i.setReadStatus(0L);
//			} else {
//				i.setReadStatus(1L);
//			}
		});
		taskPersonList.addAll(techPersonList);
		List<TaskPerson> secPersonList = taskRiskControlTechVo.getSecPersonList();
		secPersonList.forEach(i -> {
			i.setTaskId(task.getId());
			i.setCompanyId(company.getId());
			i.setType(TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue());
			i.setFirstRead(false);
			i.setReadStatus(0L);
//			if (taskRiskControlTechVo.getType() != TaskRiskControlTechTypeEnum.ONLY_DISCLOSURE.getCode()) {
//				i.setReadStatus(0L);
//			} else {
//				i.setReadStatus(1L);
//			}
		});
		taskPersonList.addAll(secPersonList);
		List<TaskPerson> proPersonList = taskRiskControlTechVo.getProPersonList();
		proPersonList.forEach(i -> {
			i.setTaskId(task.getId());
			i.setCompanyId(company.getId());
			i.setType(TaskPersonTypeEnum.ENGINEERINGSTAFF.getValue());
			i.setFirstRead(false);
			i.setReadStatus(0L);
//			if (taskRiskControlTechVo.getType() != TaskRiskControlTechTypeEnum.ONLY_DISCLOSURE.getCode()) {
//				i.setReadStatus(0L);
//			} else {
//				i.setReadStatus(1L);
//			}
		});
		taskPersonList.addAll(proPersonList);
		List<TaskPerson> otherPersonList = taskRiskControlTechVo.getOtherPersonList();
		otherPersonList.forEach(i -> {
			i.setTaskId(task.getId());
			i.setCompanyId(company.getId());
			i.setType(TaskPersonTypeEnum.OTHER.getValue());
			i.setFirstRead(false);
			i.setReadStatus(0L);
//			if (taskRiskControlTechVo.getType() != TaskRiskControlTechTypeEnum.ONLY_DISCLOSURE.getCode()) {
//				i.setReadStatus(0L);
//			} else {
//				i.setReadStatus(1L);
//			}
		});
		taskPersonList.addAll(otherPersonList);

		StringBuffer userIds = new StringBuffer();
		List<TaskPerson> examList = taskRiskControlTechVo.getExamPersonList();
		List<Long> examPersonIds = new ArrayList<>();
		if (examList != null&&taskRiskControlTechVo.getExamTemplateId()!=null) {
			examList.forEach(i -> {
				Person ePerson = iPersonService.getById(i.getPersonId());
				userIds.append(ePerson.getUserId() + ",");
				examPersonIds.add(i.getPersonId());
			});
		}

		Long examId = null;
		// 获取考试id
		if (userIds.toString().length() > 0) {
			// 发送考试
			CreatExamDto creatExamDto = new CreatExamDto();
			creatExamDto.setBusinessKey(taskRiskControl.getTaskId().toString());
			creatExamDto.setId(taskRiskControlTechVo.getExamTemplateId());
			creatExamDto.setIsAgain(1);
			creatExamDto.setUserIds(userIds.toString().substring(0, userIds.toString().length() - 1));
			creatExamDto.setIsMiniApp(false);
			ResponseModel<Long> response = examFeign.doTemplateExam(creatExamDto);
			// 获取考试id
			examId = response.getResult();
			if (examId == null) {
				throw new BaseException("获取考试id失败");
			}
		}

		taskRiskControlTechVo.setTaskId(taskRiskControl.getTaskId());
		taskRiskControlTechVo.setExamId(examId);
		taskRiskControlTechVo.setStage(taskRiskControl.getStage());
		// 分包商人员
		List<TaskCompanyPerson> taskCompanyPersons = taskRiskControlTechVo.getCompanyPersonList();
		for (TaskCompanyPerson taskCompanyPerson : taskCompanyPersons) {
			List<TaskPerson> fbsTechPersonList = taskCompanyPerson.getTechPersonList();
			if (fbsTechPersonList != null) {
				fillTaskPerson(fbsTechPersonList, examPersonIds, taskRiskControlTechVo,
						TaskPersonTypeEnum.FBS_TECHNICIAN, taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(fbsTechPersonList);
			}
			List<TaskPerson> fbsSecPersonList = taskCompanyPerson.getSecPersonList();
			if (fbsSecPersonList != null) {
				fillTaskPerson(fbsSecPersonList, examPersonIds, taskRiskControlTechVo, TaskPersonTypeEnum.SAFETYOFFICER,
						taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(fbsSecPersonList);
			}
			List<TaskPerson> monPersonList = taskCompanyPerson.getMonPersonList();
			if (monPersonList != null) {
				fillTaskPerson(monPersonList, examPersonIds, taskRiskControlTechVo, TaskPersonTypeEnum.MONITOR,
						taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(monPersonList);
			}
			List<TaskPerson> disPersonList = taskCompanyPerson.getDisclosurePerson();
			if (disPersonList != null) {
				fillTaskPerson(disPersonList, examPersonIds, taskRiskControlTechVo, TaskPersonTypeEnum.DISCLOSUREPERSON,
						taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(disPersonList);
			}
			List<TaskPerson> consDirectorList = taskCompanyPerson.getConstructionDirector();
			if (consDirectorList != null) {
				fillTaskPerson(consDirectorList, examPersonIds, taskRiskControlTechVo,
						TaskPersonTypeEnum.CONSTRUCTIONDIRECTOR, taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(consDirectorList);
			}
			List<TaskPerson> safeyList = taskCompanyPerson.getSafetyOfficer();
			if (safeyList != null) {
				fillTaskPerson(safeyList, examPersonIds, taskRiskControlTechVo, TaskPersonTypeEnum.SAFETYOFFICER,
						taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(safeyList);
			}
			List<TaskPerson> participateList = taskCompanyPerson.getParticipateDisclosure();
			if (participateList != null) {
				fillTaskPerson(participateList, examPersonIds, taskRiskControlTechVo,
						TaskPersonTypeEnum.PARTICIPATEDISCLOSURE, taskCompanyPerson.getCompanyId());
				taskPersonList.addAll(participateList);
			}
		}

		iTaskPersonService.saveBatch(taskPersonList);

		// 添加附件数据
		List<TaskPersonKnowledgeAttachment> list = new ArrayList<TaskPersonKnowledgeAttachment>();
		taskPersonList.add(taskPerson);
		for (TaskPerson taskPersonNew : taskPersonList) {
//			if (taskPersonNew.getType() != TaskPersonTypeEnum.FBS_TECHNICIAN.getValue()
//					&& taskPersonNew.getType() != TaskPersonTypeEnum.SAFETYOFFICER.getValue()
//					&& taskPersonNew.getType() != TaskPersonTypeEnum.MONITOR.getValue()
//					&& taskPersonNew.getType() != TaskPersonTypeEnum.DISCLOSUREPERSON.getValue()
//					&& taskPersonNew.getType() != TaskPersonTypeEnum.CONSTRUCTIONDIRECTOR.getValue()
//					&& taskPersonNew.getType() != TaskPersonTypeEnum.PARTICIPATEDISCLOSURE.getValue()) {
//				continue;
//			}
			if (taskRiskControlTechVo.getConstructDocumentAttachments() != null) {
				for (TaskPersonKnowledgeAttachment attachment : taskRiskControlTechVo
						.getConstructDocumentAttachments()) {
					TaskPersonKnowledgeAttachment attachmentNew = new TaskPersonKnowledgeAttachment();
					BeanUtils.copyProperties(attachment, attachmentNew);
					attachmentNew.setTaskId(task.getId());
					attachmentNew.setTaskPersonId(taskPersonNew.getId());
					attachmentNew.setKnowledgeId(taskRiskControlTechVo.getConstructDocumentId());
					attachmentNew.setReadStatus(0);
					list.add(attachmentNew);
				}
			}
			if (taskRiskControlTechVo.getConstructDisclosureDocumentAttachments() != null) {
				for (TaskPersonKnowledgeAttachment attachment : taskRiskControlTechVo
						.getConstructDisclosureDocumentAttachments()) {
					TaskPersonKnowledgeAttachment attachmentNew = new TaskPersonKnowledgeAttachment();
					BeanUtils.copyProperties(attachment, attachmentNew);
					attachmentNew.setTaskId(task.getId());
					attachmentNew.setTaskPersonId(taskPersonNew.getId());
					attachmentNew.setKnowledgeId(taskRiskControlTechVo.getConstructDisclosureDocumentId());
					attachmentNew.setReadStatus(0);
					list.add(attachmentNew);
				}
			}
			if (taskRiskControlTechVo.getTechDocumentAttachments() != null) {
				for (TaskPersonKnowledgeAttachment attachment : taskRiskControlTechVo.getTechDocumentAttachments()) {
					TaskPersonKnowledgeAttachment attachmentNew = new TaskPersonKnowledgeAttachment();
					BeanUtils.copyProperties(attachment, attachmentNew);
					attachmentNew.setTaskId(task.getId());
					attachmentNew.setTaskPersonId(taskPersonNew.getId());
					attachmentNew.setKnowledgeId(taskRiskControlTechVo.getTechDocumentId());
					attachmentNew.setReadStatus(0);
					list.add(attachmentNew);
				}
			}
		}
		iTaskPersonKnowledgeAttachmentService.saveBatch(list);

		List<TaskPerson> notices = new ArrayList<TaskPerson>();
		notices.addAll(taskPersonList);
		taskRiskNotice(taskRiskControl, notices);
		return taskRiskControlTechVo;
	}

	private void fillTaskPerson(List<TaskPerson> personList, List<Long> examPersonIds,
			TaskRiskControlTechVo taskRiskControlTechVo, TaskPersonTypeEnum typeEnum, Long companyId) {
		if (personList == null) {
			return;
		}
		for (TaskPerson i : personList) {
			i.setTaskId(taskRiskControlTechVo.getTaskId());
			i.setType(typeEnum.getValue());
			i.setCompanyId(companyId);
			i.setFirstRead(false);
			i.setConstructDocumentId(taskRiskControlTechVo.getConstructDocumentId());
			i.setConstructDocumentStatus(0);
			i.setTechDocumentId(taskRiskControlTechVo.getTechDocumentId());
			i.setTechDocumentStatus(0);
			i.setConstructDisclosureDocumentId(taskRiskControlTechVo.getConstructDisclosureDocumentId());
			i.setConstructDisclosureDocumentStatus(0);
			if (examPersonIds.contains(i.getPersonId())) {
				i.setExamId(taskRiskControlTechVo.getExamId());
				i.setExamTemplateId(taskRiskControlTechVo.getExamTemplateId());
				i.setExamName(taskRiskControlTechVo.getExamTemplateName());
			}
		}
	}

	@Override
	public TaskRiskControlTechVo createTaskByFbs(TaskRiskControlTechVo taskRiskControlTechVo) {
		Person person = iPersonService.getById(taskRiskControlTechVo.getTechPersonId());
		taskRiskControlTechVo.setOrgCode(person.getOrgCode());
		taskRiskControlTechVo.setCreatePersonId(taskRiskControlTechVo.getCreatePersonId());
		this.createTask(taskRiskControlTechVo);
		return taskRiskControlTechVo;
	}

	@Override
	public TaskRiskControlTechVo create(TaskRiskControlTechVo taskRiskControlTechVo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TaskRiskControlTechVo nextStage(TaskRiskControlTechVo taskRiskControlTechVo) {
		TaskRiskControlTech taskRiskControlTech = this.getById(taskRiskControlTechVo.getId());
		int stage = taskRiskControlTech.getStage();
		TaskRiskTechStageEnum nextEnum = TaskRiskTechStageEnum.next(taskRiskControlTech.getStage());
		int nextStage = nextEnum.getValue();
		taskRiskControlTech.setStage(nextStage);
		if (TaskRiskTechStageEnum.SELECT_PERSON_EXAM_KNOWLEDGE.getValue() == stage) {
			List<TaskPersonFile> fileList = taskRiskControlTechVo.getDisclosureList();
			for (TaskPersonFile tpf : fileList) {
				tpf.setPersonId(taskRiskControlTech.getTechPersonId());
				tpf.setPersonType(TaskPersonFileEnum.CREATEPERSONFILE.getValue());
				tpf.setTaskId(taskRiskControlTech.getTaskId());
			}
			iTaskPersonFileService.saveBatch(fileList);
			Task task = iTaskService.getById(taskRiskControlTech.getTaskId());
			task.setStatus(TaskStatusEnum.COMPLETED.getLongType());
			task.setEndTime(new Date());
			iTaskService.updateById(task);
			TaskPerson taskPerson = iTaskPersonService.getOne(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.CREATEPERSON.getValue()));
			taskPerson.setReadStatus(1L);
			iTaskPersonService.updateById(taskPerson);
			taskRiskControlTech.setTaskEndTime(new Date());
		}
		this.updateById(taskRiskControlTech);
		return taskRiskControlTechVo;
	}

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

	@Override
	public TaskRiskControlTechVo doDocument(TaskRiskControlTechVo taskRiskControlTechVo) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskRiskControlTechVo.getTaskPersonId());
		if (taskRiskControlTechVo.getConstructDocumentId() != null) {
			taskPerson.setConstructDocumentStatus(1);
		} else if (taskRiskControlTechVo.getTechDocumentId() != null) {
			taskPerson.setTechDocumentStatus(1);
		} else if (taskRiskControlTechVo.getConstructDisclosureDocumentId() != null) {
			taskPerson.setConstructDisclosureDocumentStatus(1);
		}
		iTaskPersonService.updateById(taskPerson);
		return taskRiskControlTechVo;
	}

	@Override
	public TaskRiskControlTechVo confirm(TaskRiskControlTechVo taskRiskControlTechVo) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskRiskControlTechVo.getTaskperson().getId());
		taskPerson.setReadStatus(1L);
		iTaskPersonService.updateById(taskPerson);
		return taskRiskControlTechVo;
	}

	@Override
	public TaskRiskControlTechVo getDetailById(Long id, Long personId, Long taskPersonId) {
		TaskRiskControlTech taskRiskControlTech = this.getById(id);
		TaskRiskControlTechVo taskRiskControlTechVo = new TaskRiskControlTechVo();
		BeanUtils.copyProperties(taskRiskControlTech, taskRiskControlTechVo);
		Person techPerson = iPersonService.getById(taskRiskControlTechVo.getTechPersonId());
		taskRiskControlTechVo.setTechPersonName(techPerson != null ? techPerson.getName() : null);
		// 项目部人员
		List<TaskPerson> techPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.TECHNICIAN.getValue()));
		taskRiskControlTechVo.setTechPersonList(techPersonList);
		List<TaskPerson> secPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue()));
		taskRiskControlTechVo.setSecPersonList(secPersonList);
		List<TaskPerson> proPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.ENGINEERINGSTAFF.getValue()));
		taskRiskControlTechVo.setProPersonList(proPersonList);
		List<TaskPerson> otherPersonList = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.OTHER.getValue()));
		taskRiskControlTechVo.setOtherPersonList(otherPersonList);

		// 分包商人员
		Long[] worktypes = { TaskPersonTypeEnum.FBS_TECHNICIAN.getValue(), TaskPersonTypeEnum.SAFETYOFFICER.getValue(),
				TaskPersonTypeEnum.MONITOR.getValue(), TaskPersonTypeEnum.DISCLOSUREPERSON.getValue(),
				TaskPersonTypeEnum.CONSTRUCTIONDIRECTOR.getValue(), TaskPersonTypeEnum.SAFETYOFFICER.getValue(),
				TaskPersonTypeEnum.PARTICIPATEDISCLOSURE.getValue() };
		List<TaskPerson> list = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
						.in(TaskPerson::getType, Arrays.asList(worktypes)));
		Set<Long> companyIds = list.stream().map(i -> i.getCompanyId()).collect(Collectors.toSet());
		List<TaskCompanyPerson> companyList = new ArrayList<TaskCompanyPerson>();
		for (Long companyId : companyIds) {
			TaskCompanyPerson taskCompanyPerson = new TaskCompanyPerson();
			taskCompanyPerson.setCompanyId(companyId);
			Company company = iCompanyService.getById(companyId);
			if (TypeKeyEnum.JXDJ.getLongType() == Long.valueOf(company.getTypeKey())) {
				continue;
			}
			taskCompanyPerson.setCompanyName(company != null ? company.getName() : null);
			List<TaskPerson> fbsTechPersonList = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.FBS_TECHNICIAN.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setTechPersonList(fbsTechPersonList);
			List<TaskPerson> fbsSecPersonList = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.SAFETYOFFICER.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setSecPersonList(fbsSecPersonList);
			List<TaskPerson> monPersonList = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.MONITOR.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setMonPersonList(monPersonList);
			List<TaskPerson> disclosurePerson = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.DISCLOSUREPERSON.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setDisclosurePerson(disclosurePerson);
			List<TaskPerson> constructionDirector = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.CONSTRUCTIONDIRECTOR.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setConstructionDirector(constructionDirector);
			List<TaskPerson> safetyOfficer = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.SAFETYOFFICER.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setSafetyOfficer(safetyOfficer);
			List<TaskPerson> participateDisclosure = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.PARTICIPATEDISCLOSURE.getValue())
							.eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setParticipateDisclosure(participateDisclosure);
			List<TaskPerson> examPersonList = iTaskPersonService.list(
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
							.isNotNull(TaskPerson::getExamId).eq(TaskPerson::getCompanyId, companyId));
			taskCompanyPerson.setExamPersonList(examPersonList);
			companyList.add(taskCompanyPerson);
		}
		taskRiskControlTechVo.setCompanyPersonList(companyList);

		// 考试人员
		List<TaskPerson> examList = new ArrayList<TaskPerson>();
		for (TaskPerson TaskPerson : list) {
			if (TaskPerson.getExamId() != null) {
				examList.add(TaskPerson);
			}
		}

		if (examList.size() > 0) {
			// 考试
			TaskPerson taskperson = iTaskPersonService.getById(examList.get(0).getId());
			taskRiskControlTechVo.setExamId(taskperson.getExamId());
			taskRiskControlTechVo.setExamTemplateName(taskperson.getExamName());
			taskRiskControlTechVo.setExamTemplateId(taskperson.getExamTemplateId());
		}

		// 交底图片
		List<TaskPersonFile> fileList = iTaskPersonFileService.list(
				new LambdaQueryWrapper<TaskPersonFile>().eq(TaskPersonFile::getTaskId, taskRiskControlTech.getTaskId())
						.eq(TaskPersonFile::getPersonId, taskRiskControlTech.getTechPersonId())
						.eq(TaskPersonFile::getPersonType, TaskPersonFileEnum.CREATEPERSONFILE.getValue()));
		taskRiskControlTechVo.setDisclosureList(fileList);

		Project project = iProjectService.getById(taskRiskControlTechVo.getProjectId());
		taskRiskControlTechVo.setProjectName(project != null ? project.getName() : null);
		TaskPerson taskPerson = new TaskPerson();
		if (taskPersonId == null) {
			if (personId != null) {
				List<TaskPerson> taskPersons = iTaskPersonService.list(
						new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskRiskControlTech.getTaskId())
								.eq(TaskPerson::getPersonId, personId));
				taskPerson = !taskPersons.isEmpty() ? taskPersons.get(0) : new TaskPerson();
				taskPersonId = taskPerson.getId();
			}
		} else {
			taskPerson = iTaskPersonService.getById(taskPersonId);
		}

		// 查询附件
		List<TaskPersonKnowledgeAttachment> attachs1 = iTaskPersonKnowledgeAttachmentService
				.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
						.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonId)
						.eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
								taskRiskControlTechVo.getConstructDocumentId()));
		attachs1.forEach(i->i.setUrl(fileServerUrl+i.getUrl()));
		taskRiskControlTechVo.setConstructDocumentAttachments(attachs1);
		List<TaskPersonKnowledgeAttachment> attachs2 = iTaskPersonKnowledgeAttachmentService
				.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
						.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonId)
						.eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
								taskRiskControlTechVo.getConstructDisclosureDocumentId()));
		attachs2.forEach(i->i.setUrl(fileServerUrl+i.getUrl()));
		taskRiskControlTechVo.setConstructDisclosureDocumentAttachments(attachs2);
		List<TaskPersonKnowledgeAttachment> attachs3 = iTaskPersonKnowledgeAttachmentService
				.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
						.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonId)
						.eq(TaskPersonKnowledgeAttachment::getKnowledgeId, taskRiskControlTechVo.getTechDocumentId()));
		attachs3.forEach(i->i.setUrl(fileServerUrl+i.getUrl()));
		taskRiskControlTechVo.setTechDocumentAttachments(attachs3);
		

		//如果是项目部员没有状态的
		if(StringUtil.isEmpty(attachs1)&&StringUtil.isEmpty(attachs2)&&StringUtil.isEmpty(attachs3)) 
		{
			List<TaskPersonKnowledgeAttachment> attachs4 = iTaskPersonKnowledgeAttachmentService
					.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
							.eq(TaskPersonKnowledgeAttachment::getTaskId, taskRiskControlTech.getTaskId()));
			if(!StringUtil.isEmpty(attachs4)) 
			{
				Long taskPersonIdNew = attachs4.get(0).getTaskPersonId();
				List<TaskPersonKnowledgeAttachment> attachs5 = iTaskPersonKnowledgeAttachmentService
						.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
								.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonIdNew).eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
										taskRiskControlTechVo.getConstructDocumentId()));
				attachs5.forEach(i->{i.setTaskPersonId(null);i.setUrl(fileServerUrl+i.getUrl());});
				taskRiskControlTechVo.setConstructDocumentAttachments(attachs5);
				List<TaskPersonKnowledgeAttachment> attachs6 = iTaskPersonKnowledgeAttachmentService
						.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
								.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonIdNew).eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
										taskRiskControlTechVo.getConstructDisclosureDocumentId()));
				taskRiskControlTechVo.setConstructDisclosureDocumentAttachments(attachs6);
				attachs6.forEach(i->{i.setTaskPersonId(null);i.setUrl(fileServerUrl+i.getUrl());});
				List<TaskPersonKnowledgeAttachment> attachs7 = iTaskPersonKnowledgeAttachmentService
						.list(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
								.eq(TaskPersonKnowledgeAttachment::getTaskPersonId, taskPersonIdNew).eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
										taskRiskControlTechVo.getTechDocumentId()));
				attachs7.forEach(i->{i.setTaskPersonId(null);i.setUrl(fileServerUrl+i.getUrl());});
				taskRiskControlTechVo.setTechDocumentAttachments(attachs7);
			}
		}
		
		
		taskRiskControlTechVo.setExamPersonList(examList);
		taskRiskControlTechVo.setTaskperson(taskPerson);
		return taskRiskControlTechVo;
	}

	@Override
	public Page<TaskRiskControlTechVo> constructList(CommonPageableDto pageable,
			TaskRiskControlTechDto taskRiskControlTechDto) {
		pageable.setPageNumber(0);
		pageable.setPageSize(Integer.MAX_VALUE);
		taskRiskControlTechDto.setType(TaskRiskControlTechTypeEnum.ONLY_CONSTRUCT.getCode());
		taskRiskControlTechDto.setStage(TaskRiskTechStageEnum.COMPLETED.getValue());
		if (taskRiskControlTechDto.getPersonId() == null) {
			return new Page<TaskRiskControlTechVo>();
		}
		Page<TaskRiskControlTechVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Page<TaskRiskControlTechVo> result = this.baseMapper.constructListByPage(page, taskRiskControlTechDto);
		return result;
	}

	private void taskRiskNotice(TaskRiskControlTech riskControl, TaskPerson taskPerson) {
		List<TaskPerson> personIdList = Lists.newArrayList();
		personIdList.add(taskPerson);
		taskRiskNotice(riskControl, personIdList);
	}

	private void taskRiskNotice(TaskRiskControlTech riskControl, List<TaskPerson> taskPersonList) {
		if (!CollectionUtils.isEmpty(taskPersonList)) {
			JSONArray array = new JSONArray();
			taskPersonList.forEach(i -> {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.RISK_WORK_TECH.getType());
				jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
						MessageSubTypeEnum.RISK_WORK_TECH_TODO.getType());
				jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), i.getPersonId());
				jsonObject.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.RISK_WORK_TECH_TODO.getTip());
				jsonObject.put(MessageAttributeEnum.TASK_ID.getName(), riskControl.getId());
				jsonObject.put(MessageAttributeEnum.PARAM.getName(), riskControl.getStage());
				jsonObject.put(MessageAttributeEnum.TASK_PERSON_ID.getName(), i.getId());
				array.add(jsonObject);
			});

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

	@Override
	public TaskRiskControlTechVo doDocumentAttach(Long taskPersonKnowledgeId) {
		TaskPersonKnowledgeAttachment taskPersonKnowledgeAttachment = iTaskPersonKnowledgeAttachmentService
				.getById(taskPersonKnowledgeId);
		taskPersonKnowledgeAttachment.setReadStatus(1);
		iTaskPersonKnowledgeAttachmentService.updateById(taskPersonKnowledgeAttachment);

		TaskRiskControlTech taskRiskControlTech = this.getOne(new LambdaQueryWrapper<TaskRiskControlTech>()
				.eq(TaskRiskControlTech::getTaskId, taskPersonKnowledgeAttachment.getTaskId()));
		TaskPerson taskPerson = iTaskPersonService.getById(taskPersonKnowledgeAttachment.getTaskPersonId());
		if (taskRiskControlTech.getConstructDocumentId() != null) {
			int count = iTaskPersonKnowledgeAttachmentService
					.count(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
							.eq(TaskPersonKnowledgeAttachment::getTaskPersonId,
									taskPersonKnowledgeAttachment.getTaskPersonId())
							.eq(TaskPersonKnowledgeAttachment::getReadStatus, 0)
							.eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
									taskRiskControlTech.getConstructDocumentId()));
			if (count == 0) {
				taskPerson.setConstructDocumentStatus(1);
			}
		}
		if (taskRiskControlTech.getConstructDisclosureDocumentId() != null) {
			int count = iTaskPersonKnowledgeAttachmentService
					.count(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
							.eq(TaskPersonKnowledgeAttachment::getTaskPersonId,
									taskPersonKnowledgeAttachment.getTaskPersonId())
							.eq(TaskPersonKnowledgeAttachment::getReadStatus, 0)
							.eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
									taskRiskControlTech.getConstructDisclosureDocumentId()));
			if (count == 0) {
				taskPerson.setConstructDisclosureDocumentStatus(1);
			}
		}
		if (taskRiskControlTech.getTechDocumentId() != null) {
			int count = iTaskPersonKnowledgeAttachmentService
					.count(new LambdaQueryWrapper<TaskPersonKnowledgeAttachment>()
							.eq(TaskPersonKnowledgeAttachment::getTaskPersonId,
									taskPersonKnowledgeAttachment.getTaskPersonId())
							.eq(TaskPersonKnowledgeAttachment::getReadStatus, 0)
							.eq(TaskPersonKnowledgeAttachment::getKnowledgeId,
									taskRiskControlTech.getTechDocumentId()));
			if (count == 0) {
				taskPerson.setTechDocumentStatus(1);
			}
		}
		iTaskPersonService.updateById(taskPerson);
		return new TaskRiskControlTechVo();
	}
}
