package com.zcloud.service.inspection.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.inspection.SafetyEnvironmentalMapper;
import com.zcloud.mapper.datasource.system.UsersMapper;
import com.zcloud.service.bus.*;
import com.zcloud.service.hidden.HiddenService;
import com.zcloud.service.inspection.*;
import com.zcloud.service.notice.NoticeCorpService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.ImgFilesService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Tools;
import com.zcloud.util.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 说明：安全环保检查
 * 作者：luoxiaobao
 * 时间：2022-06-08
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class SafetyEnvironmentalServiceImpl implements SafetyEnvironmentalService {

	@Resource
	private SafetyEnvironmentalMapper safetyenvironmentalMapper;
	@Lazy
	@Autowired
	private SafetyEnvironmentalInspectorService safetyenvironmentalinspectorService;
	@Lazy
	@Autowired
	private SafetyEnvironmentalSituationService safetyenvironmentalsituationService;
	@Lazy
	@Autowired
	private SafetyEnvironmentalExplainService safetyEnvironmentalExplainService;
	@Autowired
	private HiddenService hiddenService;
	@Autowired
	private HiddenUserService hiddenUserService; // 隐患相关人员信息
	@Autowired
	private ImgFilesService imgFilesService;
	@Autowired
	private SafetyEnvironmentalLogService safetyenvironmentallogService;

	@Autowired
	private HiddenExamineService hiddenExamineService;
	@Autowired
	private DepartmentService departmentService;

	@Resource
	private UsersMapper usersMapper;

	@Resource
	private NoticeCorpUtil noticeCorpUtil;

	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> save(PageData pd)throws Exception{
		List<PageData> hiddenList = new ArrayList<PageData>();
		String currentTime = DateUtil.date2Str(new Date());
		if (Tools.notEmpty(pd.getString("SITUATIONJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("SITUATIONJSON"));
			String time = currentTime;
			for (JSONObject json : list) {
				PageData situationPd = new PageData();
				situationPd.put("INSPECTION_SITUATION_ID", UuidUtil.get32UUID());    //主键
				situationPd.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //检查ID
				situationPd.put("SITUATION", json.get("SITUATION"));    //检查情况
				situationPd.put("ISDELETE", "0");    //是否删除(0:有效 1：删除)
				situationPd.put("CREATOR", pd.getString("CREATOR"));    //添加人
				situationPd.put("CREATTIME", time);    //添加时间
				situationPd.put("OPERATOR", pd.getString("OPERATOR"));    //修改人
				situationPd.put("OPERATTIME", time);    //修改时间
				situationPd.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));    //企业ID
				safetyenvironmentalsituationService.save(situationPd);
				time = DateUtil.calculateDateSecond(time, 1);
			}
		}
		if (Tools.notEmpty(pd.getString("INSPECTORJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("INSPECTORJSON"));
			String time = currentTime;
			for (int i = 0; i < list.size(); i++) {
				JSONObject json = list.get(i);
				if (i == 0) {
					pd.put("INSPECTION_LEADDEPARTMENT_ID", json.getString("INSPECTION_DEPARTMENT_ID"));
				}
				PageData inspector = new PageData();
				inspector.put("INSPECTION_INSPECTOR_ID", UuidUtil.get32UUID());	//主键
				inspector.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));	//检查ID
				inspector.put("INSPECTION_USER_ID", json.get("INSPECTION_USER_ID"));	//检查人
				inspector.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
				inspector.put("CREATOR", pd.getString("CREATOR"));	//添加人
				inspector.put("CREATTIME", time);	//添加时间
				inspector.put("OPERATOR", pd.getString("OPERATOR"));	//修改人
				inspector.put("OPERATTIME", time);	//修改时间
				inspector.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));	//企业ID
				boolean note_flag = true;
				if(StringUtils.isNotBlank(pd.getString("OPERATOR"))){
					if (pd.getString("OPERATOR").equals(json.get("INSPECTION_USER_ID"))){
						if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE"))){
							inspector.put("INSPECTION_USER_OPINION",pd.getString("CONFIRM_MESSAGE"));
							inspector.put("INSPECTION_USER_SIGN_IMG",pd.getString("CONFIRM_MESSAGE_SIGN_ROUTE"));
							inspector.put("INSPECTION_USER_SIGN_TIME",pd.getString("CONFIRM_MESSAGE_TIME"));
							// 若，检查人只有一人，且已签字。将此条安全环保检查记录状态设置为‘2’
							if (list.size() == 1){
								pd.put("INSPECTION_STATUS",2);
//								note_flag = false;
							}
						}
					}
				}
				safetyenvironmentalinspectorService.save(inspector);
				if (note_flag) noticeCorpUtil.SE_OneStepUtil(inspector);
				time = DateUtil.calculateDateSecond(time, 1);
			}
		}
		if (Tools.notEmpty(pd.getString("HIDDENJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("HIDDENJSON"));
			String time = currentTime;
			for (JSONObject json : list) {
				PageData hidden = new PageData();
				String hiddentype = json.getString("HIDDENTYPE");
				List<String> lists = JSON.parseArray(hiddentype, String.class);//隐患级别
				if (lists.size() == 1){
					hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
				}
				if (lists.size() == 2){
					hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
					hidden.put("HIDDENTYPE2", lists.get(1));    //隐患类型2
				}
				if (lists.size() == 3){
					hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
					hidden.put("HIDDENTYPE2", lists.get(1));    //隐患类型2
					hidden.put("HIDDENTYPE3", lists.get(2));    //隐患类型3
				}
				hidden.put("HIDDEN_ID", UuidUtil.get32UUID());    //主键
				hidden.put("FOREIGN_ID", pd.getString("INSPECTION_ID"));    //外键ID
				hidden.put("HIDDENDESCR", json.getString("HIDDENDESCR"));    //隐患描述
				hidden.put("HIDDENPART", json.getString("HIDDENPART"));    //隐患部位
				hidden.put("HIDDENLEVEL", json.getString("HIDDENLEVEL"));    //隐患级别
				hidden.put("HIDDENTYPE_NAME", StringUtils.isNotBlank(json.getString("HIDDENTYPENAME")) ? json.getString("HIDDENTYPENAME") : json.getString("HIDDENTYPE_NAME"));//隐患类型名称
				hidden.put("LONGITUDE", json.getString("LONGITUDE"));    //隐患位置经度
				hidden.put("LATITUDE", json.getString("LATITUDE"));    //隐患位置纬度
				hidden.put("DISCOVERYTIME", json.getString("DISCOVERYTIME"));    //隐患发现时间
				hidden.put("CREATOR", json.getString("CREATOR"));    //发现人（隐患责任人）
				PageData user = new PageData();
				user.put("USER_ID",json.getString("CREATOR"));
				user =  usersMapper.findById(user);
				if (user != null) {
					hidden.put("HIDDENFINDDEPT", user.getString("DEPARTMENT_ID"));    //隐患发现部门（隐患责任人部门）
				}
				hidden.put("SOURCE", json.getString("SOURCE"));    //发现人（隐患责任人）
				hidden.put("ISRELEVANT",json.getString("ISRELEVANT"));//是否相关方1是2否
				hidden.put("STATE", "100");    //隐患状态 100-安全环保检查暂存的隐患（流程完转0）
				hidden.put("CREATTIME", time);    //发现时间
				hidden.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
				hidden.put("RECTIFICATIONTYPE", "2");
				hidden.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
				hidden.put("POSITIONDESC",json.getString("POSITIONDESC"));
				hiddenService.save(hidden);
				PageData before = new PageData();// 添加隐患初始信息
				before.put("TYPE","0");
				before.put("STATE","2");
				before.put("HIDDEN_ID",hidden.getString("HIDDEN_ID"));
				before.put("spare1",json.getString("HIDDENLEVEL"));
				before.put("CREATOR", json.getString("CREATOR"));
				before.put("OPERATOR",json.getString("CREATOR"));
				hiddenExamineService.saveApp(before);


				PageData findUser = new PageData();
				findUser.put("HIDDENUSER_ID",  UuidUtil.get32UUID());
				findUser.put("HIDDEN_ID",hidden.getString("HIDDEN_ID"));
				findUser.put("USER_ID",json.getString("CREATOR"));
				findUser.put("TYPE","1");
				findUser.put("IS_MAIN","0");
				hiddenUserService.save(findUser);
				hiddenList.add(hidden);
				time = DateUtil.calculateDateSecond(time, 1);
			}
		}

		PageData log = new PageData();
		log.put("INSPECTION_LOG_ID", UuidUtil.get32UUID());    //安全环保检查操作记录ID
		log.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //安全环保检查ID
		log.put("ACTION", "安全环保检查申请");    //操作内容
		log.put("CREATTIME", pd.getString("CREATTIME"));	//添加时间
		log.put("CREATOR", pd.getString("ACTION_USER"));	//添加人姓名
		safetyenvironmentallogService.save(log);

		safetyenvironmentalMapper.save(pd);
		return hiddenList;
	}

	@Override
	public List<PageData> getHiddenCountByDepat(PageData pd) throws Exception {
		return safetyenvironmentalMapper.getHiddenCountByDepat(pd);
	}

	@Override
	public List<PageData> getHiddenCountByUser(PageData pd) throws Exception {
		return safetyenvironmentalMapper.getHiddenCountByUser(pd);
	}

	/**删除
	 * @param pd
	 * @throws Exception
	 */
	@Transactional
	public void delete(PageData pd)throws Exception{
		safetyenvironmentalMapper.delete(pd);
		safetyenvironmentalsituationService.deleteByInspection(pd);
		safetyenvironmentalinspectorService.deleteByInspection(pd);
		safetyEnvironmentalExplainService.deleteByInspection(pd);
		if (StringUtils.isNotBlank(pd.getString("hide")) && "1".equals(pd.getString("hide"))){
			PageData key = new PageData();
			key.put("FOREIGN_ID",pd.getString("INSPECTION_ID"));
			key.put("SOURCE","5");
			hiddenService.deleteByKey(key);
		}
	}
	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void edieditsttust(PageData pd)throws Exception{
		safetyenvironmentalMapper.edieditsttust(pd); //执行考评方法时，将检查状态改成已归档，因为bug6535提出，要是隐患考评完毕，状态应该是8已归档
	}
	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> edit(PageData pd)throws Exception{
		List<PageData> hiddenList = new ArrayList<PageData>();
		String currentTime = DateUtil.date2Str(new Date());
		String inspectorsStr = pd.getString("delInspectors");
		if (inspectorsStr != null && !inspectorsStr.isEmpty()) {
			String[] delInspectors = inspectorsStr.split(",");
			if (delInspectors.length > 0) {
				PageData delArr = new PageData();
				delArr.put("ArrayDATA_IDS", delInspectors); // 待删除的ID数组
				delArr.put("OPERATOR", pd.getString("OPERATOR")); // 操作人
				delArr.put("OPERATTIME", DateUtil.date2Str(new Date())); // 操作时间
				safetyenvironmentalinspectorService.deleteAll(delArr); // 删除操作
			}
		}
		if (Tools.notEmpty(pd.getString("INSPECTORJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("INSPECTORJSON"));
			String time = currentTime;
			for (int i = 0; i < list.size(); i++) {
				JSONObject json = list.get(i);
				if (i == 0) {
					pd.put("INSPECTION_LEADDEPARTMENT_ID", json.getString("INSPECTION_DEPARTMENT_ID"));
				}
				PageData inspector = new PageData();
				if(StringUtils.isNotBlank(pd.getString("OPERATOR"))){
					if (pd.getString("OPERATOR").equals(json.get("INSPECTION_USER_ID"))){
						if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE"))){
							inspector.put("INSPECTION_USER_OPINION",pd.getString("CONFIRM_MESSAGE"));
							inspector.put("INSPECTION_USER_SIGN_IMG",pd.getString("CONFIRM_MESSAGE_SIGN_ROUTE"));
							inspector.put("INSPECTION_USER_SIGN_TIME",pd.getString("CONFIRM_MESSAGE_TIME"));
						}
					}
				}
				if (Tools.isEmpty(json.getString("INSPECTION_INSPECTOR_ID"))) {
					inspector.put("INSPECTION_INSPECTOR_ID", UuidUtil.get32UUID());	//主键
					inspector.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));	//检查ID
					inspector.put("INSPECTION_USER_ID", json.get("INSPECTION_USER_ID"));	//检查人
					inspector.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
					inspector.put("CREATOR", pd.getString("CREATOR"));	//添加人
					inspector.put("CREATTIME", time);	//添加时间
					inspector.put("OPERATOR", pd.getString("OPERATOR"));	//修改人
					inspector.put("OPERATTIME", time);	//修改时间
					inspector.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));	//企业ID
					boolean note_flag = true;
					if(StringUtils.isNotBlank(pd.getString("OPERATOR"))){
						if (pd.getString("OPERATOR").equals(json.get("INSPECTION_USER_ID"))){
							if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE"))){
								inspector.put("INSPECTION_USER_OPINION",pd.getString("CONFIRM_MESSAGE"));
								inspector.put("INSPECTION_USER_SIGN_IMG",pd.getString("CONFIRM_MESSAGE_SIGN_ROUTE"));
								inspector.put("INSPECTION_USER_SIGN_TIME",pd.getString("CONFIRM_MESSAGE_TIME"));
								// 若，检查人只有一人，且已签字。将此条安全环保检查记录状态设置为‘2’
								if (list.size() == 1){
									pd.put("INSPECTION_STATUS",2);
									note_flag = false;
								}
							}
						}
					}
					safetyenvironmentalinspectorService.save(inspector);
					if (note_flag) noticeCorpUtil.SE_OneStepUtil(inspector);
					time = DateUtil.calculateDateSecond(time, 1);
				} else {
					inspector.put("INSPECTION_INSPECTOR_ID", json.getString("INSPECTION_INSPECTOR_ID"));	//主键
					inspector.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));	//检查ID
					inspector.put("INSPECTION_USER_ID", json.getString("INSPECTION_USER_ID"));	//检查人
					inspector.put("OPERATOR", pd.getString("OPERATOR"));	//修改人
					inspector.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
					boolean note_flag = true;
					if(StringUtils.isNotBlank(pd.getString("OPERATOR"))){
						if (pd.getString("OPERATOR").equals(json.get("INSPECTION_USER_ID"))){
							if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE"))){
								inspector.put("INSPECTION_USER_OPINION",pd.getString("CONFIRM_MESSAGE"));
								inspector.put("INSPECTION_USER_SIGN_IMG",pd.getString("CONFIRM_MESSAGE_SIGN_ROUTE"));
								inspector.put("INSPECTION_USER_SIGN_TIME",pd.getString("CONFIRM_MESSAGE_TIME"));
								// 若，检查人只有一人，且已签字。将此条安全环保检查记录状态设置为‘2’
								if (list.size() == 1){
									pd.put("INSPECTION_STATUS",2);
									note_flag = false;
								}
							}
						}
					}
					safetyenvironmentalinspectorService.edit(inspector);
					PageData inspector_information = safetyenvironmentalinspectorService.findById(inspector);
					if (note_flag) noticeCorpUtil.SE_OneStepUtil(inspector_information);
				}
			}
		}
		String situationsStr = pd.getString("delSituations");
		if (situationsStr != null && !situationsStr.isEmpty()) {
			String[] delSituations = situationsStr.split(",");
			// 检查是否有待删除的ID
			if (delSituations.length > 0) {
				PageData delArr = new PageData();
				delArr.put("ArrayDATA_IDS", delSituations); // 待删除的ID数组
				delArr.put("OPERATOR", pd.getString("OPERATOR")); // 操作人
				delArr.put("OPERATTIME", DateUtil.date2Str(new Date())); // 操作时间
				safetyenvironmentalsituationService.deleteAll(delArr); // 执行删除操作
			}
		}
		if (Tools.notEmpty(pd.getString("SITUATIONJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("SITUATIONJSON"));
			String time = currentTime;
			for (JSONObject json : list) {
				PageData situationPd = new PageData();
				if (Tools.isEmpty(json.getString("INSPECTION_SITUATION_ID"))) {
					situationPd.put("INSPECTION_SITUATION_ID", UuidUtil.get32UUID());    //主键
					situationPd.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //检查ID
					situationPd.put("SITUATION", json.get("SITUATION"));    //检查情况
					situationPd.put("ISDELETE", "0");    //是否删除(0:有效 1：删除)
					situationPd.put("CREATOR", pd.getString("CREATOR"));    //添加人
					situationPd.put("CREATTIME", time);    //添加时间
					situationPd.put("OPERATOR", pd.getString("OPERATOR"));    //修改人
					situationPd.put("OPERATTIME", time);    //修改时间
					situationPd.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));    //企业ID
					safetyenvironmentalsituationService.save(situationPd);
					time = DateUtil.calculateDateSecond(time, 1);
				} else {
					situationPd.put("INSPECTION_SITUATION_ID", json.getString("INSPECTION_SITUATION_ID"));    //主键
					situationPd.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //检查ID
					situationPd.put("SITUATION", json.getString("SITUATION"));    //检查情况
					situationPd.put("OPERATOR", pd.getString("OPERATOR"));    //修改人
					situationPd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
					safetyenvironmentalsituationService.edit(situationPd);
				}
			}
		}
		String hiddensStr = pd.getString("delHiddens");
		if (hiddensStr != null && !hiddensStr.isEmpty()) {
			String[] delHiddens = hiddensStr.split(",");
			// 检查是否有待删除的ID
			if (delHiddens.length > 0) {
				PageData delArr = new PageData();
				delArr.put("ArrayDATA_IDS", delHiddens); // 待删除的ID数组
				delArr.put("OPERATOR", pd.getString("OPERATOR")); // 操作人
				delArr.put("OPERATTIME", DateUtil.date2Str(new Date())); // 操作时间
				imgFilesService.deleteInspectionHiddenFile(delArr); // 删除隐藏文件
				hiddenService.deleteArray(delArr); // 删除隐藏记录
			}
		}
		if (Tools.notEmpty(pd.getString("HIDDENJSON"))) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.getString("HIDDENJSON"));
			String time = currentTime;
			for (JSONObject json : list) {
				PageData hidden = new PageData();
				if (Tools.isEmpty(json.getString("HIDDEN_ID"))) {
					hidden.put("HIDDEN_ID", UuidUtil.get32UUID());    //主键
					hidden.put("FOREIGN_ID", pd.getString("INSPECTION_ID"));    //外键ID
					hidden.put("HIDDENDESCR", json.getString("HIDDENDESCR"));    //隐患描述
					hidden.put("HIDDENPART", json.getString("HIDDENPART"));    //隐患部位
					hidden.put("HIDDENLEVEL", json.getString("HIDDENLEVEL"));    //隐患级别
					String hiddentype = json.getString("HIDDENTYPE");
					List<String> lists = JSON.parseArray(hiddentype, String.class);//隐患级别
					if (lists.size() == 1){
						hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
					}
					if (lists.size() == 2){
						hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
						hidden.put("HIDDENTYPE2", lists.get(1));    //隐患类型2
					}
					if (lists.size() == 3){
						hidden.put("HIDDENTYPE1",lists.get(0) );    //隐患类型1
						hidden.put("HIDDENTYPE2", lists.get(1));    //隐患类型2
						hidden.put("HIDDENTYPE3", lists.get(2));    //隐患类型3
					}
					hidden.put("HIDDENTYPE_NAME", StringUtils.isNotBlank(json.getString("HIDDENTYPENAME")) ? json.getString("HIDDENTYPENAME") : json.getString("HIDDENTYPE_NAME"));//隐患类型名称
					hidden.put("LONGITUDE", json.getString("LONGITUDE"));    //隐患位置经度
					hidden.put("LATITUDE", json.getString("LATITUDE"));    //隐患位置纬度
					hidden.put("DISCOVERYTIME", json.getString("DISCOVERYTIME"));    //隐患发现时间
//					hidden.put("HIDDENFINDDEPT", json.getString("HIDDENFINDDEPT"));    //隐患发现部门（隐患责任人部门）
					hidden.put("CREATOR", json.getString("CREATOR"));    //发现人（隐患责任人）
					PageData user = new PageData();
					user.put("USER_ID",json.getString("CREATOR"));
					user =  usersMapper.findById(user);
					if (user != null) {
						hidden.put("HIDDENFINDDEPT", user.getString("DEPARTMENT_ID"));    //隐患发现部门（隐患责任人部门）
					}
					hidden.put("SOURCE", json.getString("SOURCE"));    //发现人（隐患责任人）
					hidden.put("STATE", "100");    //隐患状态 100-安全环保检查暂存的隐患（流程完转0）
					hidden.put("CREATTIME", time);    //发现时间
					hidden.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));
					hidden.put("RECTIFICATIONTYPE", "2");
					hidden.put("ISDELETE", "0");    //是否删除(0:有效 1：删除)
					hidden.put("POSITIONDESC",json.getString("POSITIONDESC"));
					hidden.put("ISRELEVANT",json.getString("ISRELEVANT"));
					hiddenService.save(hidden);
					time = DateUtil.calculateDateSecond(time, 1);
				} else {
					hidden.put("HIDDEN_ID", json.getString("HIDDEN_ID"));    //主键
					hidden.put("FOREIGN_ID", pd.getString("INSPECTION_ID"));    //外键ID
					hidden.put("HIDDENDESCR", json.getString("HIDDENDESCR"));    //隐患描述
					hidden.put("HIDDENPART", json.getString("HIDDENPART"));    //隐患部位
					hidden.put("HIDDENLEVEL", json.getString("HIDDENLEVEL"));    //隐患级别
					hidden.put("HIDDENTYPE", json.getString("HIDDENTYPE"));    //隐患类型1
					hidden.put("HIDDENTYPE2", json.getString("HIDDENTYPE2"));    //隐患类型2
					hidden.put("LONGITUDE", json.getString("LONGITUDE"));    //隐患位置经度
					hidden.put("LATITUDE", json.getString("LATITUDE"));    //隐患位置纬度
					hidden.put("DISCOVERYTIME", json.getString("DISCOVERYTIME"));    //隐患发现时间
					hidden.put("HIDDENFINDDEPT", json.getString("HIDDENFINDDEPT"));    //隐患发现部门（隐患责任人部门）
					hidden.put("CREATOR", json.getString("CREATOR"));    //发现人（隐患责任人）
					hidden.put("SOURCE", json.getString("SOURCE"));    //发现人（隐患责任人）
					hidden.put("STATE", "100");    //隐患状态 100-安全环保检查暂存的隐患（流程完转0）
					hidden.put("ISDELETE", "0");    //是否删除(0:有效 1：删除)
					hidden.put("POSITIONDESC",json.getString("POSITIONDESC"));
					hidden.put("ISRELEVANT",json.getString("ISRELEVANT"));
					hiddenService.editInfo(hidden);

					PageData del = new PageData();
					del.put("TYPE","1");
					del.put("HIDDEN_ID",hidden.getString("HIDDEN_ID"));
					hiddenUserService.deleteByHidden(del); // 先删除后添加
				}

				PageData findUser = new PageData();
				findUser.put("HIDDENUSER_ID",  UuidUtil.get32UUID());
				findUser.put("HIDDEN_ID",hidden.getString("HIDDEN_ID"));
				findUser.put("USER_ID",json.getString("CREATOR"));
				findUser.put("TYPE","1");
				findUser.put("IS_MAIN","0");
				hiddenUserService.save(findUser);
				hiddenList.add(hidden);
			}
		}

		String delHiddenStr = pd.getString("delHiddenFiles");
		if (delHiddenStr != null && !hiddensStr.isEmpty()){
			String[] delHiddens = delHiddenStr.split(",");

			for (String delHidden : delHiddens) {
				if (delHidden != null && !delHidden.isEmpty()){
					PageData delFile = new PageData();
					delFile.put("FILEPATH", delHidden);
					imgFilesService.deleteByPath(delFile);
				}
			}
		}

//		String[] delHiddenFiles = "".equals(pd.getString("delHiddenFiles")) ? new String[0] : pd.getString("delHiddenFiles").split(",");
//		for (String delHiddenFile : delHiddenFiles) {
//			PageData delFile = new PageData();
//			delFile.put("FILEPATH", delHiddenFile);    //路径
//			imgFilesService.deleteByPath(delFile);
//		}


		PageData log = new PageData();
		log.put("INSPECTION_LOG_ID", UuidUtil.get32UUID());    //安全环保检查操作记录ID
		log.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //安全环保检查ID
		log.put("ACTION", "安全环保检查重新申请");    //操作内容
		log.put("CREATTIME", pd.getString("CREATTIME"));	//添加时间
		log.put("CREATOR", pd.getString("ACTION_USER"));	//添加人姓名
		safetyenvironmentallogService.save(log);
		// 编辑的时候自动清空附件
		if (!"1".equals(pd.getString("unClear"))){
			pd.put("INSPECTED_EXPLAIN_FILENAME",null);
			pd.put("INSPECTED_EXPLAIN_FILEPATH",null);
		}
		// 安全环保检查申辩记录没用存对应关系，所以做如下处理
		try {
			if (StringUtils.isNotBlank(pd.getString("unClear"))) {
				PageData explain_condition = new PageData();
				explain_condition.put("INSPECTION_EXPLAIN_ID", pd.getString("explainId"));
				explain_condition.put("INSPECTION_ID",pd.getString("INSPECTION_ID"));
				safetyEnvironmentalExplainService.killAllMessage(explain_condition);

			} else {
				PageData explain_condition = new PageData();
				explain_condition.put("INSPECTION_ID",pd.getString("INSPECTION_ID"));
				PageData explain =  safetyEnvironmentalExplainService.findMessage(explain_condition);
				if (explain == null || explain.size() <= 0){
					explain = safetyEnvironmentalExplainService.findMessageByTime(explain_condition);
					if (explain != null || explain.size() >= 0 || "1".equals(explain.getString("VALID"))){
						explain.put("OPERATTIME", DateUtil.date2Str(new Date()));
						explain.put("ISPASS","1");
						explain.put("VALID","0");
						safetyEnvironmentalExplainService.edit(explain);
					}
				}else {
					explain.put("OPERATTIME", DateUtil.date2Str(new Date()));
					explain.put("ISPASS","1");
					explain.put("VALID","0");
					safetyEnvironmentalExplainService.edit(explain);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		safetyenvironmentalMapper.edit(pd);
		return hiddenList;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> list(Page page)throws Exception{
		return safetyenvironmentalMapper.datalistPage(page);
	}

	/**列表(全部)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> listAll(PageData pd)throws Exception{
		return safetyenvironmentalMapper.listAll(pd);
	}

	/**列表(全部)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> findByyin(PageData pd)throws Exception{
		return safetyenvironmentalMapper.findByyin(pd);
	}

	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findById(PageData pd)throws Exception{
		return safetyenvironmentalMapper.findById(pd);
	}

	@Override
	public PageData findShowById(PageData pd) throws Exception {
		PageData data = safetyenvironmentalMapper.findById(pd);
		data.put("situationList", safetyenvironmentalsituationService.listAll(pd));
		pd.put("FOREIGN_ID",pd.getString("INSPECTION_ID"));
		data.put("hiddenList", hiddenService.listAllInspection(pd));
		pd.put("ISVERIFY",'1'); 	//查询已核实的数据
		data.put("inspectorList", safetyenvironmentalinspectorService.listAll(pd));
		return data;
	}

	@Override
	public PageData findFormById(PageData pd) throws Exception {
		PageData data = safetyenvironmentalMapper.findById(pd);
		List<PageData> INSPECTORList = safetyenvironmentalinspectorService.listAll(pd);
		List<PageData> inspectorList = new ArrayList<>();
		for (PageData bean : INSPECTORList) {
			PageData u = new PageData();
			u.put("INSPECTION_INSPECTOR_ID", bean.getString("INSPECTION_INSPECTOR_ID"));
			u.put("INSPECTION_DEPARTMENT_ID",bean.getString("INSPECTION_DEPARTMENT_ID"));
			u.put("INSPECTION_DEPARTMENT_NAME",bean.getString("INSPECTION_DEPARTMENT_NAME"));
			u.put("INSPECTION_USER_ID",bean.getString("INSPECTION_USER_ID"));
			u.put("INSPECTION_USER_NAME",bean.getString("INSPECTION_USER_NAME"));
			u.put("img",bean.getString("INSPECTION_USER_SIGN_IMG"));
			u.put("opinion",bean.getString("INSPECTION_USER_OPINION"));
			u.put("time",bean.getString("INSPECTION_USER_SIGN_TIME"));
			inspectorList.add(u);
		}
		data.put("inspectorList", inspectorList);

		List<PageData> SITUATIONList = safetyenvironmentalsituationService.listAll(pd);
		List<PageData> situationList = new ArrayList<>();
		for (PageData bean : SITUATIONList) {
			PageData u = new PageData();
			u.put("INSPECTION_SITUATION_ID", bean.getString("INSPECTION_SITUATION_ID"));
			u.put("SITUATION",bean.getString("SITUATION"));
			situationList.add(u);
		}
		data.put("situationList", situationList);
		pd.put("FOREIGN_ID",pd.getString("INSPECTION_ID"));
		data.put("hiddenList", hiddenService.listAllInspection(pd));
		pd.put("ISVERIFY",'1'); 	//查询已核实的数据
		data.put("inspectorVerifyList", safetyenvironmentalinspectorService.listAll(pd));
		return data;
	}

	/**批量删除
	 * @param pd
	 * @throws Exception
	 */
	public void deleteAll(PageData pd)throws Exception{
		safetyenvironmentalMapper.deleteAll(pd);
	}

	/**列表(根据所选ID获取数据)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> findByIds(PageData pd) throws Exception {
		return safetyenvironmentalMapper.findByIds(pd);
	}

	@Override
	public void editStatus(PageData pd) throws Exception {
		safetyenvironmentalMapper.editStatus(pd);
	}

	@Override
	public void explain(PageData pd) throws Exception {
		PageData data = safetyenvironmentalMapper.findById(pd);
		pd.put("STATE", "101"); // 101.检查已归档，待指派
		pd.put("INSPECTION_SOURCE",data.getString("INSPECTION_SOURCE"));
		hiddenService.editStateInspection(pd);

		data.put("INSPECTION_STATUS",pd.getString("INSPECTION_STATUS"));
		data.put("INSPECTED_EXPLAIN_REFUSE",pd.getString("INSPECTED_EXPLAIN_REFUSE"));
		data.put("INSPECTION_ORIGINATOR_SIGN_IMG",pd.getString("INSPECTION_ORIGINATOR_SIGN_IMG"));
		data.put("INSPECTION_ORIGINATOR_SIGN_TIME", DateUtil.date2Str(new Date()));	//签字时间
		data.put("OPERATOR", pd.getString("OPERATOR"));	//修改人
		data.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		safetyenvironmentalMapper.edit(data);

		PageData log = new PageData();
		log.put("INSPECTION_LOG_ID", UuidUtil.get32UUID());    //安全环保检查操作记录ID
		log.put("INSPECTION_ID", pd.getString("INSPECTION_ID"));    //安全环保检查ID
		log.put("ACTION", "安全环保检查申辩处理");    //操作内容
		log.put("CREATTIME", pd.getString("CREATTIME"));	//添加时间
		log.put("CREATOR", pd.getString("ACTION_USER"));	//添加人姓名
		safetyenvironmentallogService.save(log);

		PageData condition = new PageData();
		condition.put("INSPECTION_ID",data.getString("INSPECTION_ID"));
		PageData explain =  safetyEnvironmentalExplainService.findMessage(condition);
		if (explain == null || explain.size() <= 0){
			explain = safetyEnvironmentalExplainService.findMessageByTime(condition);
		}
		if (explain != null || explain.size() > 0){
			explain.put("VALID","0");
			explain.put("ISPASS","2");
			explain.put("OPERATTIME",DateUtil.date2Str(new Date()));
			safetyEnvironmentalExplainService.edit(explain);
		}
	}

	@Override
	public PageData statisticsBranch(PageData pd) throws Exception {
		return safetyenvironmentalMapper.statisticsBranch(pd);
	}

	@Override
	public List<PageData> statisticsJointStock(PageData pd) throws Exception {
		return safetyenvironmentalMapper.statisticsJointStock(pd);
	}

	/**被检查人签字/申辩数
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public PageData checkedCount(PageData pd) throws Exception {
		return safetyenvironmentalMapper.checkedCount(pd);
	}

	/**打回数
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public PageData repulseCount(PageData pd) throws Exception {
		return safetyenvironmentalMapper.repulseCount(pd);
	}

	/**指派+验收数
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public PageData repulseAndCheckCountCount(PageData pd) throws Exception {
		return safetyenvironmentalMapper.repulseAndCheckCountCount(pd);
	}

	@Override
	public List<PageData> pleadList(Page page) throws Exception {
		return safetyenvironmentalMapper.pleadlistPage(page);
	}

	@Override
	public List<PageData> checkList(Page page) {
		return safetyenvironmentalMapper.checklistPage(page);
	}

	@Override


	public PageData departmentUtil(PageData data) throws Exception {
		PageData condition = new PageData();
		condition.put("DEPARTMENT_ID",data.getString("INSPECTED_DEPARTMENT_ID"));
		List<PageData> parent_list = departmentService.getGenealogy(condition);
		if (parent_list != null && parent_list.size() > 0) {
			String corp_infos = parent_list.stream().map(n -> n.getString("NAME")).collect(Collectors.joining("-"));
			data.put("INSPECTED_DEPARTMENT_NAMES", corp_infos);
		}else{
			data.put("INSPECTED_DEPARTMENT_NAMES", "");
		}
		return data;
	}
	/**
	 *  获取所有的安全环保信息
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<PageData> statisticsBranchGroupDept(PageData pd) throws Exception{
		return safetyenvironmentalMapper.statisticsBranchGroupDept(pd);
	}

	@Override
	public String getHiddenTotal(Page page) {
		// return safetyenvironmentalMapper.datalistPage(page);
		return safetyenvironmentalMapper.getHiddenTotal(page);
	}
	/**指派+验收数
	 * @param pd
	 * @throws Exception
	 */
	@Override
	public PageData repulseAndCheckCountCountV2(PageData pd) throws Exception {
		return safetyenvironmentalMapper.repulseAndCheckCountCountV2(pd);
	}

}

