package com.zcloud.controller.risk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.Response;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.check.ListCheckItemService;
import com.zcloud.service.risk.*;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.*;

/**
 * 说明：风险点台账
 * 作者：luoxiaobao
 * 时间：2020-12-29
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/riskpoint")
public class RiskPointController extends BaseController {

	@Autowired
	private RiskPointService riskpointService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
    private UsersService usersService;
	@Autowired
    private RiskToUserService riskToUserService;
	@Autowired
	private RiskPointPositionService riskPointPositionService;
	@Autowired
	private IdentificationPartsService identificationPartsService;
	@Autowired
	private RiskUnitService riskUnitService;
	@Autowired
	private RiskCheckItemService riskcheckitemService;
	@Autowired
	private DictionariesService dictionariesService;
	@Autowired
	private IdentificationPartsService identificationpartsService;
	@Autowired
	private Smb smb;
	@Autowired
	private ListCheckItemService listcheckitemService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("riskpoint:add")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "新增")
	public Object add() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		PageData request = this.getPageData();
		pd = this.getPageData();
		pd.put("RISKPOINT_ID", this.get32UUID());	//主键
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		pd.put("ISDELETE", "0");	//是否删除
		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//创建时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		String riskPointCountString = riskpointService.countByCorpInfo(pd);
		Integer count = Integer.parseInt(riskPointCountString);
		count ++;
		pd.put("SORT", count);
		riskpointService.save(pd);
		// 大姐能不能不要这么坑！！！！我找了一天！！！
		pd = riskpointService.findById(pd);
		if(pd.get("OTHER")!=null && !pd.get("OTHER").equals("")) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.get("OTHER").toString());
			for (JSONObject json : list) {
				if(json.get("DEPARTMENT_ID")!=null && json.get("DEPARTMENT_ID")!="" && json.get("USER_ID")!=null && json.get("USER_ID")!="") {
					PageData other = new PageData();
					other.put("RISKTOUSER_ID", this.get32UUID());	//主键
					other.put("RISKPOINT_ID", pd.get("RISKPOINT_ID"));
					other.put("DEPARTMENT_ID",json.get("DEPARTMENT_ID"));
					other.put("USER_ID",json.get("USER_ID"));
					riskToUserService.save(other);
				}
			}
		}
		PageData item = new PageData();
		item.put("RISKCHECKITEM_ID", this.get32UUID());	//主键
		item.put("RISKPOINT_ID", pd.get("RISKPOINT_ID"));	//风险点主键
		item.put("ISDELETE", "0");	//是否删除
		item.put("CREATOR", Jurisdiction.getUsername());	//添加人
		item.put("CREATTIME", DateUtil.date2Str(new Date()));	//创建时间
		item.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		item.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		item.put("CHECK_CONTENT", request.get("CHECK_CONTENT"));	//检查内容
		riskcheckitemService.save(item);
		pd.put("RISKCHECKITEM_ID",item.getString("RISKCHECKITEM_ID"));
		map.put("result", errInfo);
		map.put("pd", pd);
		return map;
	}

	/**
	 * 去修改页面获取数据
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/goAdd")
	// @RequiresPermissions("riskpoint:add")
	@ResponseBody
	public Object goAdd() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
//			//获取部门下拉树
//			List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//			String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//			ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//			PageData dept = new PageData();
//			dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//			dept=this.departmentService.findById(dept);


		//获取部门下拉树
		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept = this.departmentService.findByCorpId(dept);
		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

		PageData node = new PageData();
		node.put("id", dept.get("DEPARTMENT_ID"));
		node.put("parentId", dept.get("PARENT_ID"));
		node.put("name", dept.get("NAME"));
		node.put("icon", "../../../assets/images/user.gif");
		zdepartmentPdList.add(node);
		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID, zdepartmentPdList));
		map.put("zTreeNodes", (null == arr ? "" : "{\"treeNodes\":" + arr.toString() + "}"));

		//获取人员下拉
		PageData user = new PageData();
		user.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
		List<PageData> userList = this.usersService.listAllUser(user);
		map.put("userList", userList);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("riskpoint:del")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "删除")
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData> list = listcheckitemService.listByriskpointid(pd);
		if(list!=null && list.size()>0) {
//			map.put("result", "failed");				//返回结果
			map.put("msg", "该风险管控台账已在清单中应用，无法删除");
			return map;
		}
		riskpointService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("riskpoint:edit")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "修改")
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		riskpointService.edit(pd);
		// 修改冗余字段检查内容
		PageData pd2 = new PageData();
		pd2.put("CHECK_CONTENT", pd.get("MEASURES"));
		pd2.put("RISKPOINT_ID", pd.get("RISKPOINT_ID"));
		riskcheckitemService.editByPoint(pd2);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("riskpoint:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "列表")
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		PageData npd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		npd.putAll(pd);
		if(Tools.notEmpty(KEYWORDS))npd.put("KEYWORDS", KEYWORDS.trim());
		npd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		npd.put("ISMAIN", Jurisdiction.getIS_MAIN());
		npd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
		npd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
		pd.put("USER_ID",Jurisdiction.getUSER_ID());
		PageData cpd = new PageData();
		cpd = usersService.findById(pd);
		npd.put("ISLEADER", cpd.getString("ISLEADER"));
		if(cpd.getString("ISLEADER") != null && cpd.getString("ISLEADER").equals("1")){
			String DEPARTMENT_ID = npd.getString("DEPARTMENT_ID");
			String ids = departmentService.getDEPARTMENT_IDS(DEPARTMENT_ID);
			ids=npd.getString("DEPARTMENT_ID")+","+ids;   //把自己部门插入进去
			if(ids!=null && Tools.notEmpty(ids)&& ids.lastIndexOf(",")>-1) {
				ids = ids.substring(0,ids.lastIndexOf(","));
				npd.put("DEPARTMENT_IDS", ids.split(","));
			}else {
				npd.put("DEPARTMENT_IDS", DEPARTMENT_ID);
			}
		}
		String DEPTIDS = pd.getString("DEPTIDS");
		if(Tools.notEmpty(DEPTIDS)) {
			String DEPT_IDS[] = DEPTIDS.split(",");
			npd.put("DEPT_IDS", DEPT_IDS);
		}
		page.setPd(npd);
		List<PageData>	varList = riskpointService.list(page);	//列出RiskPoint列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "去修改页面获取数据")
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = riskpointService.findById(pd);	//根据ID读取
		List<PageData> others=riskToUserService.listAll(pd);

		//获取部门下拉树
		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept=this.departmentService.findByCorpId(dept);
		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

		PageData node = new PageData();
		node.put("id", dept.get("DEPARTMENT_ID"));
		node.put("parentId", dept.get("PARENT_ID"));
		node.put("name", dept.get("NAME"));
		node.put("icon", "../../../assets/images/user.gif");
		zdepartmentPdList.add(node);
		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));

		//获取人员下拉
		PageData user = new PageData();
		user.put("DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
		List<PageData> userList = this.usersService.listAllUser(user);
		map.put("userList", userList);

		List<PageData> partsList = identificationpartsService.listAll(pd);
		map.put("partsList", partsList);
		dept.put("DEPARTMENT_ID",pd.get("DEPARTMENT_ID"));
		dept=this.departmentService.findById(dept);
		String depname = null == dept?"请选择":dept.getString("NAME");
		map.put("depname", null == depname?"请选择":depname);
		map.put("pd", pd);
		map.put("others", others);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 首页统计
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/statistic")
	@ResponseBody
	@LogAnno(menuType= "首页",menuServer= "首页",instructionsOperate = "首页",instructionsType = "首页统计")
	public Object statistic() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());

//		if(pd.get("isBI")==null) {
//			pd.put("USER_ID",Jurisdiction.getUsername());
//			String DEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//			String ids = departmentService.getDEPARTMENT_IDS(DEPARTMENT_ID);
//			if(ids!=null && Tools.notEmpty(ids)) {
//				ids = ids.substring(0,ids.lastIndexOf(","));
//				pd.put("DEPARTMENT_IDS", ids.split(","));
//			}
//		}

		List<PageData> riskAll = riskpointService.statisticsAll(pd);
		// int riskCount =
		// List<PageData> riskAll = identificationPartsService.getBiCount(pd);
		List<PageData> idAll = identificationPartsService.listIndexAll(pd);
		List<PageData> unitAll = riskUnitService.listIndexAll(pd);
		Integer idcount = 0;
		Integer unitcount = 0;
		Integer cnzfx = 0;
		if (idAll != null && idAll.size() > 0) {
			idcount = idAll.size();
		}
		if (unitAll != null && unitAll.size() > 0) {
			unitcount = unitAll.size();
		}
		for (int i = 0; riskAll.size() > i; i++) {
			if (riskAll.get(i).get("LEVELID") != null && Tools.notEmpty(riskAll.get(i).get("LEVELID").toString())) {
				if ("levelA".equals(riskAll.get(i).get("LEVELID").toString())
						|| "levelB".equals(riskAll.get(i).get("LEVELID").toString())
						|| "levelC".equals(riskAll.get(i).get("LEVELID").toString())
						|| "levelD".equals(riskAll.get(i).get("LEVELID").toString())) {
					cnzfx += Integer.valueOf(riskAll.get(i).get("COUNT").toString());
				}
			}
		}

		Map<String, Object> riskCount = new HashMap<>();

		riskCount.put("idcount", idcount);
		riskCount.put("unitcount", unitcount);
		riskCount.put("cnzfx", cnzfx);
		// 风险点-只按名称统计 辨识部位-统计不同单元内的辨识部位名称的总数

		map.put("riskCount", riskCount);
		map.put("riskAll", riskAll);
		map.put("idAll", idAll);
		map.put("unitAll", unitAll);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("riskpoint:del")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "批量删除")
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			pd.put("RISKPOINT_IDS",DATA_IDS.split(","));
			List<PageData> list = listcheckitemService.listByriskpointid(pd);
			if(list!=null && list.size()>0) {
//			map.put("result", "failed");				//返回结果
				map.put("msg", "已选择的风险管控台账已在清单中应用，无法删除");
				return map;
			}
			riskpointService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
//	// @RequiresPermissions("toExcel")
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "导出到excel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		if(Jurisdiction.getUsername()!="admin") {
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		}
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String[] ArrayDATA_IDS = DATA_IDS.split(",");
			pd.put("ArrayDATA_IDS",ArrayDATA_IDS);
		}
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("企业名称");	//1
		titles.add("风险点（单元）");	//2
		titles.add("辨识部位");	//3
		titles.add("存在风险");	//4
		//titles.add("风险点位置");	//4
		titles.add("风险分级");	//5
		titles.add("管控措施");	//6
		titles.add("事故类型");	//7
		titles.add("应急处置措施");	//8
		titles.add("管控部门");	//9
		titles.add("管控责任人");	//10
		titles.add("添加人");	//12
		titles.add("创建时间");	//13
		titles.add("修改人");	//14
		titles.add("修改时间");	//15
		dataMap.put("titles", titles);
		List<PageData> varOList = riskpointService.listAllByDc(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("CORP_NAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("RISKUNITNAME"));	    //2
			vpd.put("var3", varOList.get(i).getString("PARTSNAME"));	    //3
			vpd.put("var4", varOList.get(i).getString("RISK_DESCR"));	    //4
			//vpd.put("var4", varOList.get(i).getString("RISK_POSITION_ID"));	    //4
			vpd.put("var5", varOList.get(i).getString("LEVELID"));	    //5
			vpd.put("var6", varOList.get(i).getString("MEASURES"));	    //6
			vpd.put("var7", varOList.get(i).getString("ACCIDENTS_NAME"));	    //7
			vpd.put("var8", varOList.get(i).getString("EME_MEASURES"));	    //8
			vpd.put("var9", varOList.get(i).getString("DEPARTMENT_ID"));	    //9
			vpd.put("var10", varOList.get(i).getString("USER_ID"));	    //10
			vpd.put("var11", varOList.get(i).getString("CREATOR"));	    //12
			vpd.put("var12", varOList.get(i).getString("CREATTIME"));	    //13
			vpd.put("var13", varOList.get(i).getString("OPERATOR"));	    //14
			vpd.put("var14", varOList.get(i).getString("OPERATTIME"));	    //15
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}


	/**获取风险点下拉框选项
	 * @throws Exception
	 */
	@RequestMapping(value="/getPointSelect")
	@ResponseBody
	@LogAnno(menuType= "双重预控",menuServer= "持续改进",instructionsOperate = "隐患分析",instructionsType = "获取风险点下拉框选项")
	public Object getPointSelect() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		List<PageData> positionList = riskPointPositionService.listAll(pd);
		List<PageData> partsList = identificationPartsService.listAll(pd);
		List<PageData> unitList = riskUnitService.listAll(pd);
		map.put("positionList", positionList);
		map.put("partsList", partsList);
		map.put("unitList", unitList);
		map.put("result", errInfo);
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
//	@RequestMapping(value="/excelModel")
////	// @RequiresPermissions("toExcel")
//	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "导出模板")
//	public void exportExcelModel(HttpServletResponse response) throws Exception{
//
////		Exclupload ss=new Exclupload();
////		ss.testModuleExcel();
//
//
//		FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "riskpointExcelTemplate.xls", "风险辨识导入模板.xls");
//	}


	/**从EXCEL导入到数据库
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/readExcel2")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险管控台账",instructionsType = "上传附件")
	public Object readExcel2(@RequestParam(value="FFILE",required=false) MultipartFile file) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pdPublic = new PageData();
		pdPublic = this.getPageData();
		StringBuffer errorStr = new StringBuffer();
		List<PageData> rList = new ArrayList<PageData>();
		if (null != file && !file.isEmpty()) {


			File tempFile = new File(file.getOriginalFilename()); //新建file
			FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
			List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 1, 0, 0);			//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			/**
			 * var0 :风险点（单元）
			 * var1 :辨识部位
			 * var2 :存在风险
			 * var3 :风险分级
			 * var4 :主要管控措施
			 * var5 :管控部门
			 * var6 :责任人
			 * var7 :事故类型
			 * var8 :事故类型
			 * var9 :事故类型
			 * var10 :事故类型
			 * var11 :应急处置措施
			 */

			List<String> header = new ArrayList<>();
			header.add("风险点（单元）");header.add("辨识部位");header.add("存在风险");header.add("风险分级");header.add("主要管控措施");
			header.add("管控部门");header.add("责任人");header.add("事故类型1");header.add("事故类型2");header.add("事故类型3");
			header.add("事故类型4");header.add("应急处置措施");

			PageData corpinfoId = new PageData();//企业下的全部的风险点
			corpinfoId.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
			corpinfoId.put("ISDELETE", "0");
			List<PageData>  riskUnitList=riskUnitService.listAll(corpinfoId);
			Map<String, Object> riskMapAll = new HashMap<>();
			for (PageData pageData : riskUnitList) {
				riskMapAll.put(pageData.getString("DEPARTMENT_ID")+ Tools.excelHandle(pageData.getString("RISKUNITNAME")), pageData);
			}


			List<PageData> idenList = identificationpartsService.listAll(corpinfoId);
			Map<String, Object> identMapAll = new HashMap<>();
			for (PageData pageData : idenList) {
				identMapAll.put(pageData.getString("RISK_UNIT_ID")+ Tools.excelHandle(pageData.getString("PARTSNAME")), pageData);
			}

			List<Dictionaries> levelAll =dictionariesService.listSubDictByParentId("5a81e63ec0e94d919b3138bc01dbef6b");//获取全部的风险等级
			Map<String, Object> levelMapAll = new HashMap<>();
			for (Dictionaries dictionaries : levelAll) {
				levelMapAll.put(Tools.excelHandle(dictionaries.getNAME()), dictionaries);
			}


			List<PageData> deptListAll = departmentService.listAll(corpinfoId);
			Map<String, Object> deptMapAll = new HashMap<>();
			for (PageData pageData : deptListAll) {
				deptMapAll.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
			}

			List<Dictionaries> accListAll =dictionariesService.listSubDictByParentId("cee1190ea96a4ca9b7bca81e11f0d0f8");//获取全部的事故类型
			Map<String, Object> accMapList = new HashMap<>();
			for (Dictionaries dictionaries : accListAll) {
				accMapList.put(Tools.excelHandle(dictionaries.getNAME()), dictionaries);
			}

			String riskPointCountString = riskpointService.countByCorpInfo(corpinfoId);
			Integer rislPointCount = Integer.parseInt(riskPointCountString);
			int succeeNum = 1;
			if(listPd.size()<1) {
				map.put("result", "error");				//返回结果
				map.put("resultStr", "Excel数据为空，请检查数据后，重新上传！");
				FileUtils.deleteQuietly(tempFile);//删除临时文件
				return map;
			}
			for(PageData lpd:listPd) {
				succeeNum ++;

				for(int i=0;i<header.size();i++) {
					if(i>=6) {
						continue;
					}
					if(!lpd.containsKey("var"+i)) {
						errorStr.append("<p>第"+succeeNum+"行的\""+header.get(i)+"\"无数据</p>");
						continue;
					}
					if(Tools.isEmpty(lpd.get("var"+i))) {
						errorStr.append("<p>第"+succeeNum+"行的\""+header.get(i)+"\"无数据</p>");
						continue;
					}
				}


				String riskVar = Tools.isEmpty(lpd.get("var0"))?"": Tools.excelHandle(lpd.get("var0"));
				String identificationVar = Tools.isEmpty(lpd.get("var1"))?"": Tools.excelHandle(lpd.get("var1"));
				String riskPointVar = Tools.isEmpty(lpd.get("var2"))?"": Tools.excelHandle(lpd.get("var2"));
				String levelVar = Tools.isEmpty(lpd.get("var3"))?"": Tools.excelHandle(lpd.get("var3"));
				String measuresVar = Tools.isEmpty(lpd.get("var4"))?"": Tools.excelHandle(lpd.get("var4"));
				String departNameVar = Tools.isEmpty(lpd.get("var5"))?"": Tools.excelHandle(lpd.get("var5"));
				String accidentsNameVar = Tools.isEmpty(lpd.get("var6"))?"": Tools.excelHandle(lpd.get("var6"));
				String accidents7Var = Tools.isEmpty(lpd.get("var7"))?"": Tools.excelHandle(lpd.get("var7"));
				String accidents8Var = Tools.isEmpty(lpd.get("var8"))?"": Tools.excelHandle(lpd.get("var8"));
				String accidents9Var = Tools.isEmpty(lpd.get("var9"))?"": Tools.excelHandle(lpd.get("var9"));
				String accidents10Var = Tools.isEmpty(lpd.get("var10"))?"": Tools.excelHandle(lpd.get("var10"));
				String emeMeasuresVar = Tools.isEmpty(lpd.get("var11"))?"": Tools.excelHandle(lpd.get("var11"));

				if(!deptMapAll.containsKey(departNameVar)) {
					errorStr.append("<p>第"+succeeNum+"行的"+header.get(5)+"未找到名称为\""+departNameVar+"\"的管控部门"+"</p>");
					continue;
				}
				PageData depart = (PageData) deptMapAll.get(departNameVar);

				if(!riskMapAll.containsKey(depart.getString("DEPARTMENT_ID")+riskVar)) {
					errorStr.append("<p>第"+succeeNum+"行的"+header.get(0)+"未找到名称为\""+riskVar+"\"的风险点（单元）"+"</p>");
					continue;
				}
				PageData riskVal = (PageData)riskMapAll.get(depart.getString("DEPARTMENT_ID")+riskVar);
				if(!identMapAll.containsKey(riskVal.getString("RISKUNIT_ID")+identificationVar)) {
					errorStr.append("<p>第"+succeeNum+"行的"+header.get(1)+"未找到名称为\""+identificationVar+"\"的辨识部位"+"</p>");
					continue;
				}
				if(!levelMapAll.containsKey(levelVar)) {
					errorStr.append("<p>第"+succeeNum+"行的"+header.get(3)+"未找到名称为\""+levelVar+"\"的风险分级"+"</p>");
					continue;
				}
				if(!Tools.isEmpty(accidents7Var)) {
					if(!accMapList.containsKey(accidents7Var)) {
						errorStr.append("<p>第"+succeeNum+"行的"+header.get(7)+"未找到名称为\""+accidents7Var+"\"的事故类型(1)"+"</p>");
						continue;
					}
				}
				if(!Tools.isEmpty(accidents8Var)) {
					if(!accMapList.containsKey(accidents8Var)) {
						errorStr.append("<p>第"+succeeNum+"行的"+header.get(8)+"未找到名称为\""+accidents8Var+"\"的事故类型(2)"+"</p>");
						continue;
					}
				}
				if(!Tools.isEmpty(accidents9Var)) {
					if(!accMapList.containsKey(accidents9Var)) {
						errorStr.append("<p>第"+succeeNum+"行的"+header.get(9)+"未找到名称为\""+accidents9Var+"\"的事故类型(3)"+"</p>");
						continue;
					}
				}
				if(!Tools.isEmpty(accidents10Var)) {
					if(!accMapList.containsKey(accidents10Var)) {
						errorStr.append("<p>第"+succeeNum+"行的"+header.get(10)+"未找到名称为\""+accidents10Var+"\"的事故类型(4)"+"</p>");
						continue;
					}
				}

				PageData identVal = (PageData) identMapAll.get(riskVal.getString("RISKUNIT_ID")+identificationVar);
				Dictionaries levelVal = (Dictionaries) levelMapAll.get(levelVar);
//				Dictionaries acc7Val = (Dictionaries) accMapList.get(accidents7Var);




				String accidentsId = "";
				String accidentsNames ="";
//				accidentsId +=acc7Val.getBIANMA();
//				accidentsNames += acc7Val.getNAME();
				if(!Tools.isEmpty(accidents7Var)) {
					Dictionaries acc7Val = new Dictionaries();
					acc7Val = (Dictionaries) accMapList.get(accidents7Var);
					accidentsId += ","+acc7Val.getBIANMA();
					accidentsNames +=","+acc7Val.getNAME();
				}
				if(!Tools.isEmpty(accidents8Var)) {
					Dictionaries acc8Val = new Dictionaries();
					acc8Val = (Dictionaries) accMapList.get(accidents8Var);
					accidentsId += ","+acc8Val.getBIANMA();
					accidentsNames +=","+acc8Val.getNAME();
				}
				if(!Tools.isEmpty(accidents9Var)) {
					Dictionaries acc9Val = new Dictionaries();
					acc9Val = (Dictionaries) accMapList.get(accidents9Var);
					accidentsId += ","+acc9Val.getBIANMA();
					accidentsNames +=","+acc9Val.getNAME();
				}
				if(!Tools.isEmpty(accidents10Var)) {
					Dictionaries acc10Val = new Dictionaries();
					acc10Val = (Dictionaries) accMapList.get(accidents10Var);
					accidentsId += ","+acc10Val.getBIANMA();
					accidentsNames +=","+acc10Val.getNAME();
				}
				if(Tools.notEmpty(accidentsId)) {
					accidentsId = accidentsId.substring(1, accidentsId.length());
				}
				if(Tools.notEmpty(accidentsNames)) {
					accidentsNames = accidentsNames.substring(1, accidentsNames.length());
				}
				PageData riskPoint = new PageData();
				riskPoint.put("RISK_UNIT_ID", riskVal.getString("RISKUNIT_ID"));
				riskPoint.put("IDENTIFICATION_ID", identVal.getString("IDENTIFICATIONPARTS_ID"));
				riskPoint.put("RISK_DESCR", riskPointVar);
				riskPoint.put("LEVELID", levelVal.getBIANMA());
				riskPoint.put("MEASURES", measuresVar);
				riskPoint.put("DEPARTMENT_ID", depart.getString("DEPARTMENT_ID"));
				riskPoint.put("USER_ID", accidentsNameVar);
				riskPoint.put("ACCIDENTS", accidentsId);
				riskPoint.put("ACCIDENTS_NAME", accidentsNames);
				riskPoint.put("EME_MEASURES", emeMeasuresVar);
				riskPoint.put("RISKPOINT_ID", this.get32UUID());
				riskPoint.put("ISDELETE", "0");
				riskPoint.put("CREATOR", Jurisdiction.getUsername());
				riskPoint.put("CREATTIME", DateUtil.date2Str(new Date()));
				riskPoint.put("OPERATOR", Jurisdiction.getUsername());
				riskPoint.put("OPERATTIME", DateUtil.date2Str(new Date()));
				riskPoint.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
				riskPoint.put("SORT", rislPointCount +succeeNum);

				rList.add(riskPoint);
			}

			if(Tools.isEmpty(errorStr.toString())) {
				System.out.println(rList.size());
				for(PageData r:rList) {
					riskpointService.save(r);
					PageData riskcheckitem = new PageData();
					riskcheckitem.put("RISKCHECKITEM_ID", this.get32UUID());	//主键
					riskcheckitem.put("CHECK_CONTENT", r.getString("MEASURES"));
					riskcheckitem.put("ISDELETE", "0");	//是否删除
					riskcheckitem.put("CREATOR", Jurisdiction.getUsername());	//添加人
					riskcheckitem.put("CREATTIME", DateUtil.date2Str(new Date()));	//创建时间
					riskcheckitem.put("OPERATOR", Jurisdiction.getUsername());	//修改人
					riskcheckitem.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
					riskcheckitem.put("RISKPOINT_ID", r.getString("RISKPOINT_ID"));	//风险点
					riskcheckitemService.save(riskcheckitem);
				}
				errorStr.append("成功导入"+rList.size()+"条数据!");
			}else {
				errInfo = "error";
			}

			FileUtils.deleteQuietly(tempFile);//删除临时文件
		}
		map.put("result", "success");				//返回结果
		map.put("resultType", errInfo);				//返回message类型
		map.put("isExcel","1");				//返回类型
		map.put("resultStr", errorStr.toString());
		return map;
	}

	@RequestMapping("/getLogs")
	@ResponseBody
	public Response getLogs(Page page) {
		Response response = Response.getResponse();
		try {
			PageData request = this.getPageData();
			response.putAll(riskpointService.getLogs(request, page));
			return response.OK();
		} catch (Exception e) {
			e.printStackTrace();
			return response.errorMessage(e.getMessage());
		}
	}
}
