package com.testor.ddd.safetyControl.application.service.equipmentManage.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.DateUtil;
import com.testor.ddd.safetyControl.application.service.equipmentManage.EquipmentManageService;
import com.testor.ddd.safetyControl.application.service.equipmentManage.EquipmentTypeManageService;
import com.testor.ddd.safetyControl.application.service.riskPointManage.RiskPointManageService;
import com.testor.ddd.safetyControl.application.service.riskSourceManage.RiskSourceManageService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.domain.equipment.entity.TSafeEquipmentRepo;
import com.testor.ddd.safetyControl.domain.equipment.service.EquipmentService;
import com.testor.ddd.safetyControl.infrastructure.client.funConfClient.TableNumClient;
import com.testor.ddd.safetyControl.infrastructure.uitls.GenerateCode;
import com.testor.ddd.safetyControl.infrastructure.uitls.SpaceLevelEnum;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentTypeDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.EquipmentStatisticsVO;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.TSafeEquipmentTypeVO;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.TSafeEquipmentVO;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.testor.module.duty.util.PoiExcelUtils;
import com.testor.module.safe.model.dto.TSafeHazardOrgDTO;
import com.testor.module.safe.model.dto.TSafeHazardOrgParam;
import com.testor.module.safe.service.TSafeHazardOrgService;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckObject;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckPlan;
import com.testor.module.safeCheck.service.TSafeHazardCheckPlanService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EquipmentManageServiceImpl implements EquipmentManageService {
    @Resource
    private EquipmentService equipmentService;

    @Resource
    private TSafeEquipmentRepo tSafeEquipmentRepo;

    @Resource
    private TableNumClient tableNumClient;

    @Resource
    private GenerateCode generateCode;

    @Resource
    private SysOrgService orgService;

    @Resource
    private SpaceManageService spaceManageService;

    @Resource
    private EquipmentTypeManageService equipmentTypeManageService;

    @Resource
    private RiskSourceManageService riskSourceManageService;

    @Resource
    private RiskPointManageService riskPointManageService;

    @Resource
    private TSafeHazardCheckPlanService tSafeHazardCheckPlanService;

    @Resource
    private TSafeHazardOrgService tSafeHazardOrgService;

    /**
     * 编辑空间
     *
     * @param equipmentDto
     * @return
     */
    @Transactional
    public BaseResponse editEquipment(TSafeEquipmentDTO equipmentDto) {
        BaseResponse baseResponse = new BaseResponse<>();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();
        equipmentDto.setOrgId(curUserOrgId);

        String fieldName = null;
        boolean isGenerate = false; // 是否生成了编码
        if (StrUtil.isBlank(equipmentDto.getId())) { // 新增 生成编码
            fieldName = generateCode.generateEquipmentTableNumFieldName(equipmentDto);
            String code = generateCode.generateCodeByFieldName("t_safe_equipment", fieldName);
            equipmentDto.setCode(code);
            isGenerate = true;
        } else { // 编辑 不允许 修改 系统类型 或是 设备类型
            TSafeEquipmentDTO oldEquipmentDTO = equipmentService.findById(equipmentDto.getId());
            if (!oldEquipmentDTO.getSysTypeId().equals(equipmentDto.getSysTypeId())
                    || !oldEquipmentDTO.getEquipmentTypeId().equals(equipmentDto.getEquipmentTypeId())) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("所属的上级不允许修改");
                return baseResponse;
            }
        }

        baseResponse = equipmentService.editEquipment(curUser.getUserId(), curUserOrgId, equipmentDto);

        if (isGenerate && BaseStatusEnum.SUCCESS.code() == baseResponse.getCode().intValue()) {
            String code = equipmentDto.getCode();
            String[] codeArr = code.split("-");
            String maxNum = codeArr[codeArr.length - 1];
            tableNumClient.saveMaxNum("t_safe_equipment", fieldName, Integer.parseInt(maxNum));
        }
        return baseResponse;
    }


    public BaseResponseList<TSafeEquipmentVO> listByPage(TSafeEquipmentDTOParam param) {
//        if(StrUtil.isBlank(param.getOrgId()) &&
//                (param.getCondOrgIdList() == null || param.getCondOrgIdList().size() == 0)) {
//            UserInfo curUser = ContextUtils.getLoginUser();
//            String curUserOrgId = curUser.getOrgId();
//            param.setOrgId(curUserOrgId);
//        }
        return equipmentService.listByPage(param);
    }

    public TSafeEquipmentDTO findById(String id) {
        return tSafeEquipmentRepo.findById(id);
    }


    public TSafeEquipmentVO findDetailById(String id) {
        if (StrUtil.isBlank(id)) {
            return null;
        }
        return tSafeEquipmentRepo.findDetailById(id);
    }

    @Transactional
    public BaseResponse deleteById(String id) {
        BaseResponse baseResponse = new BaseResponse<>();
        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();
        TSafeEquipmentDTO oldEquipmentDto = tSafeEquipmentRepo.findById(id);
        if (!curUserOrgId.equals(oldEquipmentDto.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UNAUTHORIZED.code());
            baseResponse.setMsg("无权限操作");
            return baseResponse;
        }

        String checkMsg = checkDelete(id);
        if (!StrUtil.isBlank(checkMsg)) {
            baseResponse.setCode(BaseStatusEnum.UNAUTHORIZED.code());
            baseResponse.setMsg(checkMsg);
            return baseResponse;
        }
        oldEquipmentDto.setStatus(BizConstants.STATUS_DELETE);
        tSafeEquipmentRepo.updateById(oldEquipmentDto);

        //  删除 设备的关联影响
        deleteRelation(null, id);

        return baseResponse;
    }

    /**
     * 删除空间时：
     * 设备台账—若设备“安装位置-作业区域”字段所选空间为此区域，则自动删除此设备；
     *
     * @param spaceId
     * @return
     */
    @Transactional
    public boolean deleteBySpaceId(Integer type, String spaceId) {
//        tSafeEquipmentRepo.deleteBySpaceId(spaceId);
//        // 删除 设备的关联影响
//        deleteRelation(spaceId, null);

        TSafeEquipmentDTOParam param = new TSafeEquipmentDTOParam();
        param.setStatus(BizConstants.STATUS_ENABLE);
        if (type.intValue() == SpaceLevelEnum.workshop.getCode()) {
            param.setSpaceId(spaceId);
        }
        if (type.intValue() == SpaceLevelEnum.workarea.getCode()) {
            param.setSpaceAreaId(spaceId);
        }
        List<TSafeEquipmentDTO> equipmentDTOList = tSafeEquipmentRepo.listAllEntity(param);
        if (equipmentDTOList == null || equipmentDTOList.size() == 0) {
            return true;
        }

//        equipmentDTOList.parallelStream().forEach(item -> {
//            item.setStatus(BizConstants.STATUS_DELETE);
//            tSafeEquipmentRepo.updateById(item);
//
//            // 删除 设备的关联影响
//            deleteRelation(null, item.getId());
//        });
        for (TSafeEquipmentDTO dto : equipmentDTOList) {
            deleteById(dto.getId());
        }
        return true;
    }

    /**
     * 根据条件统计设备信息
     *
     * @param orgId
     * @return
     */
    public EquipmentStatisticsVO statisticsEquipment(String orgId) {
        if (StrUtil.isBlank(orgId)) {
            return null;
        }
        return equipmentService.statisticsEquipment(orgId);
    }

    @Transactional
    public Integer replaceCode(String spaceTypeId, String oldCode, String newCode) {
        return tSafeEquipmentRepo.replaceCode(spaceTypeId, oldCode, newCode);
    }

    /**
     * @param type   0-设备系统类型； 1-设备类型
     * @param typeId type=0 设备系统类型id; 1-设备类型   设备类型id
     * @return
     */
    @Transactional
    public boolean deleteByEquipmentType(int type, String typeId) {
        if (StrUtil.isBlank(typeId)) {
            return true;
        }
        TSafeEquipmentDTOParam param = new TSafeEquipmentDTOParam();
        param.setStatus(BizConstants.STATUS_ENABLE);
        if (type == 0) {
            param.setSysTypeId(typeId);
        } else if (type == 1) {
            param.setEquipmentTypeId(typeId);
        } else {
            return false;
        }

        List<TSafeEquipmentDTO> equipmentDTOList = tSafeEquipmentRepo.listAllEntity(param);
        if (equipmentDTOList == null || equipmentDTOList.size() == 0) {
            return true;
        }

//        equipmentDTOList.parallelStream().forEach(item -> {
//            item.setStatus(BizConstants.STATUS_DELETE);
//            tSafeEquipmentRepo.updateById(item);
//
//            // 删除 设备的关联影响
//            deleteRelation(null, item.getId());
//        });
        for (TSafeEquipmentDTO dto : equipmentDTOList) {
            deleteById(dto.getId());
        }
        return true;
    }

    /**
     * 删除 设备  及 关联影响
     *
     * @param id
     * @return
     */
    public boolean deleteRelation(String spaceId, String id) {

        int riskRelationType = 1;
        //  1）风险点—若危险源的“关联空间”字段所选空间为此作业区域，则删除此风险点；
        riskSourceManageService.deleteBySpaceOrEquipment(riskRelationType, id);
        //2）危险源—若风险点的“关联空间”字段所选空间为此作业区域，则删除此危险源；
        riskPointManageService.deleteBySpaceOrEquipment(riskRelationType, id);

        return true;
    }

    public String checkDelete(String equipmentId) {
        //  关联巡检计划、任务的判断
        //  此设备当前关联巡检计划，且巡检计划没有到达计划结束时间，
        //  或此巡检计划生成的巡检任务（存在巡检任务生成时间早于巡检计划的计划开始时间，
        //  巡检任务的结束时间晚于巡检计划的计划结束时间）没有完成，
        //  则此设备不得进行删除，进行删除则提示文案”此设备存在未完成的巡检任务或隐患排查工单，
        //  不得进行删除“。
        TSafeHazardCheckObject checkObject = new TSafeHazardCheckObject();
        checkObject.setObjId(equipmentId);
        List<TSafeHazardCheckPlan> checkPlanList = tSafeHazardCheckPlanService.findByObjectInfo(checkObject);
        if (checkPlanList != null && checkPlanList.size() > 0) {
            return "此设备存在未完成的巡检任务或隐患排查工单,不得进行删除";
        }
        //  此设备当前关联隐患，
        //  且隐患状态不为“已完成”或“已关闭”，则此设备不得进行删除，
        //  进行删除则提示文案“此设备存在未完成的巡检任务或隐患排查工单，不得进行删除”。
        List<String> notInStatusList = new ArrayList<>();
        notInStatusList.add("4");
        notInStatusList.add("5");
        TSafeHazardOrgParam safeHazardOrgParam = new TSafeHazardOrgParam();
        safeHazardOrgParam.setProcessNotInStatusList(notInStatusList);
        safeHazardOrgParam.setEquipment(equipmentId);
        BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> hazardOrgResult = tSafeHazardOrgService.listEntity(safeHazardOrgParam);
        if (hazardOrgResult != null && hazardOrgResult.getData() != null && hazardOrgResult.getData().getTotal() > 0) {
            return "此设备存在未完成的巡检任务或隐患排查工单,不得进行删除";
        }
        return null;
    }

    /**
     * 导入设备
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Transactional
    public BaseResponse<String> importEquipment(MultipartFile file) throws IOException {
        BaseResponse<String> baseResponse = new BaseResponse<>();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();
        SysOrg org = orgService.getById(curUserOrgId);
        String curUserOrgCode = org.getOrgCode();

        //判断是否为null
        if (file == null || file.getSize() <= 0) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("上传文件数据错误");
            return baseResponse;
        }
        InputStream inputStream = null;
        Workbook workbook = null;

        StringBuilder sbMsg = new StringBuilder();

        try {
            inputStream = file.getInputStream();
            // 读取Excel⽂件⼯作表
            workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
            //取得第⼀个⼯作表
            Sheet sheet = workbook.getSheetAt(0);
            Row row = sheet.getRow(2);
            //报表上传的没条数据
            List<Map<Integer, Object>> dataList = PoiExcelUtils.getBody(sheet, 10, 2);
            System.out.println(JSON.toJSONString(dataList));

            if (dataList == null || dataList.size() == 0) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("请填写数据");
                return baseResponse;
            }

            List<TSafeEquipmentDTO> equipmentDTOList = new ArrayList<>();
            TSafeEquipmentDTO equipmentDTO;
            int index = 2;
            DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
            // key: workareaCode(作业区域编码); value: workshopId-workareaId(车间场所id-作业区间id) 。 根据类型code获取类型id
            Map<String, String> spaceMap = new HashMap<>();
            // key: equipmentName; value: index 。判断重名
            Map<String, Integer> equipmentNameMap = new HashMap<>();
            // key: equipmentTypeCode(设备类型编码); value: sysTypeId-equipmentTypeId(系统类型id-设备类型id) 。 根据类型code获取类型id
            Map<String, String> equipmentTypeMap = new HashMap<>();
            // key: equipmentTypeCode(设备类型编码); value: fieldName 。根据类型code 生成对应的table_ fieldName 的最大值
            Map<String, String> tableFieldNameMap = new HashMap<>();
            // key: fieldName; value: num 。根据类型code获取 对应的table_num 的最大值
            Map<String, Integer> tabeNumMap = new HashMap<>();
            //  for (WorkshopImportEntity rowData : workshopImportList) {
            for (Map<Integer, Object> rowData : dataList) {
                index++;
                // 车间场所名称、类型编码不为空
                if (rowData.get(1) == null || StrUtil.isBlank(rowData.get(1).toString()) ||
                        rowData.get(2) == null || StrUtil.isBlank(rowData.get(2).toString()) ||
                        rowData.get(4) == null || StrUtil.isBlank(rowData.get(4).toString()) ||
                        rowData.get(5) == null || StrUtil.isBlank(rowData.get(5).toString()) ||
                        //  rowData.get(7) == null  || StrUtil.isBlank(rowData.get(7).toString()) ||
                        rowData.get(9) == null || StrUtil.isBlank(rowData.get(9).toString())) {
                    sbMsg.append("第" + index + "条数据，参数缺失；\n");
                    continue;
                }

                // 判断企业编码与当前用户所属企业编码是否相同
                String orgCode = rowData.get(1).toString();
                String equipmentName = rowData.get(2).toString();
                String equipmentTypeCode = rowData.get(4).toString();
                String isSpecial = rowData.get(5).toString();
                String validityDateStr = null;
                if ("是".equals(isSpecial)) {
                    if (rowData.get(6) == null) {
                        sbMsg.append("第" + index + "条数据，参数缺失；\n");
                        continue;
                    }
                    validityDateStr = rowData.get(6).toString();
                    isSpecial = "1";
                } else {
                    isSpecial = "0";
                }

                // todo  图片暂不处理
                Object imgData = rowData.get(7);

                String workareaCode = rowData.get(9).toString();

                //组织机构编码判断
                if (StrUtil.isBlank(orgCode)) {
                    orgCode = curUserOrgCode;
                }
                if (!curUserOrgCode.equals(orgCode)) {
                    sbMsg.append("第" + index + "条数据，设备[" + equipmentName + "]当前用户无权操作；\n");
                    continue;
                }

                // 检测 相同类型下 是否存在重名的
                String key = equipmentTypeCode + "-" + equipmentName;
                if (equipmentNameMap.get(key) != null) {
                    sbMsg.append("第" + index + "条数据 与 第" + equipmentNameMap.get(key) + "条重名，请修改第" + index + "条数据作；\n");
                    continue;
                } else {
                    equipmentNameMap.put(key, index);
                }

                // 根据作业区域 获取 作业区域id、车间场所id
                String workshopId = null;
                String workareaId = null;
                if (spaceMap.get(workareaCode) == null) {
                    TSafeSpaceDTOParam spaceDTOParam = new TSafeSpaceDTOParam();
                    spaceDTOParam.setOrgId(curUserOrgId);
                    spaceDTOParam.setStatus(BizConstants.STATUS_ENABLE);
                    spaceDTOParam.setLevel(SpaceLevelEnum.workarea.getCode());
                    spaceDTOParam.setCode(workareaCode);
                    BaseResponseList<TSafeSpaceVO> spaceVOList = spaceManageService.listByPage(spaceDTOParam);
                    if (spaceVOList == null || spaceVOList.getData() == null || spaceVOList.getData().size() == 0) {
                        sbMsg.append("第" + index + "条数据，设备[" + equipmentName + "]所属的作业区域编码无效；\n");
                        continue;
                    }
                    TSafeSpaceVO spaceVO = spaceVOList.getData().get(0);
                    workareaId = spaceVO.getId();
                    workshopId = spaceVO.getSpaceId();
                    spaceMap.put(workareaCode, workshopId + "-" + workareaId);
                } else {
                    String idStr = spaceMap.get(workareaCode);
                    workshopId = idStr.split("-")[0];
                    workareaId = idStr.split("-")[1];
                }

                // 根据 设备类型编码 获取 设备类型id、 系统类型id
                String equipmentTypeId = null;
                String sysTypeId = null;
                Integer curNum = null;
                String fieldName = null;
                if (equipmentTypeMap.get(equipmentTypeCode) == null) {
                    TSafeEquipmentTypeDTOParam equipmentTypeDTOParam = new TSafeEquipmentTypeDTOParam();
                    //  equipmentTypeDTOParam.setOrgId(orgCode);
                    equipmentTypeDTOParam.setStatus(BizConstants.STATUS_ENABLE);
                    equipmentTypeDTOParam.setCode(equipmentTypeCode);
                    equipmentTypeDTOParam.setNoParentId("0");
                    BaseResponseList<TSafeEquipmentTypeVO> equipmentTypeVOList = equipmentTypeManageService.listByPage(equipmentTypeDTOParam);
                    if (equipmentTypeVOList == null || equipmentTypeVOList.getData() == null || equipmentTypeVOList.getData().size() == 0) {
                        sbMsg.append("第" + index + "条数据，设备[" + equipmentName + "]所属的设备类型编码无效；\n");
                        continue;
                    }
                    TSafeEquipmentTypeVO equipmentTypeVO = equipmentTypeVOList.getData().get(0);
                    equipmentTypeId = equipmentTypeVO.getId();
                    sysTypeId = equipmentTypeVO.getParentId();
                    equipmentTypeMap.put(equipmentTypeCode, sysTypeId + "-" + equipmentTypeId);

                    // 查询此 类型 下的最大编码数
                    fieldName = orgCode + "-" + equipmentTypeVO.getParentCode() + "-" + equipmentTypeCode;
                    tableFieldNameMap.put(equipmentTypeCode, fieldName);
                    Integer maxNum = tableNumClient.obtainMaxNum("t_safe_equipment", fieldName);
                    curNum = maxNum == null ? 1 : maxNum + 1;
                } else {
                    String[] idsStr = equipmentTypeMap.get(equipmentTypeCode).split("-");
                    sysTypeId = idsStr[0];
                    equipmentTypeId = idsStr[1];
                    fieldName = tableFieldNameMap.get(equipmentTypeCode);
                    curNum = tabeNumMap.get(fieldName) + 1;
                }
                tabeNumMap.put(fieldName, curNum);

                String equipmentCode = fieldName + "-" + curNum;
                boolean checkResult = equipmentService.checkUniqueness(null, equipmentTypeId, equipmentName, equipmentCode);
                if (!checkResult) {
                    sbMsg.append("第" + index + "条数据，设备[" + equipmentName + "]在库中已存在；\n");
                    continue;
                }


                equipmentDTO = new TSafeEquipmentDTO();
                equipmentDTO.setOrgId(curUserOrgId);
                equipmentDTO.setName(equipmentName);
                equipmentDTO.setSpaceId(workshopId);
                equipmentDTO.setSpaceAreaId(workareaId);
                equipmentDTO.setEquipmentTypeId(equipmentTypeId);
                equipmentDTO.setSysTypeId(sysTypeId);
                equipmentDTO.setCode(equipmentCode);
                equipmentDTO.setIsSpecial(isSpecial);
                //  equipmentDTO.setValidityDate(validityDateStr);
                try {
                    if ("1".equals(isSpecial)) {
                        equipmentDTO.setValidityDate(DateUtil.localDateTimeToDate(LocalDateTime.parse(rowData.get(6).toString(), timeDtf)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
                    baseResponse.setData(null);
                    baseResponse.setMsg("检测有效期时间格式错误，请参照填写说明填写！");
                    return baseResponse;
                }
                equipmentDTOList.add(equipmentDTO);
            }

            if (equipmentDTOList == null || equipmentDTOList.size() == 0) {
                if (sbMsg == null) {
                    return baseResponse;
                } else {
                    baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
                    baseResponse.setMsg(sbMsg.toString());
                    return baseResponse;
                }
            }

            boolean result = tSafeEquipmentRepo.saveBatch(equipmentDTOList);
            if (!result) {
                throw new BusinessException("导入失败");
            }

            // 保持 table_num 表
            for (Map.Entry<String, Integer> entry : tabeNumMap.entrySet()) {
                // System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                tableNumClient.saveMaxNum("t_safe_equipment", entry.getKey(), entry.getValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setData(null);
            baseResponse.setMsg("导入失败，参数异常");
            return baseResponse;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (workbook != null) {
                workbook.close();
            }
        }
        baseResponse.setData(sbMsg == null ? "导入成功" : sbMsg.toString());
        return baseResponse;
    }

    /**
     * 设备列表 （安全风险 拉下数据）
     *
     * @param param
     * @return
     */
    public List<TSafeEquipmentVO> listForRisk(TSafeEquipmentDTOParam param) {
        return tSafeEquipmentRepo.listForRisk(param);
    }
}
