package com.zcloud.service.hidden.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.HiddenExcel;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.mapper.datasource.bus.HiddenExamineMapper;
import com.zcloud.mapper.datasource.hidden.HiddenCheckMapper;
import com.zcloud.mapper.datasource.hidden.HiddenMapper;
import com.zcloud.mapper.datasource.hidden.HiddenSchemeMapper;
import com.zcloud.service.bus.HiddenRegionService;
import com.zcloud.service.hidden.HiddenService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.service.system.ImgFilesService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 说明：隐患
 * 作者：luoxiaobao
 * 时间：2021-01-04
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class HiddenServiceImpl implements HiddenService {

	@Resource
	private HiddenMapper hiddenMapper;
	@Resource
	private DictionariesService dictionariesService;
	@Resource
	private UsersService usersService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private HiddenSchemeMapper hiddenSchemeMapper;
	@Resource
	private HiddenCheckMapper hiddenCheckMapper;
	@Resource
	private ImgFilesService imgFilesService;
	@Resource
	private HiddenExamineMapper hiddenexamineMapper;
	@Autowired
	private HiddenRegionService hiddenRegionService; // 隐患区域维护

	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public void save(PageData pd)throws Exception{
		hiddenMapper.save(pd);
	}

	/**删除
	 * @param pd
	 * @throws Exception
	 */
	public void delete(PageData pd)throws Exception{
		hiddenMapper.delete(pd);
	}

	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void edit(PageData pd)throws Exception{
		hiddenMapper.edit(pd);
	}

	/**修改信息
	 * @param pd
	 * @throws Exception
	 */
	public void editInfo(PageData pd)throws Exception{
		hiddenMapper.editInfo(pd);
	}
	public void editISCONFIRM(PageData pd)throws Exception{
		hiddenMapper.editISCONFIRM(pd);
	}
	public void editHIDDENLEVEL(PageData pd)throws Exception{
		hiddenMapper.editHIDDENLEVEL(pd);
	}

	/**提交隐患
	 * @throws Exception
	 */
	public void submit(PageData pd)throws Exception{
		hiddenMapper.submit(pd);
	}

	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void changeState(PageData pd)throws Exception{
		hiddenMapper.changeState(pd);
	}

	/**定时修改过期隐患
	 * @param pd
	 * @throws Exception
	 */
	public void editDeadline(PageData pd)throws Exception{
		hiddenMapper.editDeadline(pd);
	}

	/**验收
	 * @param pd
	 * @throws Exception
	 */
	public void check(PageData pd)throws Exception{
		hiddenMapper.check(pd);
	}

	/**复查
	 * @param pd
	 * @throws Exception
	 */
	public void review(PageData pd)throws Exception{
		hiddenMapper.review(pd);
	}

	/**整改
	 * @param pd
	 * @throws Exception
	 */
	public void rectify(PageData pd)throws Exception{
		hiddenMapper.rectify(pd);
	}

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

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

	/**查询昨日过期隐患。发短信
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> getYestoday(PageData pd)throws Exception{
		return hiddenMapper.getYestoday(pd);
	}
	/**列表(全部,打印使用)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> listAllToPrint(PageData pd)throws Exception{
		return hiddenMapper.listAllToPrint(pd);
	}
	public List<PageData> listHiddenAll(PageData pd)throws Exception{
		return hiddenMapper.listHiddenAll(pd);
	}

	/**
	 * 查询清单检查记录中的隐患
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> getHiddenByRecord(PageData pd)throws Exception{
		return hiddenMapper.getHiddenByRecord(pd);
	}

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

	/**批量删除
	 * @param ArrayDATA_IDS
	 * @throws Exception
	 */
	public void deleteAll(String[] ArrayDATA_IDS)throws Exception{
		hiddenMapper.deleteAll(ArrayDATA_IDS);
	}

	/**批量修改
	 * @throws Exception
	 */
	public void updateAll(PageData hiddens)throws Exception{
		hiddenMapper.updateAll(hiddens);
	}

	/**按日统计
	 * @throws Exception
	 */
	public List<PageData> hiddenStatisticsByDay(PageData pd)throws Exception{
		return hiddenMapper.hiddenStatisticsByDay(pd);
	}

	/**总数统计
	 * @throws Exception
	 */
	public List<PageData> hiddenStatisticsAll(PageData pd)throws Exception{
		return hiddenMapper.hiddenStatisticsAll(pd);
	}
	/**
	 *app首页 根据用户ID获取发现隐患信息
	 * @param pd CREATOR
	 * @return
	 * @throws Exception
	 */
	public 	List<PageData> getCountByCreatorId(PageData pd) throws Exception{
		return hiddenMapper.getCountByCreatorId(pd);
	}
	/**
	 *  app首页 根据用户ID获取整改隐患信息
	 * @param pd CREATOR
	 * @return
	 * @throws Exception
	 */
	public 	List<PageData> getCountByRectifiCationorId(PageData pd) throws Exception{
		return hiddenMapper.getCountByRectifiCationorId(pd);
	}

	/**
	 *  app首页根据用户ID获取待验收隐患
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getCountByCheckorId(PageData pd) throws Exception{
		return hiddenMapper.getCountByCheckorId(pd);
	}

	/**
	 *根据企业ID获取驾驶舱隐患统计信息
	 * @return
	 * @throws Exception
	 */
	public 	List<PageData> getBICount(PageData pd) throws Exception{
		return hiddenMapper.getBICount(pd);
	}

	/**
	 * 清单其他隐患
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<PageData> getOtherHidden(PageData pd) throws Exception {
		return hiddenMapper.getOtherHidden(pd);
	}

	/**
	 * 提交清单(其他)隐患
	 */
	@Override
	public void submitList(PageData pd) throws Exception {
		hiddenMapper.submitList(pd);
	}


	public 	List<PageData> getCountByHiddenType(PageData pd) throws Exception{
		return hiddenMapper.getCountByHiddenType(pd);
	}
	/**按日统计
	 * @throws Exception
	 */
	public List<PageData> getHiddenNum(PageData pd)throws Exception{
		return hiddenMapper.getHiddenNum(pd);
	}


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

	/**绩效得分
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> getDeptExamine(PageData pd)throws Exception{
		return hiddenMapper.getDeptExamine(pd);
	}
	public List<PageData> getUserExamine(PageData pd)throws Exception{
		return hiddenMapper.getUserExamine(pd);
	}

	public List<PageData> listAllForDiagnosis(PageData pd)throws Exception{
		return hiddenMapper.listAllForDiagnosis(pd);
	}

	public PageData getUserIndexData(PageData pd)throws Exception{
		return hiddenMapper.getUserIndexData(pd);
	}

	public PageData getDeptIndexData(PageData pd)throws Exception{
		return hiddenMapper.getDeptIndexData(pd);
	}

	public PageData getSuperviseDeptIndexData(PageData pd)throws Exception{
		return hiddenMapper.getSuperviseDeptIndexData(pd);
	}

	@Override
	public List<PageData> findByKey(PageData condition) throws Exception {
		return hiddenMapper.findByKey(condition);
	}
	public List<PageData> findByKeyHiddencheck(PageData condition) throws Exception{
		return hiddenMapper.findByKeyHiddencheck(condition);

	}

	@Override
	public List<PageData> findByQue(PageData condition) throws Exception {
		return hiddenMapper.findByQue(condition);
	}

	@Override
	public List<PageData> findByYin(PageData condition) throws Exception {
		return hiddenMapper.findByYin(condition);
	}

	@Override
	public List<PageData> findByTs(PageData condition) throws Exception {
		return hiddenMapper.findByTs(condition);
	}

	/**
	 * 通过安全检查ID获取隐患
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<PageData> findByInspectionId(PageData pd) throws Exception {
		return hiddenMapper.findByInspectionId(pd);
	}

	@Override
	public List<PageData> listAllInspection(PageData pd) throws Exception {
		List<PageData> hiddenList = hiddenMapper.listAllInspection(pd);
		for (PageData hd : hiddenList) {
			PageData pd2 = new PageData();
			pd2.put("FOREIGN_KEY",hd.getString("HIDDEN_ID"));
			pd2.put("TYPE",3);	//隐患图片
			hd.put("hiddenImgs", imgFilesService.listAll(pd2));
			pd2.put("TYPE",102);	//隐患视频
			hd.put("hiddenVideos", imgFilesService.listAll(pd2));//整改图片
		}
		return hiddenList;
	}

	@Override
	public void editStateInspection(PageData pd) throws Exception {
		hiddenMapper.editStateInspection(pd);
	}

	@Override
	public void deleteByKey(PageData pd) throws Exception {
		hiddenMapper.deleteByKey(pd);
	}

	@Override
	public void deleteArray(PageData pd) throws Exception {
		hiddenMapper.deleteArray(pd);
	}

	/**
	 *  app应用页面根据用户ID获取待确认隐患
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getCountByConfirmId(PageData pd) throws Exception{
		return hiddenMapper.getCountByConfirmId(pd);
	}

	/**
	 *  app应用页面根据用户ID获取特殊处置隐患
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getCountSpecialByhId(PageData pd) throws Exception{
		return hiddenMapper.getCountSpecialByhId(pd);
	}

	/**修改位置描述信息
	 * @param pd
	 * @throws Exception
	 */
	public void editInformation(PageData pd)throws Exception{
		hiddenMapper.editInformation(pd);
	}

	@Override
	public void editstate(PageData hiddenExa) {
		hiddenMapper.editstate(hiddenExa);
	}

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

	/**
	 * 隐患列表 -- 港务局
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> listGwj(Page page) throws Exception{
		return hiddenMapper.listGwjdatalistPage(page);
	}

	/**
	 * 忽略隐患列表 -- 港务局
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> listIgnore(Page page) throws Exception{
		return hiddenMapper.listIgnoredatalistPage(page);
	}

	public void saveForEmis(String hiddenId,String resXML)throws Exception{
		PageData pd = new PageData();
		pd.put("HIDDEN_ID",hiddenId);
		pd.put("resXML",resXML);
		hiddenMapper.saveForEmis(pd);
	}
	/**删除
	 * @param
	 * @throws Exception
	 */
	public void deleteForEmis(String hiddenId)throws Exception{
		PageData pd = new PageData();
		pd.put("HIDDEN_ID",hiddenId);
		hiddenMapper.deleteForEmis(pd);
	}
	public String goEmis (PageData pd) throws Exception{
		String result = "";
		// 1.整理数据
		PageData hiddenPd = this.findById(pd);	/**  确认之前，记录现在的隐患信息 */
		//  隐患确认人
		PageData dianjianUserPd = new PageData();
		dianjianUserPd.put("USER_ID",hiddenPd.getString("CONFIRM_USER"));
		PageData dianjianUser = usersService.findByIdForEmis(dianjianUserPd);
		if(Tools.isEmpty(dianjianUser)){
			return "未找到隐患确认人!";
		}

		if(Tools.isEmpty(dianjianUser.get("DJBM"))){
			result += "隐患确认人部门没有维护对接编码！";
		}
		if(Tools.isEmpty(dianjianUser.get("JCR"))){
			result += "隐患确认人没有维护对接编码！";
		}
		PageData  hiddenRegion= hiddenRegionService.findById(hiddenPd.getString("CORPINFO_ID"),hiddenPd.getString("HIDDENPART"));
		PageData hiddenRegionPar = new PageData();
		if(null != hiddenRegion){
			if(!hiddenRegion.getString("PARENT_ID").equals("0")){
				hiddenRegionPar = hiddenRegionService.findById(hiddenPd.getString("CORPINFO_ID"),hiddenRegion.getString("PARENT_ID"));
				if(!"0".equals(hiddenRegionPar.getString("PARENT_ID"))){
					return "隐患区域等级维护错误!";
				}
			}
		}else{
			return "隐患区域等级维护错误!";
		}

		List<PageData> imgList = imgFilesService.getListByKeyAndType(hiddenPd.getString("HIDDEN_ID"),"3");
		String imgStr = "";
		for (PageData pageData:imgList){
			imgStr += "192.168.192.201/file" + pageData.getString("FILEPATH")+";";
		}
		if (result != ""){
			return result;
		}
		String DJSJ  = DateUtil.date2Str(new Date()); // 点检时间
		String BC  = ""; // 班次,自动算
		String DJBM  = dianjianUser.get("DJBM").toString(); // 点检部门t_b_bm
		String DJBC  = pd.getString("DJBC"); // 点检班次
		String JCR  = dianjianUser.get("JCR").toString(); // 检查人
		String JCLX  =  pd.getString("JCLX"); // 检查类型t_b_jclx--fid
		String SBDL  = hiddenRegionPar.getString("SBDL"); // 设备大类t_b_sbdlxx--sbdlxxdm
		String SBMC  =  hiddenRegion.getString("SBMC");; // 设备名称t_b_shebeixx--shebeidm
		String DJWT  = hiddenPd.getString("HIDDENDESCR"); // 点检问题
		String CJR  = dianjianUser.get("JCR").toString(); // 创建人
		String CJSJ  = DateUtil.date2Str(new Date()); // 创建时间
		String GZFL  = pd.getString("GZFL"); // 故障分类 t_b_kclx
		String SBZJGID  = ""; // 子机构v_b_bujian_zjg
		String BUJIANID  = ""; // 部件v_b_bujian_bj
		String PICTURE  = imgStr; // 图片

		StringBuffer strUrl = new StringBuffer();
		strUrl.append("strDjsj=" + DJSJ);
		strUrl.append("&strBc=" + "");
		strUrl.append("&strDjbm=" + DJBM);
		strUrl.append("&strDjbc=" + DJBC);
		strUrl.append("&strJcr=" + JCR);
		strUrl.append("&strJclx=" + JCLX);
		strUrl.append("&strSbdl=" + SBDL);
		strUrl.append("&strSbmc=" + SBMC);
		strUrl.append("&strDjwt=" + DJWT);
		strUrl.append("&strCjr=" + CJR);
		strUrl.append("&strCjsj=" + CJSJ);
		strUrl.append("&strGzfl=" + GZFL);
		strUrl.append("&strSbzjgId=" + SBZJGID);
		strUrl.append("&strBuJianId=" + BUJIANID);
		strUrl.append("&strPicture=" + PICTURE);
		String resXML = HttpEmisDuijieUtil.sendPostNoAccept(strUrl.toString());
		StringBuffer strUrl2 = new StringBuffer();
		strUrl2.append("djsj:" + DJSJ);
		strUrl2.append(",bc:" + "");
		strUrl2.append(",djbm:" + DJBM);
		strUrl2.append(",djbc:" + DJBC);
		strUrl2.append(",jcr:" + JCR);
		strUrl2.append(",jclx:" + JCLX);
		strUrl2.append(",sbdl:" + SBDL);
		strUrl2.append(",sbmc:" + SBMC);
		strUrl2.append(",djwt:" + DJWT);
		strUrl2.append(",cjr:" + CJR);
		strUrl2.append(",cjsj:" + CJSJ);
		strUrl2.append(",gzfl:" + GZFL);
		strUrl2.append(",sbzjgID:" + SBZJGID);
		strUrl2.append(",bujianid:" + BUJIANID);
		strUrl2.append(",pic:" + PICTURE);
		if(strUrl2.toString().equals(resXML)){
			/**
			 * 成功
			 * 1.删除现在的隐患内容
			 * 2.存储这次的隐患内容
			 */
			this.saveForEmis(hiddenPd.getString("HIDDEN_ID"),resXML);
			this.deleteForEmis(hiddenPd.getString("HIDDEN_ID"));
			return "success";
		}else{
			//失败
			return resXML;
		}
	}

	/**
	 * 确认隐患，修改隐患状态
	 * @param pd
	 * @throws Exception
	 */
	public void confirmHidden (PageData pd) throws Exception{
		hiddenMapper.confirmHidden(pd);
	}

	@Override
	public List<PageData> listForSafetyEnvironmental(Page page) throws Exception {
		return hiddenMapper.hiddenInspectionlistPage(page);
	}

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

	@Override
	public void assign(PageData pd) throws Exception {
		hiddenMapper.assign(pd);
	}

	/**安全环保检查验收
	 * @param pd
	 * @throws Exception
	 */
	public void finalcheck(PageData pd)throws Exception{
		hiddenMapper.finalcheck(pd);
	}

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

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> getListForTianzhang(Page page)throws Exception{
		return hiddenMapper.getListForTianzhangdatalistPage(page);
	}

	/**
	 * 修改隐患信息，隐患级别 ，整改负责人 ， 整改期限
	 * @param pd
	 * @throws Exception
	 */
	public void confirmUpdate(PageData pd) throws Exception{
		hiddenMapper.confirmUpdate(pd);
	}

	public void updateStateByHidden(String type,String hiddenId) throws Exception{
		PageData pd = new PageData();
		pd.put("STATE",type);
		pd.put("HIDDEN_ID",hiddenId);
		hiddenMapper.updateStateByHidden(pd);
	}

	/**
	 *  修改隐患状态，进入隐患特殊处理审核
	 */
	public void updteStateBySpecialExamine(PageData pageData)throws Exception{
		PageData pd = new PageData();
		pd.put("HIDDENEXAMINE_ID", UuidUtil.get32UUID());
		pd.put("CREATOR", Jurisdiction.getUSER_ID());
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));
		pd.put("OPERATOR",Jurisdiction.getUSER_ID());
		pd.put("OPERATTIME",DateUtil.date2Str(new Date()));
		pd.put("TYPE","1");
		pd.put("STATE","-1");
		pd.put("EXAMINE",pageData.get("EXAMINE")); // 无法整改原因
		pd.put("HIDDEN_ID",pageData.get("HIDDEN_ID"));// 隐患id
		hiddenexamineMapper.save(pd);

		this.updateStateByHidden("7",pageData.get("HIDDEN_ID").toString()); //修改隐患状态
	}

	/**
	 * 重大隐患列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> majorlist(Page page) throws Exception{
		return hiddenMapper.majordatalistPage(page);
	}

	/**
	 * 重大隐患核实列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> verifylist(Page page) throws Exception{
		return hiddenMapper.verifydatalistPage(page);
	}

	/**
	 * 重大隐患列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> majormanage(Page page) throws Exception{
		return hiddenMapper.majormanagelistPage(page);
	}
	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findByEmisId(PageData pd)throws Exception{
		return hiddenMapper.findByEmisId(pd);
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> getListForemis(Page page)throws Exception{
		return hiddenMapper.getListForemisdatalistPage(page);
	}

	@Override
	public void createExcel(HttpServletResponse response, PageData request) throws Exception {
        PageData lock = new PageData();
        lock.putAll(request);
        // 隐患级别数据字典dicMap(id:name)
        String dicParentId = "5e7cf8620ba54ad89719d0be62133c7a";
        List<Dictionaries> dicList = dictionariesService.listSubDictByParentId(dicParentId);// 字典
        Map<String, String> dicMap = dicList.stream().collect(Collectors.toMap(Dictionaries::getBIANMA, Dictionaries::getNAME));

        PageData condition = new PageData();
        condition.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());// CORPINFO_ID
        // 公司内所有的人员信息userList(id:name)
        List<PageData> userList = usersService.listAllUser(condition);
        Map<String, String> userMap = userList.stream().collect(Collectors.toMap((x -> x.getString("USER_ID")), (y -> y.getString("NAME"))));
        // 公司内所有部门信息(id:name)
        List<PageData> deparList = departmentService.listAll(condition);
        // 查看企业下的所有部门，根据部门id匹配信息
        Map<String, String> deparMap = deparList.stream().collect(Collectors.toMap((x -> x.getString("DEPARTMENT_ID")), (y -> y.getString("NAME"))));
        // 校验请求参数
        Warden.checkRequestHiddenCreateExcel(lock);
        // 查看隐患信息
        condition.clear();
        if ("1".equals(lock.getString("havePicture"))) {
            condition.put("HIDDEN_IDS", lock.getString("hiddenIds").split(","));
        } else {
            condition.put("KEYWORDS", lock.getString("KEYWORDS"));
            condition.put("DISPOSESTATE", lock.getString("DISPOSESTATE"));
            condition.put("STATE", lock.getString("STATE"));
            condition.put("STARTTIME", lock.getString("STARTTIME"));
            condition.put("ENDTIME", lock.getString("ENDTIME"));
            condition.put("DEPTIDS", lock.getString("DEPTIDS"));
            condition.put("ISQUALIFIED", lock.getString("ISQUALIFIED"));
            condition.put("HIDDENLEVEL", lock.getString("HIDDENLEVEL"));
            condition.put("IS_SELF", lock.getString("IS_SELF"));
            condition.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        }
        List<PageData> varOList = hiddenMapper.listAll(condition);

        Set<String> imgIds = varOList.stream().map(n -> n.getString("HIDDEN_ID")).collect(Collectors.toSet());
        // 查询整改方案
        List<PageData> schemeList = hiddenSchemeMapper.listExport(condition);
        Map<String, PageData> schemeMap = schemeList.stream().filter(n -> "0".equals(n.getString("ISDELETE"))).collect(Collectors.toMap((n -> n.getString("HIDDEN_ID")), (m -> m)));
        imgIds.addAll(schemeList.stream().map(n -> n.getString("HIDDENSCHEME_ID")).collect(Collectors.toSet()));
        // 验收信息
        List<PageData> checkList = hiddenCheckMapper.listExport(condition);
        imgIds.addAll(checkList.stream().map(n -> n.getString("HIDDENCHECK_ID")).collect(Collectors.toSet()));
        Map<String, List<PageData>> checkMap = checkList.stream().collect(Collectors.toMap((n -> n.getString("HIDDEN_ID")), (Arrays::asList)));
        int checkMaxCount = checkMap.values().stream().mapToInt(List::size).max().orElse(0);
        // 组织参数查询出所有跟隐患相关的图片
        condition.clear();
        condition.put("ArrayDATA_IDS", imgIds.toArray(new String[0]));
        List<PageData> imgList = imgFilesService.listAllByIds(condition)
                .stream()
                .filter(n -> n.get("TYPE") != null && StringUtils.isNotBlank(n.get("TYPE").toString()))
                .filter(n -> n.get("FOREIGN_KEY") != null && StringUtils.isNotBlank(n.getString("FOREIGN_KEY")))
				.filter(n -> !(n.getString("FILEPATH").contains(".mp4")))//排除视频
				.filter(n -> !(n.getString("FILEPATH").contains(".MP4")))
                .collect(Collectors.toList());

        Map<String, List<PageData>> imgMap = imgList.stream().collect(Collectors.groupingBy(m -> m.getString("FOREIGN_KEY")));

        List<String> index = Arrays.asList("3", "4", "5", "8");
        Map<String, Integer> limit = new HashMap<>();
        for (String x : index) {
            int number = imgList.stream()
                    .filter(n -> x.equals(n.get("TYPE").toString()))
                    .collect(Collectors.groupingBy(m -> m.getString("FOREIGN_KEY")))
                    .values().stream()
                    .mapToInt(List::size)
                    .max()
                    .orElse(0);
            limit.put(x, number);
        }
        // 组装数据
        HiddenExcel excel = new HiddenExcel(limit.get("3"), limit.get("4"), limit.get("8"), checkMaxCount, limit.get("5"));
        excel.setHavePicture(request.getString("havePicture"));
        excel.setLeveMap(dicMap);
        excel.setDepMap(deparMap);
        excel.setUserMap(userMap);
        excel.setFoot(schemeMap);
        excel.setImgMap(imgMap);
        excel.setCheckMap(checkMap);
        excel.setNuTitle(JSONObject.parseArray(request.getString("options"), String.class));
        excel.initHead();
        excel.addAllBody(varOList);
        // 组装表格样式
        WriteCellStyle headWriteCellStyle = HiddenExcel.getHeadStyle();
        WriteCellStyle cellStyle = HiddenExcel.getHeadStyle();
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, cellStyle);

        EasyExcel.write(response.getOutputStream())
                .useDefaultStyle(true)
				.relativeHeadRowIndex(1)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                .sheet("隐患台账")
                .head(excel.getHead())
                .doWrite(excel.getHand());
    }

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> listRiskStandard(Page page)throws Exception{
		return hiddenMapper.riskStandardlistPage(page);
	}

	/**
	 * 根据用户ID获取待整改隐患（app首页）
	 * @param pd CREATOR
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getRiskStandardCountByRectifiCationorId(PageData pd) throws Exception{
		return hiddenMapper.getRiskStandardCountByRectifiCationorId(pd);
	}

	/**
	 * 根据用户ID获取待验收隐患（app首页）
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getRiskStandardCountByCheckorId(PageData pd) throws Exception{
		return hiddenMapper.getRiskStandardCountByCheckorId(pd);
	}

	/**根据用户ID获取待确认隐患（app首页）
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> getRiskStandardCountByConfirmId(PageData pd) throws Exception{
		return hiddenMapper.getRiskStandardCountByConfirmId(pd);
	}

	/**
	 *  根据用户ID获取特殊处理隐患和延期隐患（app首页）
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getRiskStandardCountSpecialByhId(PageData pd) throws Exception{
		return hiddenMapper.getRiskStandardCountSpecialByhId(pd);
	}

	/**
	 * 根据用户ID获取发现隐患信息（app首页）
	 * @param pd CREATOR
	 * @return
	 * @throws Exception
	 */
	public 	List<PageData> getRiskStandardCountByCreatorId(PageData pd) throws Exception{
		return hiddenMapper.getRiskStandardCountByCreatorId(pd);
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> hiddenlist(Page page)throws Exception{
		return hiddenMapper.hiddenAlllistPage(page);
	}
}

