package com.zcloud.controller.risk;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.risk.*;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.ImgFilesService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
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.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 说明：辨识部位
 * 作者：luoxiaobao
 * 时间：2020-12-30
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/identificationparts")
public class IdentificationPartsController extends BaseController {

    @Autowired
    private CorpInfoService corpInfoService;
    @Autowired
    private IdentificationPartsService identificationpartsService;
    @Autowired
    private RiskUnitService riskunitService;
    @Autowired
    private RiskPointService riskpointService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private IdeRepositoryService ideRepositoryService;
    @Autowired
    private RiskPointTemporaryService riskPointTemporaryService;
    @Autowired
    private RiskCheckItemService riskcheckitemService;
    @Autowired
    private ResourceCorpService resourceCorpService;
    @Autowired
    private ImgFilesService imgFilesService;
    @Autowired
    private Smb smb;
    @Autowired
    private UsersService usersService;

    /**
     * 新增
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    // @RequiresPermissions("identificationparts:add")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "双重预防", menuServer = "风险管控", instructionsOperate = "辨识部位", instructionsType = "新增")
    public Object add(@RequestParam(value = "FFILE", required = false) MultipartFile[] files) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();

        pd.put("CHECK_NAME", pd.getString("PARTSNAME"));
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd.put("RISK_UNIT_ID", pd.getString("RISK_UNIT_ID"));
        List<PageData> list = identificationpartsService.listAll(pd);
        if (list != null && list.size() > 0) {
            map.put("result", "failed");
            map.put("exception", "辨识部位已存在，请修改后重试");
            return map;
        }
        pd.put("IDENTIFICATIONPARTS_ID", this.get32UUID());    //主键

        pd.put("CREATOR", Jurisdiction.getUsername());    //添加人
        pd.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
        pd.put("OPERATOR", Jurisdiction.getUsername());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd.put("ISDELETE", "0");    //是否删除 1-是  0-否
        pd.put("ISMATCHING", "0");
        if (Tools.isEmpty(pd.getString("ELECTRONIC_FENCE_AREA_ID"))) {
            pd.put("ELECTRONIC_FENCE_NAME", null);
            pd.put("ELECTRONIC_FENCE_ID", null);
            pd.put("ELECTRONIC_FENCE_AREA_ID", null);
        }
        identificationpartsService.save(pd);

        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
//                 保存文件

                String ffile = DateUtil.getDays();
                String fileName = "";                //执0行上传

                if (null != file && !file.isEmpty()) {
                    fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    byte[] bytes = file.getBytes();
                    smb.sshSftp(file, fileName, Const.FILEPATHYHTP + ffile);
                }
                pd.put("IMGFILES_ID", this.get32UUID());
                pd.put("FILEPATH", Const.FILEPATHYHTP + ffile + "/" + fileName);
                pd.put("TYPE", 17);
                pd.put("FOREIGN_KEY", pd.get("IDENTIFICATIONPARTS_ID"));
                imgFilesService.save(pd);
            }
        }
        map.put("result", errInfo);
        return map;
    }

    /**
     * 获取风险点下拉框选项
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/getSelect")
    @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> unitList = riskunitService.listAll(pd);
        map.put("unitList", unitList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 删除
     *
     * @param out
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    // @RequiresPermissions("identificationparts: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();
        pd.put("CHECK_IDENTIFICATION_ID", pd.get("IDENTIFICATIONPARTS_ID"));
        List<PageData> list = riskpointService.listAll(pd);
        if (list != null && list.size() > 0) {
//			map.put("result", "failed");				//返回结果
            map.put("msg", "该辨识部位有风险管控台账，请删除所有的风险管控台账后再删除");
            return map;
        }
        pd.put("OPERATOR", Jurisdiction.getUsername());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        identificationpartsService.delete(pd);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 修改
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    // @RequiresPermissions("identificationparts:edit")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "双重预防", menuServer = "风险管控", instructionsOperate = "辨识部位", instructionsType = "修改")
    public Object edit(@RequestParam(value = "FFILE", required = false) MultipartFile[] files) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUsername());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        if (Tools.isEmpty(pd.getString("ELECTRONIC_FENCE_AREA_ID"))) {
            pd.put("ELECTRONIC_FENCE_NAME", null);
            pd.put("ELECTRONIC_FENCE_ID", null);
            pd.put("ELECTRONIC_FENCE_AREA_ID", null);
        }
        identificationpartsService.edit(pd);

        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
//                 保存文件

                String ffile = DateUtil.getDays();
                String fileName = "";                //执0行上传

                if (null != file && !file.isEmpty()) {
                    fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    byte[] bytes = file.getBytes();
                    smb.sshSftp(file, fileName, Const.FILEPATHYHTP + ffile);
                }
                pd.put("IMGFILES_ID", this.get32UUID());
                pd.put("FILEPATH", Const.FILEPATHYHTP + ffile + "/" + fileName);
                pd.put("TYPE", 17);
                pd.put("FOREIGN_KEY", pd.get("IDENTIFICATIONPARTS_ID"));
                imgFilesService.save(pd);
            }
        }
        map.put("result", errInfo);
        return map;
    }

//	/region/region/list

    /**
     * @Description: 电子围栏 来自人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/25/025 9:02
     * @Param: [com.zcloud.entity.Page] [page]
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/ryRegionList")
    @ResponseBody
    public Object ryRegionList(Page page) throws Exception {
        ReturnMap returnMap = new ReturnMap();
        PageData pageData = this.getPageData();
        String KEYWORDS = (String) pageData.getOrDefault("KEYWORDS", "");
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        if ("1".equals(Jurisdiction.getSession().getAttribute("PERSONNEL_POSITION"))) {
            return ReturnMap.ok();
        }
        try {
            // 进行远程调用
            JSONObject body = PLSUtil.getRyRegionList(Jurisdiction.getCORPINFO_ID(), KEYWORDS, Integer.parseInt(pageData.getString("currentPage")), Integer.parseInt(pageData.getString("showCount")), 0);
            List<JSONObject> list = body.getJSONArray("rows").toJavaList(JSONObject.class);
            returnMap.put("varList", list);
            page.setTotalResult(body.getIntValue("total"));
            returnMap.put("page", page);
        } catch (Exception e) {
            returnMap.put("webSiteStatus", "1");
        }

        return returnMap;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    // @RequiresPermissions("identificationparts: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");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) npd.put("KEYWORDS", KEYWORDS.trim());
        npd.put("ISMAIN", Jurisdiction.getIS_MAIN());
        npd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
        npd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
        npd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_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);
            }
        }
        page.setPd(npd);

        List<PageData> varList = identificationpartsService.list(page);    //列出IdentificationParts列表
        int hasJur = resourceCorpService.countByCorpId(pd);
        if (varList != null && varList.size() > 0) {
            for (PageData var : varList) {
                PageData pd2 = new PageData();
                pd2.put("FOREIGN_KEY", var.getString("IDENTIFICATIONPARTS_ID"));
                List<PageData> imgs = imgFilesService.listAll(pd2);
                var.put("imgs", imgs);
            }
        }
        map.put("varList", varList);
        map.put("hasJur", hasJur > 0 ? "1" : "0");
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/listAll")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "隐患排查", instructionsOperate = "清单管理", instructionsType = "列表")
    public Object listAll(Page page) 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> partsList = identificationpartsService.listAll(pd);
        map.put("partsList", partsList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/listAllByIdens")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "隐患排查", instructionsOperate = "清单管理", instructionsType = "列表")
    public Object listAllByIdens(Page page) 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("IDS");
        if (Tools.notEmpty(DATA_IDS)) {
            String ArrayDATA_IDS[] = DATA_IDS.split(",");
            pd.put("ArrayDATA_IDS", ArrayDATA_IDS);
            List<PageData> varList = identificationpartsService.listAllByIdens(pd);
            errInfo = "success";
            map.put("varList", varList);
        } else {
            errInfo = "error";
        }
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业
        List<PageData> partsList = identificationpartsService.listAll(pd);
        map.put("partsList", partsList);
        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 = identificationpartsService.findById(pd);    //根据ID读取

        PageData pd2 = new PageData();
        pd2.put("FOREIGN_KEY", pd.getString("IDENTIFICATIONPARTS_ID"));
        pd2.put("TYPE", pd.get("TYPE"));
        List<PageData> imgs = imgFilesService.listAll(pd2);//营业执照图片

        map.put("pd", pd);
        map.put("imgs", imgs);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 批量删除
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/deleteAll")
    // @RequiresPermissions("identificationparts: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(",");
            for (String id : ArrayDATA_IDS) {
                PageData iden = new PageData();
                iden.put("CHECK_IDENTIFICATION_ID", id);
                List<PageData> list = riskpointService.listAll(iden);
                if (list != null && list.size() > 0) {
//			map.put("result", "failed");				//返回结果
                    map.put("msg", "该辨识部位下还有风险管控台账，请先删除风险管控台账");
                    return map;
                }
                pd.put("IDENTIFICATIONPARTS_ID", id);
                pd.put("OPERATOR", Jurisdiction.getUsername());    //修改人
                pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
                identificationpartsService.delete(pd);
            }
//			identificationpartsService.deleteAll(ArrayDATA_IDS);
            errInfo = "success";
        } else {
            errInfo = "error";
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }


    @RequestMapping(value = "/resourceConfig")
    @ResponseBody
    public Object resourceConfig() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业
            String DATA_IDS = pd.getString("DATA_IDS");// 勾选的资源库ID集合
            List<String> idList = new ArrayList<String>();
            if (Tools.notEmpty(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                for (String id : ArrayDATA_IDS) {
                    idList.add(id);
                }
            }
            List<PageData> allRisk = riskPointTemporaryService.listAllByIdeAndTime(pd);

            String riskPointCountString = riskpointService.countByCorpInfo(pd);
            Integer count = Integer.parseInt(riskPointCountString);
            if (allRisk != null && allRisk.size() > 0) {
                List<String> deleteIds = new ArrayList<String>();

                for (PageData risk : allRisk) {
                    deleteIds.add(risk.get("RISKPOINTTEMPORARY_ID").toString());
                    if ("1".equals(risk.get("TYPE").toString())) { // 原有风险因素修改
                        risk.put("RISKPOINT_ID", risk.get("RES_ID"));
                        riskpointService.edit(risk);
                        // 修改冗余字段检查内容
                        PageData pd2 = new PageData();
                        pd2.put("CHECK_CONTENT", risk.get("MEASURES"));
                        pd2.put("RISKPOINT_ID", risk.get("RISKPOINT_ID"));
                        riskcheckitemService.editByPoint(pd2);
                    } else {// 新增风险因素
                        risk.put("RISKPOINT_ID", this.get32UUID());    //主键
                        count++;
                        risk.put("SORT", count);
                        for (int i = 0; i < idList.size(); i++) {
                            if (idList.get(i).equals(risk.get("RES_ID").toString())) {
                                idList.remove(i);
                                break;
                            }
                        }
                        riskpointService.save(risk);
                        PageData item = new PageData();
                        item.put("RISKCHECKITEM_ID", this.get32UUID());    //主键
                        item.put("RISKPOINT_ID", risk.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", risk.get("MEASURES"));    //检查内容
                        riskcheckitemService.save(item);
                    }
                }
            }
            if (idList != null && idList.size() > 0) {
                //查询资源库信息
                List<PageData> resList = ideRepositoryService.listAllByIds(idList.toArray(new String[idList.size()]));
                if (resList != null && resList.size() > 0) {
                    for (PageData res : resList) {
                        res.put("RISKPOINT_ID", this.get32UUID());    //主键
                        res.put("RES_ID", res.get("IDEREPOSITORY_ID"));
                        res.put("RISK_UNIT_ID", pd.get("RISK_UNIT_ID"));
                        res.put("IDENTIFICATION_ID", pd.get("IDENTIFICATION_ID"));
                        res.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
                        res.put("USER_ID", pd.get("USER_ID"));
                        res.put("DEPARTMENT_ID", pd.get("DEPARTMENT_ID"));
                        res.put("CREATOR", Jurisdiction.getUsername());    //添加人
                        res.put("CREATTIME", DateUtil.date2Str(new Date()));    //创建时间
                        res.put("OPERATOR", Jurisdiction.getUsername());    //修改人
                        res.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
                        res.put("RES_ISDELETE", "0");
                        count++;
                        res.put("SORT", count);
                        riskpointService.save(res);
                        PageData item = new PageData();
                        item.put("RISKCHECKITEM_ID", this.get32UUID());    //主键
                        item.put("RISKPOINT_ID", res.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", res.get("MEASURES"));    //检查内容
                        riskcheckitemService.save(item);
                    }
                }
            }
            // 若未配置过资源库，修改辨识部位状态
            if (pd.get("ISMATCHING") != null && Tools.notEmpty(pd.get("ISMATCHING").toString()) && !"1".equals(pd.get("ISMATCHING").toString())) {  //修改匹配资源库状态
                pd.put("ISMATCHING", "1");
                pd.put("IDENTIFICATIONPARTS_ID", pd.get("IDENTIFICATION_ID"));
                identificationpartsService.editMatching(pd);
            }
            //删除风险因素临时表中已经使用过的数据
            riskPointTemporaryService.deleteAbandoned(pd);
        } catch (Exception e) {
            e.printStackTrace();
            errInfo = "error";
            map.put("result", errInfo);
        }

        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }


    /**
     * 导出到excel
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
//	// @RequiresPermissions("toExcel")
    public ModelAndView exportExcel() throws Exception {
        ModelAndView mv = new ModelAndView();
        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("ArrayDATA_IDS", ArrayDATA_IDS);
        }
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("所属企业");    //2
        titles.add("风险点（单元）");    //2
        titles.add("辨识部位");    //1
        dataMap.put("titles", titles);
        List<PageData> varOList = identificationpartsService.listOut(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"));        //6
            varList.add(vpd);
        }
        dataMap.put("varList", varList);
        ObjectExcelView erv = new ObjectExcelView();
        mv = new ModelAndView(erv, dataMap);
        return mv;
    }

    /**导出到excel
     * @param
     * @throws Exception
     */
//		@RequestMapping(value="/excelModel")
////		// @RequiresPermissions("toExcel")
//		public void exportExcelModel(HttpServletResponse response) throws Exception{
//
//			FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "identificationpartsExcelTemplate.xls", "identificationpartsExcelTemplate.xls");
//		}

    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel")
    @SuppressWarnings("unchecked")
    @ResponseBody
    @Transactional
    public Object readExcel(@RequestParam(value = "FFILE", required = false) MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        StringBuffer errorStr = new StringBuffer();
        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
            /**
             *
             *  所属部门 	风险点（单元）	辨识部位
             */

            List<PageData> saveList = new ArrayList<>();
            try {
                if (listPd.size() > 0) {
                    List<String> header = new ArrayList<>();
                    header.add("所属部门");
                    header.add("风险点（单元）");
                    header.add("辨识部位");
                    PageData pdCorpId = new PageData();
                    pdCorpId.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    pdCorpId.put("ISDELETE", "0");
                    List<PageData> departAll = departmentService.listAll(pdCorpId);
                    Map<String, Object> departMapAll = new HashMap<>();
                    for (PageData pageData : departAll) {
                        departMapAll.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
                    }
                    List<PageData> riskunitListAll = riskunitService.listAll(pdCorpId);
                    Map<String, Object> riskunitMapAll = new HashMap<>();
                    for (PageData pageData : riskunitListAll) {
                        riskunitMapAll.put(pageData.getString("DEPARTMENT_ID") + Tools.excelHandle(pageData.getString("RISKUNITNAME")), pageData);
                    }

                    List<PageData> identiListAll = identificationpartsService.listAll(pdCorpId);
                    Map<String, Object> identiMapAll = new HashMap<>();
                    for (PageData pageData : identiListAll) {
                        identiMapAll.put(pageData.getString("RISK_UNIT_ID") + Tools.excelHandle(pageData.getString("PARTSNAME")), pageData);
                    }
                    Map<String, Object> hasAgain = new HashMap<>();
                    int succeeNum = 1;
                    for (PageData lpd : listPd) {
                        succeeNum++;

                        for (int i = 0; i < header.size(); i++) {
                            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 departVar = Tools.isEmpty(lpd.get("var0")) ? "" : Tools.excelHandle(lpd.get("var0"));
                        String riskNameVar = Tools.isEmpty(lpd.get("var1")) ? "" : Tools.excelHandle(lpd.get("var1"));
                        String checkNameVar = Tools.isEmpty(lpd.get("var2")) ? "" : Tools.excelHandle(lpd.get("var2"));
                        if (hasAgain.containsKey(departVar + riskNameVar + checkNameVar)) {
                            errorStr.append("<p>第" + succeeNum + "行的" + "数据重复</p>");
                            continue;
                        }
                        hasAgain.put(departVar + riskNameVar + checkNameVar, "1");
                        if (!departMapAll.containsKey(departVar)) {
                            errorStr.append("<p>第" + succeeNum + "行:" + "未找到名称为\"" + departVar + "\"的" + header.get(0) + "</p>");
                            continue;
                        }
                        PageData depart = (PageData) departMapAll.get(departVar);
                        if (!riskunitMapAll.containsKey(depart.getString("DEPARTMENT_ID") + riskNameVar)) {
                            errorStr.append("<p>第" + succeeNum + "行:" + "在" + departVar + "部门下未找到名称为\"" + riskNameVar + "\"的" + header.get(1) + "</p>");
                            continue;
                        }
                        PageData risk = (PageData) riskunitMapAll.get(depart.getString("DEPARTMENT_ID") + riskNameVar);
                        if (identiMapAll.containsKey(risk.get("RISKUNIT_ID") + checkNameVar)) {
                            errorStr.append("<p>第" + succeeNum + "行:" + "发现已经存在\"" + riskNameVar + "-" + checkNameVar + "\"的" + header.get(2) + "</p>");
                            continue;
                        }
//							else {
//								System.out.println(succeeNum);
//							}

                        PageData identificationparts = new PageData();
                        identificationparts.put("RISK_UNIT_ID", risk.get("RISKUNIT_ID"));
                        identificationparts.put("PARTSNAME", lpd.get("var2"));
                        identificationparts.put("IDENTIFICATIONPARTS_ID", this.get32UUID());
                        identificationparts.put("ISDELETE", "0");
                        identificationparts.put("ISMATCHING", "0");
                        identificationparts.put("CREATOR", Jurisdiction.getUsername());
                        identificationparts.put("CREATTIME", DateUtil.date2Str(new Date()));
                        identificationparts.put("OPERATOR", Jurisdiction.getUsername());
                        identificationparts.put("OPERATTIME", DateUtil.date2Str(new Date()));
                        identificationparts.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                        saveList.add(identificationparts);

                    }
                    if (Tools.isEmpty(errorStr.toString())) {
                        for (PageData pageData : saveList) {
                            identificationpartsService.save(pageData);
                        }
                        errorStr.append("成功导入" + saveList.size() + "条数据!");
                    } else {
                        errInfo = "error";
                    }
                    FileUtils.deleteQuietly(tempFile);//删除临时文件
                } else {
                    map.put("result", "error");                //返回结果
                    map.put("resultStr", "Excel数据未空，请检查数据后，重新上传！");
                    FileUtils.deleteQuietly(tempFile);//删除临时文件
                    return map;
                }
            } catch (Exception e) {
                map.put("result", "error");                //返回结果
                map.put("resultStr", e.toString());
                FileUtils.deleteQuietly(tempFile);//删除临时文件
                return map;
            }
        }
        map.put("result", "success");                //返回结果
        map.put("resultType", errInfo);                //返回message类型
        map.put("isExcel", "1");                //返回类型
        map.put("resultStr", errorStr.toString());
        return map;
    }


    /**
     * 判断同一个风险点辨识部位名称是否重复
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/hasName")
    @ResponseBody
    public Object hasName() throws Exception {
        Map<String, Object> map = new HashMap<>();
        PageData pd = new PageData();
        pd = this.getPageData();
        String errInfo = "success";
        PageData identificationparts = new PageData();

        identificationparts.put("RISKUNIT_ID", pd.getString("RISK_UNIT_ID"));
        identificationparts.put("CHECK_NAME", pd.getString("name"));
        List<PageData> list = identificationpartsService.listAll(identificationparts);
        if (list.size() > 0) {
            errInfo = "error";
        }
        map.put("result", errInfo);                //返回结果
        map.put("count", list.size());
        return map;
    }


    /**
     * 去修改页面获取数据
     * <p>
     * 风险管控->辨识部位->匹配资源存在风险
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/goEditRes")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "风险管控", instructionsOperate = "辨识部位", instructionsType = "获取匹配资源存在风险数据")
    public Object goEditRes() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        Set<String> accidentSet = new HashSet<String>();
        String levelId = new String();

        List<String> rptIdList = new ArrayList<String>();// 编辑已存在风险因素后，生成的临时风险因素ID集合
        List<String> rptResIdList = new ArrayList<String>();// 编辑资源库后，生成的临时风险因素ID集合
        // 新添加临时风险因素列表
        List<PageData> rpTimeList = riskPointTemporaryService.listAllByTime(pd);
        if (rpTimeList != null & rpTimeList.size() > 0) {
            for (PageData pData : rpTimeList) {
                if (pData.get("ACCIDENTS_NAME") != null && Tools.notEmpty(pData.get("ACCIDENTS_NAME").toString())) {
                    String[] split = pData.get("ACCIDENTS_NAME").toString().split(",");
                    Set<String> accSet = new HashSet<String>(Arrays.asList(split));
                    accidentSet.addAll(accSet);
                }
                if (pData.get("LEVELID") != null && Tools.notEmpty(pData.get("LEVELID").toString())) {
                    if (levelId.compareTo(pData.get("LEVELID").toString()) < 0) {// 取最高级
                        levelId = pData.get("LEVELID").toString();
                    }
                }
                if (pData.get("TYPE") != null && Tools.notEmpty(pData.get("TYPE").toString())) {
                    if ("1".equals(pData.get("TYPE").toString())) {// 原数据是已存在风险因素
                        rptIdList.add(pData.get("RES_ID").toString());
                    } else if ("2".equals(pData.get("TYPE").toString())) { // 原数据是资源库
                        rptResIdList.add(pData.get("RES_ID").toString());
                    }
                }
            }
        }
        if (rptIdList != null && rptIdList.size() > 0) {
            pd.put("rptIds", rptIdList.toArray());
        }

        // 自定义风险因素列表
        pd.put("CHECK_IDENTIFICATION_ID", pd.get("IDENTIFICATIONPARTS_ID"));
        List<PageData> riskPointList = riskpointService.listAllToRes(pd);

        if (riskPointList != null & riskPointList.size() > 0) {
            for (PageData pData : riskPointList) {
                if (pData.get("ACCIDENTS_NAME") != null && Tools.notEmpty(pData.get("ACCIDENTS_NAME").toString())) {
                    String[] split = pData.get("ACCIDENTS_NAME").toString().split(",");
                    Set<String> accSet = new HashSet<String>(Arrays.asList(split));
                    accidentSet.addAll(accSet);
                }
                if (pData.get("LEVELID") != null && Tools.notEmpty(pData.get("LEVELID").toString())) {
                    if (levelId.compareTo(pData.get("LEVELID").toString()) < 0) {// 取最高级
                        levelId = pData.get("LEVELID").toString();
                    }
                }
                // 将已经保存的资源库数据排除
                if (pData.get("RES_ID") != null && Tools.notEmpty(pData.get("RES_ID").toString())) {
                    rptResIdList.add(pData.get("RES_ID").toString());
                }
            }
        }

        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业
        PageData corp = corpInfoService.findById(pd);
        // 资源库列表
        pd.put("CORP_TYPE", corp.get("CORP_TYPE"));
        pd.put("CORP_TYPE2", corp.get("CORP_TYPE2"));
        pd.put("CORP_TYPE3", corp.get("CORP_TYPE3"));
        pd.put("CORP_TYPE4", corp.get("CORP_TYPE4"));
        //查询资源库使用状态是否为启用
        int count = resourceCorpService.countByCorpId(pd);
        if (count != 0) {
            // 将查询条件单拿出来
            // change by liu jun description:梦姐提的新需求：[只匹配辨识部位名称，不需匹配风险点（单元）]（禅道编号：8290）
            PageData condition = new PageData();
            // 公司的行业类型
            condition.put("CORP_TYPE", pd.get("CORP_TYPE"));
            condition.put("CORP_TYPE2", pd.get("CORP_TYPE2"));
            condition.put("CORP_TYPE3", pd.get("CORP_TYPE3"));
            condition.put("CORP_TYPE4", pd.get("CORP_TYPE4"));
            // 辨识部位
            condition.put("IDENTIFICATION", pd.get("IDENTIFICATION"));
            List<PageData> ideResList = ideRepositoryService.listAll(condition);
            // add by liu jun description:根据公司的行业类型一级一级的匹配。从第四级开始匹配，如果第四级没有数据，就匹配第三级以此类推
            if (ideResList == null || ideResList.size() == 0) {
                condition.put("CORP_TYPE4", "");
                ideResList = ideRepositoryService.listAll(condition);
                if (ideResList == null || ideResList.size() == 0) {
                    condition.put("CORP_TYPE3", "");
                    ideResList = ideRepositoryService.listAll(condition);
                    if (ideResList == null || ideResList.size() == 0) {
                        condition.put("CORP_TYPE2", "");
                        ideResList = ideRepositoryService.listAll(condition);
                        if (ideResList == null || ideResList.size() == 0) {
                            condition.put("CORP_TYPE", "");
                            ideResList = ideRepositoryService.listAll(condition);
                        }
                    }
                }
            }
            // 行业类型
            if (ideResList != null & ideResList.size() > 0) {
                for (PageData pData : ideResList) {
                    if (pData.get("ACCIDENTS_NAME") != null && Tools.notEmpty(pData.get("ACCIDENTS_NAME").toString())) {
                        String[] split = pData.get("ACCIDENTS_NAME").toString().split(",");
                        Set<String> accSet = new HashSet<String>(Arrays.asList(split));
                        accidentSet.addAll(accSet);
                    }
                    if (pData.get("LEVELID") != null && Tools.notEmpty(pData.get("LEVELID").toString())) {
                        if (levelId.compareTo(pData.get("LEVELID").toString()) > 0) {// 取最高级
                            levelId = pData.get("LEVELID").toString();
                        }
                    }
                }
            }
            map.put("ideResList", ideResList);
        }
        String accidents_name = String.join(",", accidentSet);
        pd = identificationpartsService.findById(pd);    //根据ID读取
        pd.put("ACCIDENTS_NAME", accidents_name);
        pd.put("LEVELID", levelId);
        map.put("pd", pd);
        map.put("riskPointList", riskPointList);
        map.put("rpTimeList", rpTimeList);
        map.put("result", errInfo);
        return map;
    }

}
