package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.excel.ExplicitConstraint;
import com.yeejoin.amos.boot.module.common.api.feign.PrivilegeFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.*;
import com.yeejoin.amos.boot.module.jcs.api.dto.SignDto;
import com.yeejoin.amos.feign.privilege.model.GroupUserModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.QRCodeUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.FireChemical;
import com.yeejoin.amos.boot.module.common.api.entity.FireExperts;
import com.yeejoin.amos.boot.module.common.api.entity.FireStation;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContacts;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersEducation;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersPost;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersWorkexperience;
import com.yeejoin.amos.boot.module.common.api.entity.MaintenanceCompany;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.entity.RescueEquipment;
import com.yeejoin.amos.boot.module.common.api.entity.SpecialPositionStaff;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyCarServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyPersonServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyPersonShiftServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyShiftServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormColumnServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireChemicalServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireExpertsServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireStationServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersContactsServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersEducationServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersPostServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersWorkexperienceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.LinkageUnitServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.RescueEquipmentServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SpecialPositionStaffServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.WaterResourceServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.AircraftDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.OrgUsrSafeReportExcelDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Aircraft;
import com.yeejoin.amos.boot.module.jcs.api.entity.OrgUsrSafeReport;
import com.yeejoin.amos.boot.module.jcs.api.enums.ExcelEnums;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.core.io.Resource;
/**
 * @author tb
 */
@Service
public class ExcelServiceImpl {
	private final Logger logger = LoggerFactory.getLogger(OrgUsrServiceImpl.class);
	private static final String NOT_DUTY = "休班";
	private static final String PERSON = "PERSON";
	private static final String MAINTENANCE_PERSON = "maintenancePerson";

	@Autowired
	DataSourcesImpl dataSourcesImpl;
	@Autowired
	FireChemicalServiceImpl fireChemicalServiceImpl;
	@Autowired
	FireExpertsServiceImpl fireExpertsServiceImpl;
	@Autowired
	WaterResourceServiceImpl waterResourceServiceImpl;
	@Autowired
	AircraftServiceImpl aircraftServiceImpl;
	@Autowired
	FireTeamServiceImpl fireTeamService;
	@Autowired
	FireStationServiceImpl fireStationService;
	@Autowired
	FirefightersServiceImpl firefightersService;
	@Autowired
	IMaintenanceCompanyService maintenanceCompanyService;
	@Autowired
	IKeySiteService keySiteService;
	@Autowired
	DutyCarServiceImpl dutyCarService;
	@Autowired
	DutyPersonServiceImpl dutyPersonService;
	@Autowired
	Sequence sequence;
	@Autowired
	DynamicFormColumnServiceImpl dynamicFormColumnService;
	@Autowired
	DutyPersonShiftServiceImpl dutyPersonShiftService;
	@Autowired
	OrgUsrServiceImpl orgUsrService;
	@Autowired
	DutyShiftServiceImpl dutyShiftService;
	@Autowired
	IDutyPersonService iDutyPersonService;
	@Autowired
	DataDictionaryServiceImpl dataDictionaryService;
	@Autowired
	DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;
	@Autowired
	LinkageUnitServiceImpl linkageUnitServiceImpl;
	@Autowired
	SpecialPositionStaffServiceImpl specialPositionStaffServiceImpl;
	@Autowired
	RescueEquipmentServiceImpl rescueEquipmentServiceImpl;
	@Autowired
	IOrgUsrService orgUsrServer;
	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;

	@Autowired
	FirefightersPostServiceImpl iFirefightersPostService;
	@Autowired
	FirefightersContactsServiceImpl ifirefightersContactsService;
	@Autowired
	FirefightersEducationServiceImpl ifirefightersEducationService;
	@Autowired
	FirefightersWorkexperienceServiceImpl ifirefightersWorkexperienceService;

	@Autowired
	IDutyFireFightingService dutyFireFightingService;

	@Autowired
	OrgUsrSafeReportServiceImpl orgUsrSafeReportService;

	@Autowired
	IDutyFirstAidService dutyFirstAidService;

	@Autowired
	DynamicFormInstanceServiceImpl dynamicFormInstanceService;

	@Autowired
	private OrgUsrMapper orgUsrMapper;

	@Autowired
	private IDataSyncService dataSyncService;

	@Autowired
    PrivilegeFeignClient privilegeFeignClient;
    @Autowired
    ApplicationContext applicationContext;

	@Value("${logic}")
	Boolean logic;

	@Autowired
	SignServiceImpl signServiceImpl;


	private static final String GENDER="gender";

	private static final String INSTANCEID="instanceId";

	private static final String INAGREEMENT="inAgreement";

	private static final String JCDWRY="JCDWRY";


    @Value("classpath:/json/userData.json")
    private Resource areaRes;



	public void templateExport(HttpServletResponse response, ExcelDto excelDto) throws ClassNotFoundException {
		String url = excelDto.getClassUrl();
		Class<?> clz = Class.forName(url);
		ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz, dataSourcesImpl,
				true);
	}

	public void commonExport(HttpServletResponse response, ExcelDto excelDto, Map par) {
		//效验参数
		boolean authFlag = true;
		if (!"QDSJ".equals(excelDto.getType())) {
			authFlag = getFlag(par);
		}

		switch (excelDto.getType()) {

		case "WHP":
			List<FireChemicalDto> data = null;
			if(par.size()>0) {
				data = fireChemicalServiceImpl.queryForFireChemicalList(par.containsKey("casNo")?par.get("casNo").toString():null,par.containsKey("formula")?par.get("formula").toString():null,
						par.containsKey("name")?par.get("name").toString():null,par.containsKey("typeCode")?par.get("typeCode").toString():null,false);
			}else{
				data = fireChemicalServiceImpl.queryForFireChemicalList(null,null,null,null,false);
			}
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
					FireChemicalDto.class, dataSourcesImpl, false);
			break;
		case "XFZJ":
			List<FireExpertsDto> fireExpertsDtoList =null;
			if(par.size()>0) {
			  fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false,par.containsKey("name")?par.get("name").toString():null,par.containsKey("expertCode")?par.get("expertCode").toString():null,par.containsKey("bizOrgCode")?par.get("bizOrgCode").toString():null);
			}else{
				  fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false,null,null, null);
			}
			QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("type", "XLLX");
			List<DataDictionary> list = iDataDictionaryService.list(queryWrapper);
			for (FireExpertsDto fireExpertsDto : fireExpertsDtoList) {
				for (DataDictionary dataDictionary : list) {
					if (fireExpertsDto.getHighestEducation() != null
							&& !fireExpertsDto.getHighestEducation().equals("")) {
						if (fireExpertsDto.getHighestEducation().equals(dataDictionary.getCode())) {
							fireExpertsDto.setHighestEducation(dataDictionary.getName());
						}
					}
				}
			}
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireExpertsDtoList,
					FireExpertsDto.class, dataSourcesImpl, false);
			break;
		case "SYXX":
			// 暂时先还原代码不加 “非” ，为修改bug http://36.46.149.14:5080/zentao/task-view-6974.html 水源导出没有数据问题
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						WaterResourceDto.class, dataSourcesImpl, false);
				break;
			}
			List<WaterResourceForExportDto> waterResourceDtoList = null;
			if(par.size()>0) {
				waterResourceDtoList = waterResourceServiceImpl.exportToExcel(true,par.containsKey("name")?par.get("name").toString():null,
						par.containsKey("equipCateGoryCode")?par.get("equipCateGoryCode").toString():null,par.containsKey("bizOrgCode")?par.get("bizOrgCode").toString():null);
			}else{
				waterResourceDtoList = waterResourceServiceImpl.exportToExcel(true,null,null,par.containsKey("bizOrgCode")?par.get("bizOrgCode").toString():null);
			}
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), waterResourceDtoList,
					WaterResourceForExportDto.class, dataSourcesImpl, false);
			break;
		case "HKQ":
			List<AircraftDto> aircraftDtoList = null;
			if(par.size()>0) {
				aircraftDtoList = aircraftServiceImpl.queryAircraftDtoForList(false,par.containsKey("aircraftModel")?par.get("aircraftModel").toString():null,
						par.containsKey("engineTypeCode")?par.get("engineTypeCode").toString():null,par.containsKey("fuelTypeCode")?par.get("fuelTypeCode").toString():null);
			}else{
				aircraftDtoList = aircraftServiceImpl.queryAircraftDtoForList(false,null,null,null);
			}
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), aircraftDtoList,
					AircraftDto.class, dataSourcesImpl, false);
			break;
		case "XFDW":
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						FireTeamDto.class, dataSourcesImpl, false);
				break;
			}
			List<FireTeamDto> fireTeamDtoList = fireTeamService.queryFireTeamForList(false, par);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireTeamDtoList,
					FireTeamDto.class, dataSourcesImpl, false);
			break;
		case "WXXFZ":
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						FireStationDto.class, null, false);
				break;
			}
            String nameString =null;
            Long bizCompanyId =null;
			if(par!=null && par.size()>0) {
				nameString =par.containsKey("name")?par.get("name").toString():null;
				bizCompanyId =par.containsKey("bizCompanyId")?Long.parseLong(par.get("bizCompanyId").toString()):null;
			}
			List<FireStationDto> fireStationDtoList = fireStationService.queryForFireStationList(false, bizCompanyId,nameString,par.containsKey("bizOrgCode")?par.get("bizOrgCode").toString():null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireStationDtoList,
					FireStationDto.class, null, false);
			break;
		case "XFRY":
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
						null, FirefightersExcelDto.class, null, false);
				break;
			}
			List<OrgUsrFireExcelDto> firefightersExcelDtoList = firefightersService.exportToExcelNew(false, par);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
					firefightersExcelDtoList, OrgUsrFireExcelDto.class, null, false);
			break;
		case "WBRY":
			List<MaintenancePersonExcleDto> maintenancePersonExcelDtoList = maintenanceCompanyService
					.exportToMaintenancePersonExcel(par);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
					maintenancePersonExcelDtoList, MaintenancePersonExcleDto.class, null, false);
			break;
		case "QDSJ":
			SignDto dto = new SignDto();
			String fileName=null;
			if(par!=null && par.size()>0) {

				String date =par.containsKey("date")?par.get("date").toString():null;
				String bizOrgName =par.containsKey("bizOrgName")?par.get("bizOrgName").toString():null;
				String name =par.containsKey("name")?par.get("name").toString():null;
				String type =par.containsKey("type")?par.get("type").toString():null;
				String signTimeBIGGER =par.containsKey("signTimeBIGGER")?par.get("signTimeBIGGER").toString():null;
				String signTimeLESS =par.containsKey("signTimeLESS")?par.get("signTimeLESS").toString():null;
				ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
				dto.setBizOrgCode(reginParams.getPersonIdentity().getCompanyBizOrgCode());
				dto.setDate(date);
				dto.setBizOrgName(bizOrgName);
				dto.setName(name);
				dto.setSignTimeBIGGER(signTimeBIGGER);
				dto.setSignTimeLESS(signTimeLESS);
				dto.setType(type);
                //区分统计和签到
				if(!par.containsKey("current")){
					OrgUsr orgUsr1 = orgUsrMapper.queryByBizCode(reginParams.getPersonIdentity().getCompanyBizOrgCode());
					fileName="【"+orgUsr1.getBizOrgName()+"】-【"+date+"】·消防人员出勤明细";
				}
			}
			Page<SignDto> page = new Page<>();
			page.setCurrent(1);
			page.setSize(-1);
			IPage<SignDto> signDtos = signServiceImpl
					.queryForSignPageByMapper(page,dto);
			signDtos.getRecords().stream().forEach(e->{
				e.setType(e.getType().equals("0") ? "上班打卡" :"下班打卡" );
			});

			ExcelUtil.createTemplate(response, fileName!=null?fileName:excelDto.getFileName(), excelDto.getSheetName(),
					signDtos.getRecords(), SignDto.class, null, false);
			break;
		case "KEYSITE":
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						KeySiteExcleDto.class, null, false);
				break;
			}
			List<KeySiteExcleDto> keySiteDtoList = null;
			if(par.size()>0 && par.containsKey("bizOrgCode")&&!par.get("bizOrgCode").equals("undefined")) {
				keySiteDtoList = keySiteService.exportToExcel(par.containsKey("name")?par.get("name").toString():null,
						par.containsKey("buildingId")?Long.valueOf(par.get("buildingId").toString()):null,
						par.containsKey("fireEnduranceRate")?par.get("fireEnduranceRate").toString():null,
						par.containsKey("useNature")?par.get("useNature").toString():null,
						par.containsKey("fireFacilitiesInfo")?par.get("fireFacilitiesInfo").toString():null,
						par.containsKey("bizOrgCode")? par.get("bizOrgCode").toString():null);
			}
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), keySiteDtoList,
					KeySiteExcleDto.class, null, false);
			break;
		case JCDWRY:
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						OrgUsrExcelDto.class, null, false);
				break;
			}
			List<OrgUsrExcelDto> orgUsrList = orgUsrService.exportToExcel(par);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), orgUsrList,
					OrgUsrExcelDto.class, null, false);
			break;
		case "DLDWRY":
			if(!authFlag) {
				ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null,
						OrgUsrDlExcelDto.class, null, false);
				break;
			}
			List<OrgUsrExcelDto> orgUsrDlList = orgUsrService.exportToExcel(par);
			String content = JSON.toJSONString(orgUsrDlList);
			List<OrgUsrDlExcelDto> dtoList = JSON.parseArray(content, OrgUsrDlExcelDto.class);

			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), dtoList,
					OrgUsrDlExcelDto.class, null, false);
			break;
		case "LDDW":
			List<LinkageUnitDto> LinkageUnitDtoList = null;
			String inAgreement = par.containsKey(INAGREEMENT)&&!(par.get(INAGREEMENT).toString()).equals("null")?par.get(INAGREEMENT).toString():"";

			if(par.size()>0) {
				LinkageUnitDtoList = linkageUnitServiceImpl.exportToExcel(par.containsKey("unitName")?par.get("unitName").toString():null,
						par.containsKey("linkageUnitTypeCode")?par.get("linkageUnitTypeCode").toString():null,
						par.containsKey("emergencyLinkageUnitCode")?par.get("emergencyLinkageUnitCode").toString():null,
						par.containsKey("bizOrgCode")?par.get("bizOrgCode").toString():null
						);
			}else{
				LinkageUnitDtoList = linkageUnitServiceImpl.exportToExcel(null,null,null, null);
			}

			List<Map> linkageUnitListMap =JSON.parseArray(JSON.toJSONString(LinkageUnitDtoList), Map.class);

			List<Map<String, Object>> pageList = dynamicFormInstanceService.listAll("linkageUnit");


			linkageUnitListMap.forEach(i -> {
				if ( i.get(INSTANCEID) != null){
					String mainString = i.get(INSTANCEID).toString();
					pageList.stream().forEach(detail -> {
						if (detail.get(INSTANCEID).toString().equals(mainString)) {
							i.putAll(detail);
						}
					});
				}
			});
			List<LinkageUnitDto> resultDtoList = JSON.parseArray(JSON.toJSONString(linkageUnitListMap),
					LinkageUnitDto.class);
			List<LinkageUnitDto> detaiList = resultDtoList.stream().map(item -> {
				Date now = new Date();

				boolean isInAgreement = DateUtils.belongCalendar(now, item.getAgreementStartDate(),
						item.getAgreementEndDate());
				item.setInAgreement(isInAgreement ? "是" : "否");
				return item;
			}).filter(item -> org.apache.commons.lang3.StringUtils.isEmpty(inAgreement) || inAgreement.equals(item.getInAgreement()))
					.collect(Collectors.toList());
			/*经纬度导出精度会丢失 转换成string导出 2021-11-02 陈召 开始*/
			List<LinkageUnitVo> result = new ArrayList<>();
			detaiList.forEach(d->{
				LinkageUnitVo linkageUnitVo = new LinkageUnitVo();
				BeanUtils.copyProperties(d,linkageUnitVo);
				linkageUnitVo.setLatitude(d.getLatitude() != null? String.valueOf(d.getLatitude()):" ");
				linkageUnitVo.setLongitude(d.getLongitude() != null?String.valueOf(d.getLongitude()):" ");
				result.add(linkageUnitVo);
			});
			/*经纬度导出精度会丢失 转换成string导出 2021-11-02 陈召 结束*/
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), result,
					LinkageUnitVo.class, null, false);
			break;
		default:
			break;
		}
	}


	@Transactional
	public Object commonUpload(MultipartFile multipartFile, ExcelDto excelDto, String uuidString, HttpServletRequest equest) throws Exception {
		switch (excelDto.getType()) {

		case "WHP":
			excelImportFireChemical(multipartFile);
			break;
		case "XFZJ":
			excelImportFireExperts(multipartFile);
			break;
		case "SYXX":
			excelImportWaterResource(multipartFile);
			break;
		case "HKQ":
			excelImportAircraft(multipartFile);
			break;
		case "XFDW":
			excelImportFireTeam(multipartFile);
			break;
		case "WXXFZ":
			excelImportFireStation(multipartFile);
			break;
		case "XFRY":
			excelImportFirefighters(multipartFile);
			break;
		case "CLZQ":
			excelImportDutyPerson(multipartFile, "CLZQ",uuidString);
			break;
		case "RYZB":
			excelImportDutyPerson(multipartFile, "RYZB",uuidString);
			break;
		case "WBRY":
			excelImportMaintenancePerson(multipartFile);
			break;
		case "KEYSITE":
			excelImportKeySite(multipartFile);
			break;
		case JCDWRY:

		case "DLDWRY":
			excelImportOrgUsrExcelDtoNew(multipartFile);
			break;
		case "LDDW":
			excelImportLinkageUnitZhDto(multipartFile);
			break;
		case "TGRY":
			excelImportLinkageUnitTGRYDto(multipartFile);
			break;
		case "JYZB":
			excelImportLinkageUnitJYZBDto(multipartFile);
			break;
		case "WXXFZB":
			excelImportDutyPerson(multipartFile, "WXXFZB",uuidString);
			break;
		case "XFAQBG":
			excelImportSafeReport(multipartFile);
			break;
		case "JJZB":
			excelImportDutyPerson(multipartFile, "JJZB",uuidString);
            break;
        case "JCDWRYTP":
            return excelImportOrgUsrTPExcelDtoNew(multipartFile,equest);
		}
		return null;
	}
    @Transactional
	public void excelImportLinkageUnitTGRYDto(MultipartFile multipartFile) throws Exception {

		List<SpecialPositionStaffDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
				SpecialPositionStaffDto.class, 1);

		if (excelDtoList != null && excelDtoList.size() > 0) {
			outer: for (SpecialPositionStaffDto positionStaffDto : excelDtoList) {
				String code = "";
				if (positionStaffDto.getPositionName() != null) {
					String[] certificates = positionStaffDto.getPositionName().split("@");
					positionStaffDto.setPositionName(certificates[0]);
					positionStaffDto.setPositionNameCode(certificates[1]);
					code = certificates[1];
				} else {
					continue;
				}
				if (positionStaffDto.getCompany() != null) {
					String[] certificates = positionStaffDto.getCompany().split("@");
					positionStaffDto.setCompany(certificates[0]);
					positionStaffDto.setCompanyId(Long.parseLong(certificates[1]));
					// 获取特岗人员已经存在的岗位 如果存在则不导入
					LambdaQueryWrapper<SpecialPositionStaff> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(SpecialPositionStaff::getCompanyId, Long.parseLong(certificates[1]))
							.eq(SpecialPositionStaff::getIsDelete, false);
					List<SpecialPositionStaff> tempList = specialPositionStaffServiceImpl.list(queryWrapper);
					for (SpecialPositionStaff temp : tempList) {
						if (temp.getPositionNameCode().equals(code)) {
							continue outer; // 已经存在则不导入继续循环
						}
					}
				} else {
					continue;
				}
				positionStaffDto = Bean.toPo(getCurrentInfo(), positionStaffDto);
				specialPositionStaffServiceImpl.createWithModel(positionStaffDto);
			}
		}
	}
    @Transactional
    public void excelImportLinkageUnitJYZBDto(MultipartFile multipartFile) throws Exception {
		List<RescueEquipmentDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, RescueEquipmentDto.class,
				1);
		if (excelDtoList != null && excelDtoList.size() > 0) {
			outer: for (RescueEquipmentDto rescueEquipmentDto : excelDtoList) {
				String code = "";
				if (rescueEquipmentDto.getVehicleType() != null) {
					String[] certificates = rescueEquipmentDto.getVehicleType().split("@");
					rescueEquipmentDto.setVehicleType(certificates[0]);
					rescueEquipmentDto.setVehicleTypeCode(certificates[1]);
					code = certificates[1];
				} else {
					continue;
				}
				if (rescueEquipmentDto.getCompany() != null) {
					String[] certificates = rescueEquipmentDto.getCompany().split("@");
					rescueEquipmentDto.setCompany(certificates[0]);
					rescueEquipmentDto.setCompanyId(Long.parseLong(certificates[1]));
					// 获取救援装备已经存在的装备 如果存在则不导入
					LambdaQueryWrapper<RescueEquipment> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(RescueEquipment::getCompanyId, Long.parseLong(certificates[1]))
							.eq(RescueEquipment::getIsDelete, false);
					List<RescueEquipment> tempList = rescueEquipmentServiceImpl.list(queryWrapper);
					for (RescueEquipment temp : tempList) {
						if (temp.getVehicleTypeCode().equals(code)) {
							continue outer; // 已经存在则不导入继续循环
						}
					}
				} else {
					continue;
				}
				rescueEquipmentDto = Bean.toPo(getCurrentInfo(), rescueEquipmentDto);
				rescueEquipmentServiceImpl.createWithModel(rescueEquipmentDto);
			}

		}
	}
    @Transactional
    public void excelImportLinkageUnitZhDto(MultipartFile multipartFile) throws Exception {
		List<LinkageUnitDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, LinkageUnitDto.class, 1);
		ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
		String companyId = reginParams.getPersonIdentity().getCompanyId();
		String bizOrgCode = "1";
		String bizOrgName = "1";
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(companyId)) {
			OrgUsr orgUsr = orgUsrMapper.queryBySequenceNbr(companyId);
			bizOrgCode = orgUsr.getBizOrgCode();
			bizOrgName = orgUsr.getBizOrgName();
		}
		if (excelDtoList != null && excelDtoList.size() > 0) {
			String finalBizOrgCode = bizOrgCode;
			String finalBizOrgName = bizOrgName;
			excelDtoList.forEach(linkageUnitDto -> {
				if (linkageUnitDto.getLinkageUnitType() != null) {
					String[] certificates = linkageUnitDto.getLinkageUnitType().split("@");
					linkageUnitDto.setLinkageUnitType(certificates[0]);
					linkageUnitDto.setLinkageUnitTypeCode(certificates[1]);
				}
				if (linkageUnitDto.getEmergencyLinkageUnit() != null) {
					String[] certificates = linkageUnitDto.getEmergencyLinkageUnit().split("@");
					linkageUnitDto.setEmergencyLinkageUnit(certificates[0]);
					linkageUnitDto.setEmergencyLinkageUnitCode(certificates[1]);
				}
				linkageUnitDto = Bean.toPo(getCurrentInfo(), linkageUnitDto);
				linkageUnitDto.setBizOrgCode(finalBizOrgCode);
				linkageUnitDto.setBizOrgName(finalBizOrgName);
				linkageUnitServiceImpl.saveLinkageModel(linkageUnitDto);
			});
		}

	}

	private void excelImportOrgUsrExcelDto(MultipartFile multipartFile) throws Exception {

		List<OrgUsrExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, OrgUsrExcelDto.class, 1);

		if (excelDtoList != null && excelDtoList.size() > 0) {
			excelDtoList.forEach(orgUsrExcelDto -> {
				if (orgUsrExcelDto.getParentId() != null) {
					String[] certificates = orgUsrExcelDto.getParentId().split("@");
					orgUsrExcelDto.setParentId(certificates[1]);
				}
				// 动态字段填充

				List<DynamicFormInitDto> dynamicFormColumn = dynamicFormColumnServiceImpl.getFormlist("246");

				List<DynamicFormInstanceDto> dynamicFormValue = new ArrayList<>();
				List<DynamicFormInstance> dynamicFormInstancelist = new ArrayList<>();

				dynamicFormColumn.forEach(DynamicFormInitDto -> {
					dynamicFormValue.add(DynamicFormInitDto.getFormItemDescr());
				});

				dynamicFormValue.forEach(dynamicFormInstanceDto -> {
					switch (dynamicFormInstanceDto.getFieldCode()) {
					case "administrativePositionCode":
						if (orgUsrExcelDto.getAdministrativePositionCode() != null) {
							String[] certificates = orgUsrExcelDto.getAdministrativePositionCode().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);
						}
						break;
					case "auditCycle":
						if (orgUsrExcelDto.getAuditCycle() != null) {
							String[] certificates = orgUsrExcelDto.getAuditCycle().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "certificatesNumber":
						dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getCertificatesNumber());
						break;
					case "certificatesTypeCode":
						if (orgUsrExcelDto.getCertificatesTypeCode() != null) {
							String[] certificates = orgUsrExcelDto.getCertificatesTypeCode().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "certificateType": // 持证类别
						if (orgUsrExcelDto.getCertificateType() != null) {
							String[] certificates = orgUsrExcelDto.getCertificateType().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);
						}
						break; // BUG 2892 导入机场单位没有持证类别和 人员性别 处理 by kongfm 2021-09-16
					case "fireManagementPostCode":
						if (orgUsrExcelDto.getFireManagementPostCode() != null) {
							String[] certificates = orgUsrExcelDto.getFireManagementPostCode().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);
						}
						break;
					case GENDER:
						if (orgUsrExcelDto.getGender() != null) {// BUG 2892 导入机场单位没有持证类别和 人员性别 处理 by kongfm 2021-09-16
							String[] gender = orgUsrExcelDto.getGender().split("@");
							dynamicFormInstanceDto.setFieldValue(gender[1]);
							dynamicFormInstanceDto.setFieldValueLabel(gender[0]);
						}
						break;
					case "internalPositionCode":
						if (orgUsrExcelDto.getInternalPositionCode() != null) {
							String[] certificates = orgUsrExcelDto.getInternalPositionCode().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "personNumber":
						dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getPersonNumber());
						break;
					case "positionType":
						if (orgUsrExcelDto.getPositionType() != null) {
							String[] certificates = orgUsrExcelDto.getPositionType().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "safetyTraining":
						if (orgUsrExcelDto.getSafetyTraining() != null) {
							String[] certificates = orgUsrExcelDto.getSafetyTraining().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "stateCode":
						if (orgUsrExcelDto.getStateCode() != null) {
							String[] certificates = orgUsrExcelDto.getStateCode().split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);

						}
						break;
					case "telephone":
						dynamicFormInstanceDto.setFieldValue(orgUsrExcelDto.getTelephone());
						break;

					}

					DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
					BeanUtils.copyProperties(dynamicFormInstanceDto, dynamicFormInstance);
					dynamicFormInstancelist.add(dynamicFormInstance);

				});
				orgUsrExcelDto.setDynamicFormValue(dynamicFormInstancelist);
				Bean.toPo(getCurrentInfo(), orgUsrExcelDto);
				try {
					orgUsrService.saveOrgPersonExcel(orgUsrExcelDto);
				} catch (Exception e) {
					throw new BadRequest("导入失败!");
				}
			});
		}

	}
    @Transactional
    public void excelImportOrgUsrExcelDtoNew(MultipartFile multipartFile) throws Exception {
		List<OrgUsrExcelDto> excelDtoList = new ArrayList<>();
		if (!logic){
			List<OrgUsrDlExcelDto> list = ExcelUtil.readFirstSheetExcel(multipartFile, OrgUsrDlExcelDto.class, 1);
			if (list.size() > 0) {
				String s = JSON.toJSONString(list);
				List<OrgUsrExcelDto> list1 = JSON.parseArray(s, OrgUsrExcelDto.class);
				excelDtoList.addAll(list1);
			}
		}else {
			List<OrgUsrExcelDto> list = ExcelUtil.readFirstSheetExcel(multipartFile, OrgUsrExcelDto.class, 1);
			if (list.size() > 0){
				excelDtoList.addAll(list);
			}
		}
		if (!ObjectUtils.isEmpty(excelDtoList)) {
			Set<String> set = new HashSet<>();
			Set<String> set1 = new HashSet<>();
			excelDtoList.forEach(orgUsrExcelDto -> {
				if (orgUsrExcelDto.getParentId() != null) {
					String[] certificates = orgUsrExcelDto.getParentId().split("@");
					orgUsrExcelDto.setParentName(certificates[0]);
					orgUsrExcelDto.setParentId(certificates[1]);
				}
				if (orgUsrExcelDto.getAmosOrgCode() != null) {
					String[] certificates = orgUsrExcelDto.getAmosOrgCode().split("@");
					orgUsrExcelDto.setAmosOrgId(certificates[0]);
					orgUsrExcelDto.setAmosOrgCode(certificates[1]);
				}
				// 动态字段填充
				List<DynamicFormInitDto> dynamicFormColumn = dynamicFormColumnServiceImpl.getFormlist("246");
				Map<String, Object> map = new HashMap<>();
				// 获取对象属性和值
				Field[] fields = orgUsrExcelDto.getClass().getDeclaredFields();
				for (Field field : fields) {
					try{
						field.setAccessible(true);
						Object value = field.get(orgUsrExcelDto);
						String name = field.getName();
						// 解析注解信息
						ExplicitConstraint explicitConstraint = field.getAnnotation(ExplicitConstraint.class);
						if (!ObjectUtils.isEmpty(explicitConstraint)) {
							name = name + "@";
						}
						map.put(name, value);
					}	catch (Exception ex){
						logger.error("获取{}字段值失败, {}", field.getName(), ex);
					}
				}
				String s = JSON.toJSONString(orgUsrExcelDto);
				Map<String,Object> map1 = JSON.parseObject(s, Map.class);
				List<DynamicFormInstanceDto> dynamicFormValue = new ArrayList<>();
				List<DynamicFormInstance> dynamicFormInstancelist = new ArrayList<>();

				dynamicFormColumn.forEach(DynamicFormInitDto -> {
					if ("birthdayTime".equals(DynamicFormInitDto.getKey())) {
						DynamicFormInstanceDto formItemDescr = DynamicFormInitDto.getFormItemDescr();
						formItemDescr.setFieldValue(null);
						DynamicFormInitDto.setFormItemDescr(formItemDescr);
					}
					if (GENDER.equals(DynamicFormInitDto.getKey())){
						DynamicFormInstanceDto formItemDescr = DynamicFormInitDto.getFormItemDescr();
						formItemDescr.setFieldValue(null);
						DynamicFormInitDto.setFormItemDescr(formItemDescr);
					}
					dynamicFormValue.add(DynamicFormInitDto.getFormItemDescr());
				});
				dynamicFormValue.forEach(dynamicFormInstanceDto -> {
					String key = dynamicFormInstanceDto.getFieldCode();

					if (map1.containsKey(key) && !ObjectUtils.isEmpty(map1.get(key))){
						String value = map1.get(key).toString();
						if (value.contains("@")) {
							String[] certificates = value.split("@");
							dynamicFormInstanceDto.setFieldValue(certificates[1]);
							dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);
						} else {
							dynamicFormInstanceDto.setFieldValue(value);
						}
					}
					if (map.containsKey(key) &&  map.get(key) != null&&("birthdayTime".equals(key) || "holdingTime".equals(key) )){

							Date o = (Date) map.get(key);
							SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
							String format = dtf.format(o);
							try {
								dynamicFormInstanceDto.setFieldValue(format);
							} catch (Exception e) {
								logger.error("日期转换失败");
								throw new BadRequest("出生日期格式不对!");
							}

					}

					DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
					BeanUtils.copyProperties(dynamicFormInstanceDto, dynamicFormInstance);
					String fieldCode = dynamicFormInstance.getFieldCode();
					if (map1.containsKey(fieldCode.substring(0,fieldCode.length()-4)) && map1.get(fieldCode.substring(0,fieldCode.length()-4)) != null){
						dynamicFormInstance.setFieldValueLabel(map1.get(fieldCode.substring(0,fieldCode.length()-4)).toString());
					}
					if (GENDER.equals(dynamicFormInstance.getFieldCode()) && !ObjectUtils.isEmpty(dynamicFormInstance.getFieldValue())){
						dynamicFormInstance.setFieldValueLabel("346".equals(String.valueOf(dynamicFormInstance.getFieldValue()))?"男":"女");
					}
					if ("positionType".equals(dynamicFormInstance.getFieldCode()) && !ObjectUtils.isEmpty(dynamicFormInstance.getFieldValue())){
						dynamicFormInstance.setFieldValueLabel(dataDictionaryService.getById(dynamicFormInstance.getFieldValue()).getName());
					}
					if ("certificatesTypeCode".equals(fieldCode) && !ObjectUtils.isEmpty(map1.get(fieldCode))){
						String[] split = map1.get(fieldCode).toString().split("@");
						dynamicFormInstance.setFieldValue(split[1]);
						dynamicFormInstance.setFieldValueLabel(split[0]);}
					if ("residenceDetailsCode".equals(fieldCode) && map1.get("residenceDetails") != null) {
						String[] residenceDetails = map1.get("residenceDetails").toString().split("@");
						dynamicFormInstance.setFieldValue(residenceDetails[1]);
						dynamicFormInstance.setFieldValueLabel(residenceDetails[0]);
					}
					if ("nativePlaceCode".equals(fieldCode)&& map1.get("nativePlace") != null){
						String[] split = map1.get("nativePlace").toString().split("@");
						dynamicFormInstance.setFieldValue(split[1]);
						dynamicFormInstance.setFieldValueLabel(split[0]);}

					dynamicFormInstancelist.add(dynamicFormInstance);
				});

				orgUsrExcelDto.setDynamicFormValue(dynamicFormInstancelist);
				Bean.toPo(getCurrentInfo(), orgUsrExcelDto);
				// 保存动态表单和人员单位表
				if (!ObjectUtils.isEmpty(orgUsrExcelDto.getCertificatesTypeCode())){
					String[] split55 = orgUsrExcelDto.getCertificatesTypeCode().toString().split("@");
					if (!ObjectUtils.isEmpty(orgUsrExcelDto.getCertificatesNumber())&&split55[1].equals("120")) {
						if (!set.add(orgUsrExcelDto.getCertificatesNumber())) {
							throw new BadRequest("身份证号码重复!");
						} else {
							boolean b = orgUsrService.checkCertificatesNumber(orgUsrExcelDto.getCertificatesNumber(), null);
							if (b) {
								throw new BadRequest("身份证号码重复!");
							}
						}
					}
				}

				//平台用户唯一效验
				if (!ObjectUtils.isEmpty(orgUsrExcelDto.getAmosOrgId())) {
					if (!set1.add(orgUsrExcelDto.getAmosOrgId())) {
						throw new BadRequest("关联用户"+orgUsrExcelDto.getAmosOrgCode()+"重复!");
					} else {
						int num = orgUsrMapper.amosIdExist(orgUsrExcelDto.getAmosOrgId(),null);

						if (num > 0) {
							throw new BadRequest("关联用户"+orgUsrExcelDto.getAmosOrgCode()+"重复!");
						}
					}
				}
				try {
					OrgUsrDto orgUsrDto = orgUsrService.saveOrgPersonExcel(orgUsrExcelDto);
					if (!ObjectUtils.isEmpty(orgUsrDto)) {
						// 保存其余项
						orgUsrExcelDto.setOrgUsrId(orgUsrDto.getSequenceNbr().toString());
						savePeopleItem(orgUsrExcelDto);
						//  巡检站端与中心级数据同步
						TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
							@Override
							public void afterCommit() {
								// 事物提交后业务逻辑
								dataSyncService.OrgUsrSyncDtoDataSync(orgUsrDto.getSequenceNbr());
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new BadRequest("导入失败!");
				}
			});
		}
	}

     //调用平台创建用户
    private Map<String,Object> createUser(OrgUserVO agencyUser,List<StringBuilder> falseData,String appKey,String product,String token){
        LinkedHashMap<String, Object> user=null;
        try {
            //同步平台
            ResponseModel<Object> amosUser = privilegeFeignClient.create(
                    appKey,
                    product,
                    token,agencyUser);
            if (!ObjectUtils.isEmpty(amosUser)) {
                logger.info("添加用户结果"+(amosUser!=null?JSON.toJSONString(amosUser):""));
                if(amosUser.getStatus()==200){
                    user = (LinkedHashMap<String, Object>) amosUser.getResult();
                }else{
                    StringBuilder falsest=new  StringBuilder();
                    falsest.append("用户:").append(agencyUser.getRealName()).append("同步平台失败，").append(amosUser.getMessage());
                    falseData.add(falsest);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }
    //用户添加用户组
    private List<Map<String, Object>> groupUser(Long group,String  agencyUser,String appKey,String product,String token){
        List<Map<String, Object>> user=null;
        try {
            //同步平台
            List<String> li=new ArrayList<>();
            li.add(agencyUser);
            ResponseModel<Object> amosUser = privilegeFeignClient.groupUser(
                    appKey,
                    product,
                    token,
                    group,li);

            logger.info("添加用户组结果"+(amosUser!=null?JSON.toJSONString(amosUser):""));

            if (!ObjectUtils.isEmpty(amosUser)&&amosUser.getStatus()==200) {
                user = (List<Map<String, Object>>) amosUser.getResult();
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    private boolean setcreateUser(OrgUsrTPDlExcelDto orgUsrExcelDto,List<StringBuilder> falseData,String appKey,String product,String token,List<UserVO> listUser,String companySeqs){
        boolean flag=true;
       try {
        //创建平台用户
        OrgUserVO user=new OrgUserVO();
        //组装参数
       Long group=null;
        user.setCompanySeqs(companySeqs);
        if (!StringUtils.isEmpty(orgUsrExcelDto.getDeptSeqs())){
			String[] split = orgUsrExcelDto.getDeptSeqs().split("@");
			user.setDeptSeqs(split[1]);
		}
        user.setEmail(orgUsrExcelDto.getEmail());
        user.setLockStatus("UNLOCK");
           for (UserVO userVO : listUser) {
               if(userVO.getType().equals(orgUsrExcelDto.getUserType())){
                   Map<String,List<String>>  orgRoleSeqs=new HashMap<>();
				   if (!StringUtils.isEmpty(orgUsrExcelDto.getDeptSeqs())) {
					   orgRoleSeqs.put(orgUsrExcelDto.getDeptSeqs().split("@")[1],userVO.getRoleSeqs());
				   }
                   user.setOrgRoleSeqs(orgRoleSeqs);
                   user.setAppCodes(userVO.getAppCodes());
                   user.setRoleSeqs(userVO.getRoleSeqs());
                   group=Long.valueOf(userVO.getGroup());
               }
           }
        //密码效验加密,不能为空，并且必须相等
        if(!StringUtils.isEmpty(orgUsrExcelDto.getPassword())){
            user.setPassword(DesUtil.encode(orgUsrExcelDto.getPassword(), "qaz"));
            user.setRePassword(DesUtil.encode(orgUsrExcelDto.getPassword(), "qaz"));
        }else{
            StringBuilder falsest=new  StringBuilder();
            falsest.append("用户:").append(orgUsrExcelDto.getBizOrgName()).append(",两次密码不能为空并且必须相等！");
            falseData.add(falsest);
            flag=false;
            return flag;
        }
        user.setRealName(orgUsrExcelDto.getBizOrgName());
        user.setUserName(orgUsrExcelDto.getUserName());

        //平台创建用户
        Map<String,Object> userModel=this.createUser(user, falseData,appKey,
                product,
                token);
        if(userModel==null){
            flag=false;
            return flag;
        }
        //用户权限组分配
        List<Map<String, Object>>   groupUserModel = this.groupUser(group,userModel.get("userId").toString(),appKey,
                product,
                token);
        if(groupUserModel==null){
            StringBuilder falsest1=new  StringBuilder();
            falsest1.append("用户:").append(orgUsrExcelDto.getBizOrgName()).append(",分配用户组失败！");
            falseData.add(falsest1);
            flag=false;
            return flag;
        }
        orgUsrExcelDto.setAmosOrgId(userModel.get("userId").toString());
        orgUsrExcelDto.setAmosOrgCode(userModel.get("userName").toString());
       }catch (Exception e){
           StringBuilder falsest1=new  StringBuilder();
           falsest1.append("用户:").append(orgUsrExcelDto.getBizOrgName()).append(",请求接口异常失败！");
           falseData.add(falsest1);
           flag=false;
           e.printStackTrace();
       }
        return flag;
    }


    private  String excelImportOrgUsrTPExcelDtoNew(MultipartFile multipartFile,HttpServletRequest request)  {
        List<OrgUsrTPDlExcelDto> excelDtoList=null;
        List<UserVO> mapList =null;
        try {
            //读取excel
            excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, OrgUsrTPDlExcelDto.class, 1);
        }catch (Exception e){
            e.printStackTrace();
            //捕获异常，记录失败
            throw new BadRequest("解析异常！");
        }
        String key=UUID.randomUUID().toString();
        String json = null;
        try {
            json = IOUtils.toString(areaRes.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
             mapList = JSON.parseArray(json, UserVO.class);
            //判断数据
            if (ObjectUtils.isEmpty(excelDtoList)) {
                throw new BadRequest("数据为空!");
            }
            ExcelServiceImpl   bean=applicationContext.getBean(ExcelServiceImpl.class);
            ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            String sequenceNbr = reginParams.getCompany().getSequenceNbr().toString();
            //异步处理
            String appKey = request.getHeader("appKey");
            String product = request.getHeader("product");
            String token = request.getHeader("token");

            bean.syssaveuser(excelDtoList,appKey,
                    product,
                    token,key,mapList,sequenceNbr);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BadRequest("解析异常！");
        }





        return key;
    }
    //异步处理流程
    @Async
    public void syssaveuser(List<OrgUsrTPDlExcelDto> excelDtoList,String appKey,String product,String token,String key,List<UserVO> listUser,String sequenceNbr ){
        Map<String,Object> map=new HashMap<String,Object>();
        Set<String> set = new HashSet<>();
        //成功数据标记
        List<StringBuilder> trueData=new ArrayList<>();
        //失败数据标记
        List<StringBuilder> falseData=new ArrayList<>();
        int num=0;
        map.put("znum",excelDtoList.size());
        for (OrgUsrTPDlExcelDto orgUsrExcelDto : excelDtoList) {
            //成功日志
            StringBuilder truest =new StringBuilder();
            //失败日志
            StringBuilder falsest =new StringBuilder();
            //同步平台，绑定用户组
            boolean fa= this.setcreateUser(orgUsrExcelDto,falseData,appKey,
                    product,
                    token,listUser,sequenceNbr);
                if(!fa){
                    //失败跳过此条
                    num=num+1;
                    map.put("trueData",trueData);
                    map.put("falseData",falseData);
                    map.put("falsenum",falseData.size());
                    map.put("truenum",trueData.size());
                    map.put("num",num);
                    redisUtils.set(key,map,1200);
                    continue;
                }

            //业务用户添加
            try {
                //设置平台用户
                this.saveuser(orgUsrExcelDto, set,appKey,
                        product,
                        token);
            }catch (Exception e){

                falsest.append("用户:").append(orgUsrExcelDto.getBizOrgName()).append(",添加机场单位人员失败！");
                falseData.add(falsest);
                e.printStackTrace();
            }
            truest.append("用户:").append(orgUsrExcelDto.getBizOrgName()).append(",添加成功！");
            trueData.add(truest);
            num=num+1;
            map.put("trueData",trueData);
            map.put("falseData",falseData);
            map.put("falsenum",falseData.size());
            map.put("truenum",trueData.size());
            map.put("num",num);
            redisUtils.set(key,map,1200);
            logger.info("导入结果"+key+JSON.toJSONString(map));
        };


    }






//业务用户添加，保持原来逻辑不变
private void saveuser(OrgUsrTPDlExcelDto orgUsrExcelDto,Set<String> set,String appKey,String product,String token){

    if (orgUsrExcelDto.getParentId() != null) {
        String[] certificates = orgUsrExcelDto.getParentId().split("@");
        orgUsrExcelDto.setParentName(certificates[0]);
        orgUsrExcelDto.setParentId(certificates[1]);
    }

    // 动态字段填充
    List<DynamicFormInitDto> dynamicFormColumn = dynamicFormColumnServiceImpl.getFormlist("246");
    Map<String, Object> map = new HashMap<>();
    // 获取对象属性和值
    Field[] fields = orgUsrExcelDto.getClass().getDeclaredFields();
    for (Field field : fields) {
        try{
            field.setAccessible(true);
            Object value = field.get(orgUsrExcelDto);
            String name = field.getName();
            // 解析注解信息
            ExplicitConstraint explicitConstraint = field.getAnnotation(ExplicitConstraint.class);
            if (!ObjectUtils.isEmpty(explicitConstraint)) {
                name = name + "@";
            }
            map.put(name, value);
        }	catch (Exception ex){
            logger.error("获取{}字段值失败, {}", field.getName(), ex);
        }
    }
    String s = JSON.toJSONString(orgUsrExcelDto);
    Map<String,Object> map1 = JSON.parseObject(s, Map.class);
    List<DynamicFormInstanceDto> dynamicFormValue = new ArrayList<>();
    List<DynamicFormInstance> dynamicFormInstancelist = new ArrayList<>();

    dynamicFormColumn.forEach(DynamicFormInitDto -> {
        if ("birthdayTime".equals(DynamicFormInitDto.getKey())) {
            DynamicFormInstanceDto formItemDescr = DynamicFormInitDto.getFormItemDescr();
            formItemDescr.setFieldValue(null);
            DynamicFormInitDto.setFormItemDescr(formItemDescr);
        }
        if (GENDER.equals(DynamicFormInitDto.getKey())){
            DynamicFormInstanceDto formItemDescr = DynamicFormInitDto.getFormItemDescr();
            formItemDescr.setFieldValue(null);
            DynamicFormInitDto.setFormItemDescr(formItemDescr);
        }
        dynamicFormValue.add(DynamicFormInitDto.getFormItemDescr());
    });
    dynamicFormValue.forEach(dynamicFormInstanceDto -> {
        String key = dynamicFormInstanceDto.getFieldCode();

        if (map1.containsKey(key) && !ObjectUtils.isEmpty(map1.get(key))){
            String value = map1.get(key).toString();
            if (value.contains("@")) {
                String[] certificates = value.split("@");
                dynamicFormInstanceDto.setFieldValue(certificates[1]);
                dynamicFormInstanceDto.setFieldValueLabel(certificates[0]);
            } else {
                dynamicFormInstanceDto.setFieldValue(value);
            }
        }
        if (map.containsKey(key) &&  map.get(key) != null&&("birthdayTime".equals(key) || "holdingTime".equals(key) )){

            Date o = (Date) map.get(key);
            SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String format = dtf.format(o);
            try {
                dynamicFormInstanceDto.setFieldValue(format);
            } catch (Exception e) {
                logger.error("日期转换失败");
                throw new BadRequest("出生日期格式不对!");
            }

        }

        DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
        BeanUtils.copyProperties(dynamicFormInstanceDto, dynamicFormInstance);
        String fieldCode = dynamicFormInstance.getFieldCode();
        if (map1.containsKey(fieldCode.substring(0,fieldCode.length()-4)) && map1.get(fieldCode.substring(0,fieldCode.length()-4)) != null){
            dynamicFormInstance.setFieldValueLabel(map1.get(fieldCode.substring(0,fieldCode.length()-4)).toString());
        }
        if (GENDER.equals(dynamicFormInstance.getFieldCode()) && !ObjectUtils.isEmpty(dynamicFormInstance.getFieldValue())){
            dynamicFormInstance.setFieldValueLabel("346".equals(String.valueOf(dynamicFormInstance.getFieldValue()))?"男":"女");
        }
        if ("positionType".equals(dynamicFormInstance.getFieldCode()) && !ObjectUtils.isEmpty(dynamicFormInstance.getFieldValue())){
            dynamicFormInstance.setFieldValueLabel(dataDictionaryService.getById(dynamicFormInstance.getFieldValue()).getName());
        }
        if ("certificatesTypeCode".equals(fieldCode) && !ObjectUtils.isEmpty(map1.get(fieldCode))){
            String[] split = map1.get(fieldCode).toString().split("@");
            dynamicFormInstance.setFieldValue(split[1]);
            dynamicFormInstance.setFieldValueLabel(split[0]);}
        if ("residenceDetailsCode".equals(fieldCode) && map1.get("residenceDetails") != null) {
            String[] residenceDetails = map1.get("residenceDetails").toString().split("@");
            dynamicFormInstance.setFieldValue(residenceDetails[1]);
            dynamicFormInstance.setFieldValueLabel(residenceDetails[0]);
        }
        if ("nativePlaceCode".equals(fieldCode)&& map1.get("nativePlace") != null){
            String[] split = map1.get("nativePlace").toString().split("@");
            dynamicFormInstance.setFieldValue(split[1]);
            dynamicFormInstance.setFieldValueLabel(split[0]);}

        dynamicFormInstancelist.add(dynamicFormInstance);
    });

    orgUsrExcelDto.setDynamicFormValue(dynamicFormInstancelist);
    Bean.toPo(getCurrentInfoNew( appKey, product, token), orgUsrExcelDto);
    // 保存动态表单和人员单位表
    if (!ObjectUtils.isEmpty(orgUsrExcelDto.getCertificatesTypeCode())){
        String[] split55 = orgUsrExcelDto.getCertificatesTypeCode().toString().split("@");
        if (!ObjectUtils.isEmpty(orgUsrExcelDto.getCertificatesNumber())&&split55[1].equals("120")) {
            if (!set.add(orgUsrExcelDto.getCertificatesNumber())) {
                throw new BadRequest("身份证号码重复!");
            } else {
                boolean b = orgUsrService.checkCertificatesNumber(orgUsrExcelDto.getCertificatesNumber(), null);
                if (b) {
                    throw new BadRequest("身份证号码重复!");
                }
            }
        }
    }


    try {
        OrgUsrExcelDto orgUsrnew = new OrgUsrExcelDto();
        BeanUtils.copyProperties(orgUsrExcelDto, orgUsrnew);

        OrgUsrDto orgUsrDto = orgUsrService.saveOrgPersonExcel(orgUsrnew);
        if (!ObjectUtils.isEmpty(orgUsrDto)) {
            // 保存其余项
            orgUsrnew.setOrgUsrId(orgUsrDto.getSequenceNbr().toString());
            savePeopleItem(orgUsrnew);
            //  巡检站端与中心级数据同步
           // 事物提交后业务逻辑
            dataSyncService.OrgUsrSyncDtoDataSync(orgUsrDto.getSequenceNbr());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new BadRequest("导入失败!");
    }

}









    private void savePeopleItem(OrgUsrExcelDto item) {
		FirefightersContacts firefightersContacts = new FirefightersContacts();
		// 手动添加主键，以便于给岗位、职位等实体赋值id
		Long sequenceId = null;
		firefightersContacts = Bean.toPo(item, firefightersContacts);
		if (firefightersContacts.getRelationship() != null) {
			String relationship = firefightersContacts.getRelationship().split("@")[1];
			firefightersContacts.setRelationship(relationship);
		}
		if (!ObjectUtils.isEmpty(item.getPeopleType()) && item.getPeopleType().contains("@") && "1601".equals(item.getPeopleType().split("@")[1])) {
			// 保存消防队伍人员和紧急联系人
			Firefighters firefighters = new Firefighters();
			firefighters = Bean.toPo(item, firefighters);
			firefighters = Bean.toPo(getCurrentInfo(), firefighters);
			sequenceId = sequence.nextId();
			firefighters.setSequenceNbr(sequenceId);
			firefighters.setName(item.getBizOrgName());
			if (firefighters.getCertificatesType() != null) {
				String[] certificates = firefighters.getCertificatesType().split("@");
				firefighters.setCertificatesType(certificates[0]);
				firefighters.setCertificatesTypeCode(certificates[1]);
			}
			if (firefighters.getState() != null) {
				String[] state = firefighters.getState().split("@");
				firefighters.setState(state[0]);
				firefighters.setStateCode(state[1]);
			}
			if (firefighters.getJobTitle() != null) {
				String[] jobTitle = firefighters.getJobTitle().split("@");
				firefighters.setJobTitle(jobTitle[0]);
				firefighters.setJobTitleCode(jobTitle[1]);
			}
			if (item.getParentId() != null) {
				firefighters.setCompanyName(item.getParentName());
				firefighters.setCompanyCode(item.getParentId());
				firefighters.setCompany(item.getParentId());
				OrgUsr result = orgUsrService.getById(Long.valueOf(item.getParentId()));
				firefighters.setBizOrgName(item.getParentName());
				firefighters.setBizOrgCode(result.getBizOrgCode());
			}
			if (item.getNativePlace() != null) {
				String[] tempCity = item.getNativePlace().split("@");
				firefighters.setNativePlaceValue(tempCity[0]);
				firefighters.setNativePlace(tempCity[1]);
			}
			if (item.getResidenceDetails() != null) {
				String[] tempCity = item.getResidenceDetails().split("@");
				firefighters.setResidence(tempCity[0]);
				firefighters.setResidenceDetails(tempCity[1]);
			}
            if (firefighters.getGender() != null) {
                String[] tempCity = firefighters.getGender().split("@");
                firefighters.setGender(tempCity[0]);
            }
            if (firefighters.getPeopleType() != null) {
                String[] tempCity = firefighters.getPeopleType().split("@");
                firefighters.setPeopleType(tempCity[1]);
            }
			if (firefighters.getStateCode() != null) {
				String[] tempCity = firefighters.getStateCode().split("@");
				firefighters.setState(tempCity[0]);
				firefighters.setStateCode(tempCity[1]);
			}
			if (firefighters.getCertificatesTypeCode() != null) {
				String[] tempCity = firefighters.getCertificatesTypeCode().split("@");
				firefighters.setCertificatesType(tempCity[0]);
				firefighters.setCertificatesTypeCode(tempCity[1]);
			}
			if (firefighters.getSafetyTraining() != null) {
				String[] tempCity = firefighters.getSafetyTraining().split("@");
				firefighters.setSafetyTraining(tempCity[1]);
			}
			if (item.getPositionType() != null) {
				String[] tempCity = item.getPositionType().split("@");
				firefighters.setJobTitle(tempCity[0]);
				firefighters.setJobTitleCode(tempCity[1]);
			}
			if (item.getTelephone() != null) {
				firefighters.setMobilePhone(item.getTelephone());
			}
			FirefightersInfoDto firefightersInfo = new FirefightersInfoDto(firefighters, firefightersContacts);
			firefightersService.saveFirefighters(firefightersInfo);
		} else {
			// 保存紧急联系人
			ifirefightersContactsService.save(firefightersContacts);
		}

		item.setFirefightersId(sequenceId);
		FirefightersWorkexperience firefightersWorkexperience = new FirefightersWorkexperience();
		FirefightersEducation firefightersEducation = new FirefightersEducation();
		FirefightersPost firefightersPost = new FirefightersPost();

		firefightersWorkexperience = Bean.toPo(item, firefightersWorkexperience);
		firefightersEducation = Bean.toPo(item, firefightersEducation);
		firefightersPost = Bean.toPo(item, firefightersPost);

		/************************* 岗位职级 ***********************/
		if (item.getEmployeeHierarchy() != null) {
			String[] employeeHierarchy = item.getEmployeeHierarchy().split("@");
			firefightersPost.setEmployeeHierarchy(employeeHierarchy[0]);
			firefightersPost.setEmployeeHierarchyCode(employeeHierarchy[1]);
		}
        if (item.getAdministrativePositionCode() != null) {
            String[] employeeHierarchy = item.getAdministrativePositionCode().split("@");
            firefightersPost.setAdministrativePosition(employeeHierarchy[0]);
            firefightersPost.setAdministrativePositionCode(employeeHierarchy[1]);
        }
        if (item.getPositionType() != null) {
            String[] employeeHierarchy = item.getPositionType().split("@");
            firefightersPost.setJobTitle(employeeHierarchy[0]);
            firefightersPost.setJobTitleCode(employeeHierarchy[1]);
        }
        if (item.getPostQualification() != null) {
            String[] employeeHierarchy = item.getPostQualification().split("@");
            firefightersPost.setPostQualification(employeeHierarchy[0]);
            firefightersPost.setPostQualificationCode(employeeHierarchy[1]);
        }
        if (item.getInternalPositionCode() != null) {
            String[] employeeHierarchy = item.getInternalPositionCode().split("@");
            firefightersPost.setInternalPosition(employeeHierarchy[0]);
            firefightersPost.setInternalPositionCode(employeeHierarchy[1]);
        }
        if (item.getFireManagementPostCode() != null) {
            String[] employeeHierarchy = item.getFireManagementPostCode().split("@");
            firefightersPost.setFireManagementPost(employeeHierarchy[0]);
            firefightersPost.setFireManagementPostCode(employeeHierarchy[1]);
        }
        if (item.getCertificateType() != null) {
            String[] employeeHierarchy = item.getCertificateType().split("@");
            firefightersPost.setCertificateType(employeeHierarchy[0]);
            firefightersPost.setCertificateTypeCode(employeeHierarchy[1]);
        }
        if (item.getAuditCycle() != null) {
            String[] employeeHierarchy = item.getAuditCycle().split("@");
            firefightersPost.setAuditCycle(employeeHierarchy[1]);
        }


		/************************* 学历教育 ***********************/
		if (item.getFirstDegree() != null) {
			String[] employeeHierarchy = item.getFirstDegree().split("@");
			firefightersEducation.setFirstDegree(employeeHierarchy[1]);
		}

		if (item.getHighestEducation() != null) {
			String[] employeeHierarchy = item.getHighestEducation().split("@");
			firefightersEducation.setHighestEducation(employeeHierarchy[1]);
		}
		if (item.getAcademicDegree() != null) {
			String[] employeeHierarchy = item.getAcademicDegree().split("@");
			firefightersEducation.setAcademicDegree(employeeHierarchy[1]);
		}

		iFirefightersPostService.save(firefightersPost);
		ifirefightersEducationService.save(firefightersEducation);
		ifirefightersWorkexperienceService.save(firefightersWorkexperience);
	}


    @Transactional
    public void excelImportFirefighters(MultipartFile multipartFile) throws Exception {
		List<FirefightersExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
				FirefightersExcelDto.class, 1);
		excelDtoList.forEach(item -> {
			Firefighters firefighters = new Firefighters();
			FirefightersContacts firefightersContacts = new FirefightersContacts();
			firefighters = Bean.toPo(item, firefighters);
			firefighters = Bean.toPo(getCurrentInfo(), firefighters);
			// 手动添加主键，以便于给岗位、职位等实体赋值id
			Long sequenceId = sequence.nextId();
			firefighters.setSequenceNbr(sequenceId);
			item.setFirefightersId(sequenceId);
			firefightersContacts = Bean.toPo(item, firefightersContacts);

			FirefightersWorkexperience firefightersWorkexperience = new FirefightersWorkexperience();
			FirefightersEducation firefightersEducation = new FirefightersEducation();
			FirefightersPost firefightersPost = new FirefightersPost();

			firefightersWorkexperience = Bean.toPo(item, firefightersWorkexperience);
			firefightersEducation = Bean.toPo(item, firefightersEducation);
			firefightersPost = Bean.toPo(item, firefightersPost);

			if (item.getFireTeam() != null) {
				Long fireTeamId = Long.valueOf(item.getFireTeam().split("@")[1]);
				firefighters.setFireTeamId(fireTeamId);
				firefighters.setFireTeamName(item.getFireTeam().split("@")[0]);
			}
			if (firefighters.getCertificatesType() != null) {
				String[] certificates = firefighters.getCertificatesType().split("@");
				firefighters.setCertificatesType(certificates[0]);
				firefighters.setCertificatesTypeCode(certificates[1]);
			}
			if (firefighters.getState() != null) {
				String[] state = firefighters.getState().split("@");
				firefighters.setState(state[0]);
				firefighters.setStateCode(state[1]);
			}
			if (firefighters.getJobTitle() != null) {
				String[] jobTitle = firefighters.getJobTitle().split("@");
				firefighters.setJobTitle(jobTitle[0]);
				firefighters.setJobTitleCode(jobTitle[1]);
			}
			if (firefightersContacts.getRelationship() != null) {
				String relationship = firefightersContacts.getRelationship().split("@")[1];
				firefightersContacts.setRelationship(relationship);
			}
			if (firefighters.getCompanyName() != null) {
				String[] tempCompany = firefighters.getCompanyName().split("@");
				firefighters.setCompanyName(tempCompany[0]);
				firefighters.setCompanyCode(tempCompany[1]);
				firefighters.setCompany(tempCompany[1]);
				OrgUsr result = orgUsrService.getById(Long.valueOf(tempCompany[1]));
				firefighters.setBizOrgName(tempCompany[0]);
				firefighters.setBizOrgCode(result.getBizOrgCode());
			}
			if (firefighters.getNativePlaceValue() != null) {
				String[] tempCity = firefighters.getNativePlaceValue().split("@");
				firefighters.setNativePlaceValue(tempCity[0]);
				firefighters.setNativePlace(tempCity[1]);
			}
			if (firefighters.getResidence() != null) {
				String[] tempCity = firefighters.getResidence().split("@");
				firefighters.setResidence(tempCity[0]);
				firefighters.setResidenceDetails(tempCity[1]);
			}
			/************************* 岗位职级 ***********************/
			if (item.getEmployeeHierarchy() != null) {
				String[] employeeHierarchy = item.getEmployeeHierarchy().split("@");
				firefightersPost.setEmployeeHierarchy(employeeHierarchy[0]);
				firefightersPost.setEmployeeHierarchyCode(employeeHierarchy[1]);
			}
			if (item.getAdministrativePosition() != null) {
				String[] employeeHierarchy = item.getAdministrativePosition().split("@");
				firefightersPost.setAdministrativePosition(employeeHierarchy[0]);
				firefightersPost.setAdministrativePositionCode(employeeHierarchy[1]);
			}
			if (item.getEmployeeHierarchy() != null) {
				String[] employeeHierarchy = item.getEmployeeHierarchy().split("@");
				firefightersPost.setEmployeeHierarchy(employeeHierarchy[0]);
				firefightersPost.setEmployeeHierarchyCode(employeeHierarchy[1]);
			}
			if (item.getPostQualification() != null) {
				String[] employeeHierarchy = item.getPostQualification().split("@");
				firefightersPost.setPostQualification(employeeHierarchy[0]);
				firefightersPost.setPostQualificationCode(employeeHierarchy[1]);
			}
			if (item.getCategory() != null) {
				String[] employeeHierarchy = item.getCategory().split("@");
				firefightersPost.setCategory(employeeHierarchy[0]);
				firefightersPost.setCategoryCode(employeeHierarchy[1]);
			}
			if (item.getLevel() != null) {
				String[] employeeHierarchy = item.getLevel().split("@");
				firefightersPost.setLevel(employeeHierarchy[0]);
				firefightersPost.setLevelCode(employeeHierarchy[1]);
			}
			if (item.getAreasExpertise() != null) {
				String[] employeeHierarchy = item.getAreasExpertise().split("@");
				firefightersPost.setAreasExpertise(employeeHierarchy[0]);
				firefightersPost.setAreasExpertiseCode(employeeHierarchy[1]);
			}

			/************************* 学历教育 ***********************/
			if (item.getFirstDegree() != null) {
				String[] employeeHierarchy = item.getFirstDegree().split("@");
				firefightersEducation.setFirstDegree(employeeHierarchy[1]);
			}

			if (item.getHighestEducation() != null) {
				String[] employeeHierarchy = item.getHighestEducation().split("@");
				firefightersEducation.setHighestEducation(employeeHierarchy[1]);
			}
			if (item.getAcademicDegree() != null) {
				String[] employeeHierarchy = item.getAcademicDegree().split("@");
				firefightersEducation.setAcademicDegree(employeeHierarchy[1]);
			}

			iFirefightersPostService.save(firefightersPost);
			ifirefightersEducationService.save(firefightersEducation);
			ifirefightersWorkexperienceService.save(firefightersWorkexperience);
			// BUG 2760 修改消防人员导出模板和 导入问题 bykongfm
			FirefightersInfoDto firefightersInfo = new FirefightersInfoDto(firefighters, firefightersContacts);
			firefightersService.saveFirefighters(firefightersInfo);
		});
	}
    @Transactional
    public void excelImportFireStation(MultipartFile multipartFile) throws Exception {

		List<FireStationDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireStationDto.class, 1);
		Map<String, String> maps =	getAllBuildingIdForParentBuilingIds(excelDtoList);
		List<FireStation> excelEntityList = new ArrayList<>();
		excelDtoList.forEach(item -> {
			FireStation fireStation = new FireStation();
			fireStation = Bean.toPo(item, fireStation);
			fireStation = Bean.toPo(getCurrentInfo(), fireStation);
			if (fireStation.getWhereBuilding() != null) {
				String[] whereBuilding = fireStation.getWhereBuilding().split("@");
				fireStation.setWhereBuilding(whereBuilding[0]);
				fireStation.setWhereBuildingId(whereBuilding[1]);
				if(maps.containsKey(whereBuilding[1])){
					fireStation.setParentBuildingId(maps.get(whereBuilding[1]));
				}
			}
			if (fireStation.getBizCompany() != null) {
				String[] bizCompany = fireStation.getBizCompany().split("@");
				fireStation.setBizCompany(bizCompany[0]);
				fireStation.setBizOrgName(bizCompany[0]);
				fireStation.setBizCompanyId(Long.valueOf(bizCompany[1]));
				OrgUsr byId = orgUsrService.getById(Long.valueOf(bizCompany[1]));
				if (byId != null && byId.getBizOrgCode() != null){
					fireStation.setBizCompanyCode(byId.getBizOrgCode());
					fireStation.setBizOrgCode(byId.getBizOrgCode());
				}
			}
			if (fireStation.getPersonChargeName() != null){
				String[] personChargeName = fireStation.getPersonChargeName().split("@");
				fireStation.setPersonChargeName(personChargeName[0]);
				fireStation.setPersonChargeId(personChargeName[1]);
			}
			excelEntityList.add(fireStation);
		});
		fireStationService.saveBatch(excelEntityList);
	}
	   public Map<String, String> getAllBuildingIdForParentBuilingIds(List<FireStationDto> excelDtoList) {
	    	List<String> list = new ArrayList<String>();
	    	for (FireStationDto fireStation : excelDtoList) {
				if (org.apache.commons.lang3.StringUtils.isNotBlank(fireStation.getWhereBuilding())) {
					String[] whereBuilding = fireStation.getWhereBuilding().split("@");
					fireStation.setWhereBuildingId(whereBuilding[1]);
					list.add(whereBuilding[1]);
				}
			}
			return keySiteService.getNodeAllParentIds(list);
	    }
    @Transactional
    public void excelImportFireTeam(MultipartFile multipartFile) throws Exception {
		List<FireTeamDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireTeamDto.class, 1);
		List<FireTeam> excelEntityList = new ArrayList<>();

		excelDtoList.forEach(item -> {
			if (StringUtils.isEmpty(item.getCompanyName()) || StringUtils.isEmpty(item.getName()) ||
					StringUtils.isEmpty(item.getType()) || StringUtils.isEmpty(item.getAddress())) {
				throw new BadRequest("请检查必填项是否为空");
			}
			FireTeam fireTeam = new FireTeam();
			fireTeam = Bean.toPo(item, fireTeam);
			fireTeam = Bean.toPo(getCurrentInfo(), fireTeam);
			/* bug2835 添加获取上级单位的信息方法 陈浩 2021-09-10 --start */
			if (fireTeam.getCompanyName() != null) {
				String[] companyArray = fireTeam.getCompanyName().split("@");
				fireTeam.setCompany(Long.parseLong(companyArray[1]));
				fireTeam.setCompanyName(companyArray[0]);
				try {
					OrgUsrFormDto companyDto = orgUsrServer.selectCompanyById(Long.parseLong(companyArray[1]));
					fireTeam.setCompanyCode(companyDto.getBizOrgCode());
					fireTeam.setBizOrgCode(companyDto.getBizOrgCode());
					fireTeam.setBizOrgName(companyDto.getBizOrgName());
					} catch (Exception e) {
                   e.printStackTrace();
				}
			}
			/* bug2835 添加获取上级单位的信息方法 陈浩 2021-09-10 --end */
			if (fireTeam.getType() != null) {
				String[] type = fireTeam.getType().split("@");
				fireTeam.setType(type[0]);
				fireTeam.setTypeCode(type[1]);
			}
			if (fireTeam.getContactUser() != null) {
				String[] contactUser = fireTeam.getContactUser().split("@");
				fireTeam.setContactUser(contactUser[0]);
				fireTeam.setContactUserId(Long.valueOf(contactUser[1]));
			}
			if (item.getParentName() != null) {
				String[] parentName = item.getParentName().split("@");
				fireTeam.setParent(Long.valueOf(parentName[1]));
			}
			excelEntityList.add(fireTeam);
		});
		fireTeamService.saveBatch(excelEntityList);
	}
    @Transactional
    public void excelImportAircraft(MultipartFile multipartFile) throws Exception {
		List<AircraftDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, AircraftDto.class, 1);
		List<Aircraft> excelEntityList = new ArrayList<>();
		excelDtoList.forEach(item -> {
			Aircraft aircraft = new Aircraft();
			aircraft = Bean.toPo(item, aircraft);
			aircraft = Bean.toPo(getCurrentInfo(), aircraft);
			if (aircraft.getEngineType() != null) {
				String[] engineType = aircraft.getEngineType().split("@");
				aircraft.setEngineType(engineType[0]);
				aircraft.setEngineTypeCode(engineType[1]);
			}
			if (aircraft.getFuelType() != null) {
				String[] fuelType = aircraft.getFuelType().split("@");
				aircraft.setFuelType(fuelType[0]);
				aircraft.setFuelTypeCode(fuelType[1]);
			}
			excelEntityList.add(aircraft);
		});
		aircraftServiceImpl.saveBatch(excelEntityList);
	}
    @Transactional
    public void excelImportFireChemical(MultipartFile multipartFile) throws Exception {
		List<FireChemicalDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireChemicalDto.class, 1);
		List<FireChemical> excelEntityList = new ArrayList<>();
		excelDtoList.forEach(item -> {
			FireChemical fireChemical = new FireChemical();
			fireChemical = Bean.toPo(item, fireChemical);
			fireChemical = Bean.toPo(getCurrentInfo(), fireChemical);
			if (fireChemical.getType() != null) {
				String[] type = fireChemical.getType().split("@");
				fireChemical.setType(type[0]);
				fireChemical.setTypeCode(type[1]);
			}
			excelEntityList.add(fireChemical);
		});
		fireChemicalServiceImpl.saveBatch(excelEntityList);
	}
    @Transactional
    public void excelImportWaterResource(MultipartFile multipartFile) throws Exception {
		List<WaterResourceDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, WaterResourceDto.class, 1);

		excelDtoList.forEach(item -> {
			/* Bug 2950 消防水源，缺失设施分类、设施定义等必填字段可以上传成功 陈召 2021-10-09 */
			if (item.getEquipName() == null || item.getEquipName().equals(" ")) {
				throw new BadRequest("设备定义名称为必填字段，填写后重新上传");
			}

			// BUG 2953 导入模板没有设备编码生成 2021-09-18 陈召开始
			item.setEquipCode(QRCodeUtil.generateQRCode());
			// BUG 2953 导入模板没有设备编码生成 2021-09-18 陈召结束
			if (item.getResourceTypeName() != null) {
				String[] resourceTypeName = item.getResourceTypeName().split("@");
				item.setResourceTypeName(resourceTypeName[0]);
				item.setResourceType(resourceTypeName[1]);
			}
			if (item.getHydrantType() != null) {
				item.setType(item.getHydrantType());
			}
			if (item.getSystemType() != null) {
				String[] systemType = item.getSystemType().split("@");
				item.setSystemType(systemType[0]);
				item.setSystemTypeCode(systemType[1]);
			}
			if (item.getPlaceForm() != null) {
				String[] placeForm = item.getPlaceForm().split("@");
				item.setPlaceForm(placeForm[0]);
				item.setPlaceFormCode(placeForm[1]);
			}
			if (item.getBelongBuilding() != null) {
				String[] belongBuilding = item.getBelongBuilding().split("@");
				item.setBelongBuilding(belongBuilding[0]);
				item.setBelongBuildingId(Long.valueOf(belongBuilding[1]));
			}
			if (item.getBelongFightingSystem() != null) {
				String[] belongFightingSystem = item.getBelongFightingSystem().split("@");
				item.setBelongFightingSystem(belongFightingSystem[0]);
				item.setBelongFightingSystemId(Long.valueOf(belongFightingSystem[1]));
			}
			if (item.getManagementUnit() != null) {
				String[] managementUnit = item.getManagementUnit().split("@");
				item.setManagementUnit(managementUnit[0]);
				item.setManagementUnitId(Long.valueOf(managementUnit[1]));
				OrgUsr org = orgUsrService.getById(Long.valueOf(managementUnit[1]));
				if(org!=null) {
					item.setBizOrgCode(org.getBizOrgCode());
					item.setBizOrgName(org.getBizOrgName());
				}
			}
			if (item.getMaintenanceUnit() != null) {
				String[] maintenanceUnit = item.getMaintenanceUnit().split("@");
				item.setMaintenanceUnit(maintenanceUnit[0]);
				item.setMaintenanceUnitId(Long.valueOf(maintenanceUnit[1]));
			}
			if (item.getHoseConnection() != null) {
				String[] hoseConnection = item.getHoseConnection().split("@");
				item.setHoseConnection(hoseConnection[0]);
				item.setHoseConnectionCode(hoseConnection[1]);
			}
			if (item.getIntakeForm() != null) {
				String[] intakeForm = item.getIntakeForm().split("@");
				item.setIntakeForm(intakeForm[0]);
			}
			if (item.getPipeTypeName() != null) {
				String[] pipeTypeName = item.getPipeTypeName().split("@");
				item.setPipeTypeName(pipeTypeName[0]);
				item.setPipeTypeCode(pipeTypeName[1]);
			}
			if (item.getStatus() != null) {
				String[] status = item.getStatus().split("@");
				item.setStatus(status[0]);
				item.setStatusCode(status[1]);
			}
			if (item.getType() != null) {
				String[] type = item.getType().split("@");
				item.setType(type[0]);
				item.setTypeCode(type[1]);
			}
			if (item.getLevelDeviceName() != null) {
				String[] type = item.getLevelDeviceName().split("@");
				item.setLevelDeviceName(type[0]);
				item.setLevelDeviceId(type[1]);
			}
			// BUG 2935 优化项 分类从93060000 取得字典数据 by kongfm 2021-09-17
			if (item.getEquipCategoryName() != null) {
				String[] equipCategory = item.getEquipCategoryName().split("@");
				item.setEquipCategoryName(equipCategory[0]);
				item.setEquipCategoryId(Long.parseLong(equipCategory[1]));
			}

			if (item.getHasDrySeasonType() != null) {
				boolean flag = "有".equals(item.getHasDrySeasonType()) ? true : false;
				item.setHasDrySeason(flag);
			}
			if (item.getEquipName() != null) {
				String[] equipCategory = item.getEquipName().split("@");
				item.setEquipId(Long.parseLong(equipCategory[1]));
				item.setEquipName(equipCategory[0]);
				item.setEquipCategoryId(Long.parseLong(equipCategory[2]));
				item.setEquipCategoryName(equipCategory[3]);
				switch (equipCategory[3]) {
				case "天然水源":
					item.setEquipCategoryCode("93060300");
					break;
				case "水源-消火栓":
					item.setEquipCategoryCode("93060400");
					break;
				case "消火栓":
					item.setEquipCategoryCode("93060400");
					break;
				case "消防水池":
					item.setEquipCategoryCode("93060100");
					break;
				case "消防水鹤":
					item.setEquipCategoryCode("93060200");
					break;
				case "工业水池":
					item.setEquipCategoryCode("93060500");
					break;
				default:
					break;
				}
			}
			if (item.getContactUser() != null) {
				String[] contactUser = item.getContactUser().split("@");
				item.setContactUser(contactUser[0]);
				item.setContactUserId(contactUser[1]);
			}
			item = Bean.toPo(getCurrentInfo(), item);
			//水源的isdelete是反着的
			item.setIsDelete(true);
			waterResourceServiceImpl.importByExcel(item);
		});
	}

	@Transactional
	public void excelImportWaterResourceNew(MultipartFile multipartFile) throws Exception {
		List<WaterResourceDto>  excelDtoList = new ArrayList<>();
		List<WaterExcelPoolDto> waterExcelPoolDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelPoolDto.class, 0, 0);
		List<WaterExcelHydrantDto> waterExcelHydrantDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelHydrantDto.class, 0, 1);
		List<WaterExcelCraneDto> waterExcelCraneDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelCraneDto.class, 0, 2);
		List<WaterExcelNaturalDto> waterExcelNaturalDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelNaturalDto.class, 0, 3);
		List<WaterExcelIndustryPoolDto> waterExcelIndustryPoolDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelIndustryPoolDto.class, 0, 4);
		List<WaterExcelWaterTankDto> waterExcelWaterTankDtos = ExcelUtil.readManySheetExcel(multipartFile, WaterExcelWaterTankDto.class, 0, 5);
		waterExcelPoolDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto); excelDtoList.add(waterResourceDto); });
		waterExcelHydrantDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto); excelDtoList.add(waterResourceDto);  });
		waterExcelCraneDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto); excelDtoList.add(waterResourceDto);  });
		waterExcelNaturalDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto);excelDtoList.add(waterResourceDto);  });
		waterExcelIndustryPoolDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto);excelDtoList.add(waterResourceDto);  });
		waterExcelWaterTankDtos.forEach(e->{ WaterResourceDto waterResourceDto = new WaterResourceDto();BeanUtils.copyProperties(e,waterResourceDto);excelDtoList.add(waterResourceDto);  });

		excelDtoList.forEach(item -> {
			/* Bug 2950 消防水源，缺失设施分类、设施定义等必填字段可以上传成功 陈召 2021-10-09 */
			if (item.getEquipName() == null || item.getEquipName().equals(" ")) {
				throw new BadRequest("设备定义名称为必填字段，填写后重新上传");
			}

			// BUG 2953 导入模板没有设备编码生成 2021-09-18 陈召开始
			item.setEquipCode(QRCodeUtil.generateQRCode());
			// BUG 2953 导入模板没有设备编码生成 2021-09-18 陈召结束
			if (item.getResourceTypeName() != null) {
				String[] resourceTypeName = item.getResourceTypeName().split("@");
				item.setResourceTypeName(resourceTypeName[0]);
				item.setResourceType(resourceTypeName[1]);
			}
			if (item.getHydrantType() != null) {
				item.setType(item.getHydrantType());
			}
			if (item.getSystemType() != null) {
				String[] systemType = item.getSystemType().split("@");
				item.setSystemType(systemType[0]);
				item.setSystemTypeCode(systemType[1]);
			}
			if (item.getPlaceForm() != null) {
				String[] placeForm = item.getPlaceForm().split("@");
				item.setPlaceForm(placeForm[0]);
				item.setPlaceFormCode(placeForm[1]);
			}
			if (item.getBelongBuilding() != null) {
				String[] belongBuilding = item.getBelongBuilding().split("@");
				item.setBelongBuilding(belongBuilding[0]);
				item.setBelongBuildingId(Long.valueOf(belongBuilding[1]));
			}
			if (item.getBelongFightingSystem() != null) {
				String[] belongFightingSystem = item.getBelongFightingSystem().split("@");
				item.setBelongFightingSystem(belongFightingSystem[0]);
				item.setBelongFightingSystemId(Long.valueOf(belongFightingSystem[1]));
			}
			if (item.getManagementUnit() != null) {
				String[] managementUnit = item.getManagementUnit().split("@");
				item.setManagementUnit(managementUnit[0]);
				item.setManagementUnitId(Long.valueOf(managementUnit[1]));
				OrgUsr org = orgUsrService.getById(Long.valueOf(managementUnit[1]));
				if(org!=null) {
					item.setBizOrgCode(org.getBizOrgCode());
					item.setBizOrgName(org.getBizOrgName());
				}
			}
			if (item.getMaintenanceUnit() != null) {
				String[] maintenanceUnit = item.getMaintenanceUnit().split("@");
				item.setMaintenanceUnit(maintenanceUnit[0]);
				item.setMaintenanceUnitId(Long.valueOf(maintenanceUnit[1]));
			}
			if (item.getHoseConnection() != null) {
				String[] hoseConnection = item.getHoseConnection().split("@");
				item.setHoseConnection(hoseConnection[0]);
				item.setHoseConnectionCode(hoseConnection[1]);
			}
			if (item.getIntakeForm() != null) {
				String[] intakeForm = item.getIntakeForm().split("@");
				item.setIntakeForm(intakeForm[0]);
			}
			if (item.getPipeTypeName() != null) {
				String[] pipeTypeName = item.getPipeTypeName().split("@");
				item.setPipeTypeName(pipeTypeName[0]);
				item.setPipeTypeCode(pipeTypeName[1]);
			}
			if (item.getStatus() != null) {
				String[] status = item.getStatus().split("@");
				item.setStatus(status[0]);
				item.setStatusCode(status[1]);
			}
			if (item.getType() != null) {
				String[] type = item.getType().split("@");
				item.setType(type[0]);
				item.setTypeCode(type[1]);
			}
			if (item.getLevelDeviceName() != null) {
				String[] type = item.getLevelDeviceName().split("@");
				item.setLevelDeviceName(type[0]);
				item.setLevelDeviceId(type[1]);
			}
			// BUG 2935 优化项 分类从93060000 取得字典数据 by kongfm 2021-09-17
			if (item.getEquipCategoryName() != null) {
				String[] equipCategory = item.getEquipCategoryName().split("@");
				item.setEquipCategoryName(equipCategory[0]);
				item.setEquipCategoryId(Long.parseLong(equipCategory[1]));
			}

			if (item.getHasDrySeasonType() != null) {
				boolean flag = "有".equals(item.getHasDrySeasonType()) ? true : false;
				item.setHasDrySeason(flag);
			}
			if (item.getEquipName() != null) {
				String[] equipCategory = item.getEquipName().split("@");
				item.setEquipId(Long.parseLong(equipCategory[1]));
				item.setEquipName(equipCategory[0]);
				item.setEquipCategoryId(Long.parseLong(equipCategory[2]));
				item.setEquipCategoryName(equipCategory[3]);
				switch (equipCategory[3]) {
					case "天然水源":
						item.setEquipCategoryCode("93060300");
						break;
					case "水源-消火栓":
						item.setEquipCategoryCode("93060400");
						break;
					case "消火栓":
						item.setEquipCategoryCode("93060400");
						break;
					case "消防水池":
						item.setEquipCategoryCode("93060100");
						break;
					case "消防水鹤":
						item.setEquipCategoryCode("93060200");
						break;
					case "工业水池":
						item.setEquipCategoryCode("93060500");
						break;
					default:
						break;
				}
			}
			if (item.getContactUser() != null) {
				String[] contactUser = item.getContactUser().split("@");
				item.setContactUser(contactUser[0]);
				item.setContactUserId(contactUser[1]);
			}
			item = Bean.toPo(getCurrentInfo(), item);
			//水源的isdelete是反着的
			item.setIsDelete(true);
			waterResourceServiceImpl.importByExcel(item);
		});
	}
    @Transactional
    public void excelImportFireExperts(MultipartFile multipartFile) throws Exception {
		ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
		String companyId = reginParams.getPersonIdentity().getCompanyId();
		String bizOrgCode = "1";
		String bizOrgName = "1";
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(companyId)) {
			OrgUsr orgUsr = orgUsrMapper.queryBySequenceNbr(companyId);
			bizOrgCode = orgUsr.getBizOrgCode();
			bizOrgName = orgUsr.getBizOrgName();
		}
		List<FireExpertsDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, FireExpertsDto.class, 1);
		List<FireExperts> excelEntityList = new ArrayList<>();
		String finalBizOrgCode = bizOrgCode;
		String finalBizOrgName = bizOrgName;
		excelDtoList.forEach(fireExpertsDto -> {
			FireExperts fireExperts = new FireExperts();
			fireExperts = Bean.toPo(fireExpertsDto, fireExperts);
			fireExperts = Bean.toPo(getCurrentInfo(), fireExperts);
			if (fireExperts.getCertificatesType() != null) {
				String[] certificates = fireExperts.getCertificatesType().split("@");
				fireExperts.setCertificatesType(certificates[0]);
				fireExperts.setCertificatesTypeCode(certificates[1]);
			}
			if (fireExperts.getJobs() != null) {
				String[] jobs = fireExperts.getJobs().split("@");
				fireExperts.setJobs(jobs[0]);
				fireExperts.setJobsCode(jobs[1]);
			}
			if (fireExperts.getExpert() != null) {
				String[] expert = fireExperts.getExpert().split("@");
				fireExperts.setExpert(expert[0]);
				fireExperts.setExpertCode(expert[1]);
			}
			if (fireExperts.getHighestEducation() != null) {
				String[] highestEducation = fireExperts.getHighestEducation().split("@");
				fireExperts.setHighestEducation(highestEducation[1]); // BUG 2942 by litw 2021年9月18日 导入学历编号
			}
			if (fireExperts.getNativePlaceVal() != null) {
				String[] nativePlaceVal = fireExperts.getNativePlaceVal().split("@");
				fireExperts.setNativePlace(nativePlaceVal[1]);
				fireExperts.setNativePlaceVal(nativePlaceVal[0]);
			}
			if (fireExperts.getResidenceDetailVal() != null) {
				String[] residenceDetailVal = fireExperts.getResidenceDetailVal().split("@");
				fireExperts.setResidence(residenceDetailVal[1]);
				fireExperts.setResidenceDetailVal(residenceDetailVal[0]);
			}
			fireExperts.setBizOrgCode(finalBizOrgCode);
			fireExperts.setBizOrgName(finalBizOrgName);
			excelEntityList.add(fireExperts);
		});
		fireExpertsServiceImpl.saveBatch(excelEntityList);
	}
    @Transactional
	public void excelImportDutyPerson(MultipartFile multipartFile, String dutyType,String uuidString) {
		try {
			ImportDutyPerson(multipartFile,dutyType);
			if(redisUtils.hasKey(uuidString)){
				redisUtils.set(uuidString, 1);
			}
		} catch (Exception e) {
			if(redisUtils.hasKey(uuidString)){
				redisUtils.set(uuidString, 2);
			}
		}

	}
    private void ImportDutyPerson(MultipartFile multipartFile, String dutyType) throws BadRequest, IOException {
    	String fileName = multipartFile.getOriginalFilename();
		if (fileName == null) {
			throw new BadRequest("文件不存在！");
		}
		if (!fileName.toLowerCase().endsWith(ExcelTypeEnum.XLS.getValue())
				&& !fileName.toLowerCase().endsWith(ExcelTypeEnum.XLSX.getValue())) {
			throw new BadRequest("文件类型异常！");
		}
		InputStream input = multipartFile.getInputStream();
		XSSFWorkbook workbook = new XSSFWorkbook(input);
		XSSFSheet sheet = workbook.getSheetAt(0);
		List<Map<String, Object>> dataList = new ArrayList<>();
		if (sheet != null) {
			// 获取表头月份
			Row titleRow = sheet.getRow(0);
			// 958
			Cell monthCell = titleRow.getCell(6);
			String dateStr = monthCell == null ? "" : monthCell.toString();

			List<Date> dayByMonth = DateUtils.getDayByMonth(dateStr);
			if (ExcelEnums.CLZQ.getType().equals(dutyType)) {
				initDutyCarData(sheet, dataList, dayByMonth);
				dutyCarService.saveImportData(dataList);
			} else if (ExcelEnums.RYZB.getType().equals(dutyType)) {
				initDutyPersonData(sheet, dataList, dayByMonth);
				dutyPersonService.saveImportData(dataList);
			} else if (ExcelEnums.WXXFZB.getType().equals(dutyType)) {
				initDutyFireFightingData(sheet, dataList, dayByMonth);
				dutyFireFightingService.saveImportData(dataList);
			} else if (ExcelEnums.JJZB.getType().equals(dutyType)) {
				initDutyFirstAidData(sheet, dataList, dayByMonth);
				dutyFirstAidService.saveImportData(dataList);
			}
		}

    }
	private void initDutyFirstAidData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			DutyFirstAidDto dutyFirstAidDto = new DutyFirstAidDto();
			// row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
			Row row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			Cell cell = row.getCell(2);
			if (cell == null) {
				continue;
			}
			cell = row.getCell(1);
			if (cell != null) {
				String[] split = cell.toString().split("@");
				dutyFirstAidDto.setTeamId(split[1]);
				dutyFirstAidDto.setTeamName(split[0]);
			}
			cell = row.getCell(2);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFirstAidDto.setUserName(splitStr[0]);
				dutyFirstAidDto.setUserId(splitStr[1]);
			}
			cell = row.getCell(3);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFirstAidDto.setPostTypeName(splitStr[0]);
				dutyFirstAidDto.setPostType(splitStr[1]);
			}
			cell = row.getCell(4);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFirstAidDto.setFirstAid(splitStr[0]);
				dutyFirstAidDto.setFirstAidId(splitStr[1]);
			}
			List<DutyPersonShiftDto> dutyShift = new ArrayList<>();
			for (int j = 0; j < dayByMonth.size(); j++) {
				cell = row.getCell(5 + j);
				String dutyType = cell == null ? "" : cell.toString();
				if (!StringUtils.isEmpty(dutyType)) {
					DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
					dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
					dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
					dutyShift.add(dutyPersonShiftDto);
				}
			}
			dutyFirstAidDto.setDutyShift(dutyShift);
			Map<String, Object> dutyPersonDtoMap = Bean.BeantoMap(dutyFirstAidDto);
			dataList.add(dutyPersonDtoMap);
		}

	}
    @Transactional
    public void excelImportSafeReport(MultipartFile multipartFile) throws Exception {

		String fileName = multipartFile.getOriginalFilename();
		if (fileName == null) {
			throw new BadRequest("文件不存在！");
		}
		if (!fileName.toLowerCase().endsWith(ExcelTypeEnum.XLS.getValue())
				&& !fileName.toLowerCase().endsWith(ExcelTypeEnum.XLSX.getValue())) {
			throw new BadRequest("文件类型异常！");
		}
		List<OrgUsrSafeReportExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
				OrgUsrSafeReportExcelDto.class, 1);
		List<OrgUsrSafeReport> excelEntityList = new ArrayList<>();
		excelDtoList.forEach(fireExpertsDto -> {
			OrgUsrSafeReport reportExcel = new OrgUsrSafeReport();
			reportExcel = Bean.toPo(fireExpertsDto, reportExcel);
			reportExcel = Bean.toPo(getCurrentInfo(), reportExcel);
			if (reportExcel.getCompany() != null) {
				String[] compandyArr = reportExcel.getCompany().split("@");
				reportExcel.setCompany(compandyArr[0]);
				reportExcel.setCompanyId(Long.valueOf(compandyArr[1]));
			}
			excelEntityList.add(reportExcel);
		});
		orgUsrSafeReportService.saveBatch(excelEntityList);
	}

	private void initDutyCarData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
		// 遍历行，i = 1，从第二行开始，第一行是表头跳过。
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			DutyCarDto dutyCarDto = new DutyCarDto();
			// row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
			Row row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			Cell cell4 = row.getCell(4);
			if(cell4 ==null) {
				continue;
			}
			Cell cell = row.getCell(1);
			if (cell != null) {
				String[] split = cell.toString().split("@");
				dutyCarDto.setTeamName(split[0]);
				dutyCarDto.setTeamId(split[1]);
			}
			cell = row.getCell(2);
			if (cell != null) {
				String[] userName = cell.toString().split("@");
				dutyCarDto.setUserName(userName[0]);
				dutyCarDto.setUserId(userName[1]);

				cell = row.getCell(3);
				if (cell != null) {
					String[] postType = cell.toString().split("@");
					dutyCarDto.setPostTypeName(postType[0]);
					dutyCarDto.setPostType(postType[1]);
				}
				cell = row.getCell(4);
				if (cell != null) {
					String[] carName = cell.toString().split("@");
					dutyCarDto.setCarName(carName[0]);
					dutyCarDto.setCarId(carName[1]);
				}
				cell = row.getCell(5);
				if (cell != null) {
					String[] dutyArea = cell.toString().split("@");
					dutyCarDto.setDutyArea(dutyArea[0]);
					dutyCarDto.setDutyAreaId(dutyArea[1]);
				}
				List<DutyPersonShiftDto> dutyShift = dutyCarDto.getDutyShift();
				for (int j = 0; j < dayByMonth.size(); j++) {
					cell = row.getCell(6 + j);
					String dutyType = cell == null ? "" : cell.toString();
					if (!StringUtils.isEmpty(dutyType)) {
						DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
						dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
						dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
						dutyShift.add(dutyPersonShiftDto);
					}
				}
				Map<String, Object> dutyCarDtoMap = Bean.BeantoMap(dutyCarDto);
				dataList.add(dutyCarDtoMap);
			}
		}
	}

	private void initDutyPersonData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
		// 遍历行，i = 1，从第二行开始，第一行是表头跳过。
		for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
			DutyPersonDto dutyPersonDto = new DutyPersonDto();
			// row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
			Row row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			if (i == 0){
				if ( !row.getCell(1).toString().equals("用户ID")){
					throw new BadRequest("上传模板类型不正确");
				}else {
					continue;
				}
			}
//			Cell	cell4 = row.getCell(4);
//			if(cell4 ==null) {
//				continue;
//			}
			Cell cell = row.getCell(1);
			if (cell != null) {
				dutyPersonDto.setUserId(cell.toString());
				cell = row.getCell(2);
				if (cell != null) {
					dutyPersonDto.setUserName(cell.toString());
				}
				cell = row.getCell(3);
				if (cell != null) {
					String[] split = cell.toString().split("@");
					dutyPersonDto.setDeptName(split[0]);
					dutyPersonDto.setDeptId(split[1]);
				}
				cell = row.getCell(4);
				if (cell != null) {
					String[] split = cell.toString().split("@");
					dutyPersonDto.setPostTypeName(split[0]);
					dutyPersonDto.setPostType(split[1]);
				} else {
					throw new BadRequest("第"+i+1+"行，第5列数据为空，请检查数据后再上传");
				}
				// 需求958 添加值班区域 导入 by kongfm 2021-09-15
				cell = row.getCell(5);
				if (cell != null) {
					String[] dutyArea = cell.toString().split("@");
					dutyPersonDto.setDutyArea(dutyArea[0]);
					dutyPersonDto.setDutyAreaId(dutyArea[1]);
				} else {
						throw new BadRequest("第"+i+1+"行，第6列数据为空，请检查数据后再上传");
				}
				List<DutyPersonShiftDto> dutyShift = new ArrayList<>();
				for (int j = 0; j < dayByMonth.size(); j++) {
					cell = row.getCell(6 + j);
					String dutyType = cell == null ? "" : cell.toString();
					if (!StringUtils.isEmpty(dutyType)) {
						DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
						dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
						dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
						dutyShift.add(dutyPersonShiftDto);
					}
				}
				dutyPersonDto.setDutyShift(dutyShift);
				Map<String, Object> dutyPersonDtoMap = Bean.BeantoMap(dutyPersonDto);
				dataList.add(dutyPersonDtoMap);
			}
		}
	}

	private void initDutyFireFightingData(XSSFSheet sheet, List<Map<String, Object>> dataList, List<Date> dayByMonth) {
		// 遍历行，i = 1，从第二行开始，第一行是表头跳过。
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			DutyFireFightingDto dutyFireFightingDto = new DutyFireFightingDto();
			// row是一行数据，row.getCell(i),代表拿到这一行，第i列数据
			Row row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			Cell cell = row.getCell(4);
			if (cell == null) {
				continue;
			}
			cell = row.getCell(1);
			if (cell != null) {
				String[] split = cell.toString().split("@");
				dutyFireFightingDto.setTeamId(split[1]);
				dutyFireFightingDto.setTeamName(split[0]);
			}
			cell = row.getCell(2);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFireFightingDto.setUserName(splitStr[0]);
				dutyFireFightingDto.setUserId(splitStr[1]);
			}
			cell = row.getCell(3);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFireFightingDto.setPostTypeName(splitStr[0]);
				dutyFireFightingDto.setPostType(splitStr[1]);
			}
			cell = row.getCell(4);
			if (cell != null) {
				String[] splitStr = cell.toString().split("@");
				dutyFireFightingDto.setFireFighting(splitStr[0]);
				dutyFireFightingDto.setFireFightingId(splitStr[1]);
			}
			List<DutyPersonShiftDto> dutyShift = new ArrayList<>();
			for (int j = 0; j < dayByMonth.size(); j++) {
				cell = row.getCell(5 + j);
				String dutyType = cell == null ? "" : cell.toString();
				if (!StringUtils.isEmpty(dutyType)) {
					DutyPersonShiftDto dutyPersonShiftDto = new DutyPersonShiftDto();
					dutyPersonShiftDto.setDutyDate(dayByMonth.get(j));
					dutyPersonShiftDto.setShiftId(Long.valueOf(dutyType.split("@")[1]));
					dutyShift.add(dutyPersonShiftDto);
				}
			}
			dutyFireFightingDto.setDutyShift(dutyShift);
			Map<String, Object> dutyPersonDtoMap = Bean.BeantoMap(dutyFireFightingDto);
			dataList.add(dutyPersonDtoMap);
		}
	}
    @Transactional
    public void excelImportMaintenancePerson(MultipartFile multipartFile) throws Exception {
		List<MaintenancePersonExcleDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile,
				MaintenancePersonExcleDto.class, 1);
		List<DynamicFormColumn> columns = dynamicFormColumnService.list(
				new LambdaQueryWrapper<DynamicFormColumn>().eq(DynamicFormColumn::getGroupCode, MAINTENANCE_PERSON));
		List<MaintenanceCompany> maintenanceCompanyList = new ArrayList<MaintenanceCompany>();
		List<DynamicFormInstance> dynamicFormInstanceList = new ArrayList<DynamicFormInstance>();
		for (MaintenancePersonExcleDto maintenancePersonExcleDto : excelDtoList) {
			Long instanceId = sequence.nextId();
			// 先填充主表的属性
			MaintenanceCompany maintenanceCompany = new MaintenanceCompany();
			maintenanceCompany = Bean.toPo(maintenancePersonExcleDto, maintenanceCompany);
			maintenanceCompany = Bean.toPo(getCurrentInfo(), maintenanceCompany);
			maintenanceCompany.setType(PERSON);
			if (maintenanceCompany.getParentId() != null) {
				long getParentId = Long.valueOf(maintenancePersonExcleDto.getParentName().split("@")[1]);
				maintenanceCompany.setParentId(getParentId);
			}
			if (maintenanceCompanyService.checkPersonCodeExists(maintenancePersonExcleDto.getCode())) {
				maintenanceCompany.setBizCode(maintenancePersonExcleDto.getCode());
			} else {
				maintenanceCompany.setCode(null);
			}
			maintenanceCompany.setOrgCode(null);
			maintenanceCompany.setBizCode(sequence.nextId() + "");
			maintenanceCompany.setInstanceId(instanceId);
			maintenanceCompanyList.add(maintenanceCompany);
			maintenanceCompanyService.maintenancePersonExcleDtoToDynamicFormInstanceList(columns,
					maintenancePersonExcleDto, instanceId, dynamicFormInstanceList);
		}
		maintenanceCompanyService.saveMaintenanceCompanyBatch(maintenanceCompanyList, dynamicFormInstanceList);
	}
    @Transactional
    public void excelImportKeySite(MultipartFile multipartFile) throws Exception {
		List<KeySiteExcleDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, KeySiteExcleDto.class, 1);
		keySiteService.saveExcel(excelDtoList);
	}

	public void dutyTemplateExport(HttpServletResponse response, String beginDate, String endDate, ExcelDto excelDto,
			String ids) {
		List<List<Object>> data = new ArrayList<>();
		if (ExcelEnums.CLZQ.getType().equals(excelDto.getType())) {
			data = initDutyCarTemplate(ids);
		} else if (ExcelEnums.RYZB.getType().equals(excelDto.getType())) {
			data = initDutyPersonTemplate(ids);
		} else if (ExcelEnums.WXXFZB.getType().equals(excelDto.getType())) {
			data = initDutyDutyFireFightingTemplate(ids);
		} else if (ExcelEnums.JJZB.getType().equals(excelDto.getType())) {
			data = initDutyDutyFirstAidTemplate(ids);
		}
		// 获取日期
		List<Map<String, Object>> rangeDate = dutyPersonShiftService.getBaseMapper().genRangeDate(beginDate, endDate);
		List<String> dayByMonth = new ArrayList<>();
		rangeDate.forEach(item -> dayByMonth.add((String) item.get("date")));
		exportDutyTemplate(response, excelDto.getClassUrl(), dayByMonth, excelDto, data, true,
				excelDto.getType(),true);
	}

	private List<List<Object>> initDutyDutyFirstAidTemplate(String ids) {
		List<List<Object>> data = new ArrayList<>();
		// 根据id列表获取单位下的微型消防站集合
		List<String> companyIdList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(ids)) {
			companyIdList = Lists.newArrayList(ids.split(","));
		}
		List<Map<String, Object>> personDetailList = dutyFirstAidService.getFirstAidExportData(companyIdList);

		if (!personDetailList.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			personDetailList.forEach(o -> {
				ArrayList<Object> list = new ArrayList<>();
				list.add(row.getAndIncrement());
				list.add(o.get("companyName"));
				list.add(o.get("userName"));
				list.add(o.get("postTypeName"));
				list.add(o.get("firstAidName"));
				data.add(list);
			});
		}
		return data;
	}

	private List<List<Object>> initDutyDutyFireFightingTemplate(String ids) {
		List<List<Object>> data = new ArrayList<>();
		// 根据id列表获取单位下的微型消防站集合
		List<String> companyIdList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(ids)) {
			companyIdList = Lists.newArrayList(ids.split(","));
		}
		List<Map<String, Object>> personDetailList = orgUsrServer.getPersonDetailByCompanyIds(companyIdList);

		if (!personDetailList.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			personDetailList.forEach(o -> {
				DutyFireFightingDto dto = (DutyFireFightingDto) Bean.mapToBean(o, DutyFireFightingDto.class);
				ArrayList<Object> list = new ArrayList<>();
				list.add(row.getAndIncrement());
				list.add(dto.getTeamName() + "@" + dto.getTeamId());
				list.add(dto.getUserName() + "@" + dto.getUserId());
				list.add(dto.getPostTypeName() + "@" + dto.getPostType());
				list.add(o.get("fireStation"));
				data.add(list);
			});
		}
		return data;
	}

	public void dutyInfoExport(HttpServletResponse response, String beginDate, String endDate, ExcelDto excelDto)
			throws ParseException {
		// 获取日期
		List<Map<String, Object>> rangeDate = dutyPersonShiftService.getBaseMapper().genRangeDate(beginDate, endDate);
		List<String> dayByMonth = new ArrayList<>();
		rangeDate.forEach(item -> dayByMonth.add((String) item.get("date")));
		List<List<Object>> data = new ArrayList<>();
		if (ExcelEnums.CLZQ.getType().equals(excelDto.getType())) {
			data = initDutyCarInfo(beginDate, endDate, dayByMonth);
		} else if (ExcelEnums.RYZB.getType().equals(excelDto.getType())) {
			data = initDutyPersonInfo(beginDate, endDate, dayByMonth);
		} else if (ExcelEnums.WXXFZB.getType().equals(excelDto.getType())) {
			data = initDutyDutyFireFighting(beginDate, endDate, dayByMonth);
		} else if (ExcelEnums.JJZB.getType().equals(excelDto.getType())) {
			data = initDutyDutyFirstAid(beginDate, endDate, dayByMonth);
		}

		exportDutyTemplate(response, excelDto.getClassUrl(), dayByMonth, excelDto, data, false, ExcelEnums.WXXFZB.getType(),false);
	}

	private List<List<Object>> initDutyDutyFirstAid(String beginDate, String endDate, List<String> dayByMonth) throws ParseException {

		List<DutyFirstAidDto> list = dutyFirstAidService.downloadList(beginDate, endDate);
		List<List<Object>> data = new ArrayList<>();
		// 组装导出数据
		if (!list.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			list.forEach(o -> {
				ArrayList<Object> detailList = new ArrayList<>();
				detailList.add(row.getAndIncrement());
				detailList.add(o.getTeamName());
				detailList.add(o.getUserName());
				detailList.add(o.getPostTypeName());
				detailList.add(o.getFirstAid());
				List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
				initDutyShift(dayByMonth, dutyShift, detailList);
				data.add(detailList);
			});
		}
		return data;
	}

	private List<List<Object>> initDutyDutyFireFighting(String beginDate, String endDate,
			List<String> dayByMonth) throws ParseException {

		List<DutyFireFightingDto> list = dutyFireFightingService.downloadList(beginDate, endDate);
		List<List<Object>> data = new ArrayList<>();
		// 组装导出数据
		if (!list.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			list.forEach(o -> {
				ArrayList<Object> detailList = new ArrayList<>();
				detailList.add(row.getAndIncrement());
				detailList.add(o.getTeamName());
				detailList.add(o.getUserName());
				detailList.add(o.getPostTypeName());
				detailList.add(o.getFireFighting());
				List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
				initDutyShift(dayByMonth, dutyShift, detailList);
				data.add(detailList);
			});
		}
		return data;
	}

	private List<List<Object>> initDutyCarTemplate(String teamIds) {
		List<List<Object>> data = new ArrayList<>();
		// 根据id列表获取队伍下的人
		List<String> teamIdList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(teamIds)) {
			teamIdList = Lists.newArrayList(teamIds.split(","));
		}
		List<FirefightersDto> firefightersDtoList = fireTeamService.getFighterByTeamId(teamIdList);

		if (!firefightersDtoList.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			firefightersDtoList.forEach(o -> {
				ArrayList<Object> list = new ArrayList<>();
				list.add(row.getAndIncrement());
				list.add(o.getFireTeamName() + "@" + o.getFireTeamId());
				list.add(o.getName() + "@" + o.getSequenceNbr());
				if(!ValidationUtil.isEmpty(o.getJobTitle())) {
					list.add(o.getJobTitle() + "@" + o.getJobTitleCode());
				}
				data.add(list);
			});
		}
		return data;
	}

	private List<List<Object>> initDutyPersonTemplate(String ids) {
		List<List<Object>> data = new ArrayList<>();
		// 根据id列表获取部门下的人
		List<Long> idList = Lists.newArrayList();
		if (!ValidationUtil.isEmpty(ids)) {
			String[] strings = ids.split(",");
			Long[] convert = (Long[]) ConvertUtils.convert(strings, Long.class);
			idList = Arrays.asList(convert);
		}
		try {
			List<CompanyPerson> companyPeople = orgUsrService.returnCompanyPerson(idList);
			if (!companyPeople.isEmpty()) {
				AtomicInteger row = new AtomicInteger(1);
				companyPeople.forEach(item -> {
					List<OrgUsrDto> persons = item.getPersons();
					if (persons != null && !persons.isEmpty()) {
						persons.forEach(o -> {
							ArrayList<Object> list = new ArrayList<>();
							list.add(row.getAndIncrement());
							list.add(o.getSequenceNbr().toString());
							list.add(o.getBizOrgName());
							list.add(item.getBizOrgName() + "@" + item.getSequenceNbr());
							data.add(list);
						});
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BadRequest("系统异常！");
		}
		return data;
	}

	private void exportDutyTemplate(HttpServletResponse response, String classUrl, List<String> dayByMonth,
			ExcelDto excelDto, List<? extends Object> data, Boolean flag, String typeFlag,boolean isTemplete) {
		try {
			// 获取排班类型
			String[] dutyNameList = getDutyNameList();
			Class<?> clz = Class.forName(classUrl);
			ExcelUtil.createDutyTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data, clz,
					dayByMonth, dutyNameList, dataSourcesImpl, flag, typeFlag,isTemplete);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private String[] getDutyNameList() {
		List<String> dutyShiftList = new ArrayList<>();
		List<DutyShiftDto> dutyShiftDtoList = dutyShiftService.queryForDutyShiftList(null, false);
		dutyShiftDtoList.forEach(item -> dutyShiftList.add(item.getName() + "@" + item.getSequenceNbr()));
		return dutyShiftList.toArray(new String[dutyShiftList.size()]);
	}

	private List<List<Object>> initDutyCarInfo(String beginDate, String endDate, List<String> dayByMonth)
			throws ParseException {
		// 查询已值班数据
		List<DutyCarDto> contentList = dutyCarService.downloadList(beginDate, endDate);
		List<List<Object>> data = new ArrayList<>();
		// 组装导出数据
		if (!contentList.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			contentList.forEach(o -> {
				ArrayList<Object> list = new ArrayList<>();
				list.add(row.getAndIncrement());
				list.add(o.getTeamName());
				list.add(o.getUserName());
				list.add(o.getPostTypeName());
				list.add(o.getCarName());
				list.add(o.getDutyArea());
				List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
				initDutyShift(dayByMonth, dutyShift, list);

				data.add(list);
			});
		}
		return data;
	}

	private void initDutyShift(List<String> dayByMonth, List<DutyPersonShiftDto> dutyShift, ArrayList<Object> list) {
		HashMap<String, String> dutyShiftMap = new HashMap<>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		dutyShift.forEach(item -> dutyShiftMap.put(format.format(item.getDutyDate()), item.getShiftName()));

		for (int i = 0; i < dayByMonth.size(); i++) {
			if (dutyShiftMap.containsKey(dayByMonth.get(i))) {
				list.add(dutyShiftMap.get(dayByMonth.get(i)));
			} else {
				list.add(NOT_DUTY);
			}
		}
	}

	private List<List<Object>> initDutyPersonInfo(String beginDate, String endDate, List<String> dayByMonth)
			throws ParseException {
		// 查询已值班数据
		List<DutyPersonDto> contentList = iDutyPersonService.downloadList(beginDate, endDate);
		List<List<Object>> data = new ArrayList<>();
		// 组装导出数据
		if (!contentList.isEmpty()) {
			AtomicInteger row = new AtomicInteger(1);
			contentList.forEach(o -> {
				ArrayList<Object> list = new ArrayList<>();
				list.add(row.getAndIncrement());
				list.add(o.getUserId());
				list.add(o.getUserName());
				list.add(o.getDeptName());
				list.add(o.getPostTypeName());
				list.add(o.getDutyArea());
				List<DutyPersonShiftDto> dutyShift = o.getDutyShift();
				initDutyShift(dayByMonth, dutyShift, list);

				data.add(list);
			});
		}
		return data;
	}

	public void exportByParams(HttpServletResponse response, ExcelDto excelDto, String params) {
		switch (excelDto.getType()) {


		case "XFZJ":
			List<FireExpertsDto> fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false,null,null, null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireExpertsDtoList,
					FireExpertsDto.class, dataSourcesImpl, false);
			break;

		case "XFDW":
			List<FireTeamDto> fireTeamDtoList = fireTeamService.queryFireTeamForList(false,null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireTeamDtoList,
					FireTeamDto.class, dataSourcesImpl, false);
			break;
		case "WXXFZ":
			List<FireStationDto> fireStationDtoList = fireStationService.queryForFireStationList(false,null,null,null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), fireStationDtoList,
					FireStationDto.class, null, false);
			break;
		case "XFRY":
			List<FirefightersExcelDto> firefightersExcelDtoList = firefightersService.exportToExcel(false,null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
					firefightersExcelDtoList, FirefightersExcelDto.class, null, false);
			break;
		case "WBRY":
			List<MaintenancePersonExcleDto> maintenancePersonExcelDtoList = maintenanceCompanyService
					.exportToMaintenancePersonExcel(null);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(),
					maintenancePersonExcelDtoList, MaintenancePersonExcleDto.class, null, false);
			break;

		case JCDWRY:
			// 机场单位人员参数传递为 parentId = xxxxxxx
			String parentIdStr = params.split("=")[1];
			Long parentId = -1l;
			try {
				parentId = Long.parseLong(parentIdStr);
			} catch (NumberFormatException e) {
				throw new BadRequest("导出机场单位时未传递正确parentId");
			}
			List<OrgUsrExcelDto> orgUsrList = orgUsrService.exportPersonToExcelByParentId(parentId);
			ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), orgUsrList,
					OrgUsrExcelDto.class, null, false);
			break;

		default:
			break;
		}
	}

	@Autowired
	private RedisUtils redisUtils;

    public BaseEntity getCurrentInfoNew(String appKey,String product,String token) {
        BaseEntity userModel = new BaseEntity();
        RequestContext.setToken(token);
        RequestContext.setProduct(product);
        RequestContext.setAppKey(appKey);

        FeignClientResult<AgencyUserModel> agencyUserModel = Privilege.agencyUserClient.getme();
        AgencyUserModel userModel1 = agencyUserModel.getResult();
        String keyString = userModel1.getUserId();
        ReginParams params = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(keyString, token)).toString(),
                ReginParams.class);
        userModel.setRecUserId(params.getUserModel().getUserId());
        userModel.setRecUserName(params.getUserModel().getRealName());
        userModel.setRecDate(new Date());
        return userModel;
    }



	public BaseEntity getCurrentInfo() {
		BaseEntity userModel = new BaseEntity();
		FeignClientResult<AgencyUserModel> agencyUserModel = Privilege.agencyUserClient.getme();
		AgencyUserModel userModel1 = agencyUserModel.getResult();
		String keyString = userModel1.getUserId();
		String token = RequestContext.getToken();
		ReginParams params = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(keyString, token)).toString(),
				ReginParams.class);
		userModel.setRecUserId(params.getUserModel().getUserId());
		userModel.setRecUserName(params.getUserModel().getRealName());
		userModel.setRecDate(new Date());
		return userModel;
	}
	public ReginParams getCurrentAllInfo() {
		FeignClientResult<AgencyUserModel> agencyUserModel = Privilege.agencyUserClient.getme();
		AgencyUserModel userModel1 = agencyUserModel.getResult();
		String keyString = userModel1.getUserId();
		String token = RequestContext.getToken();
		return JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(keyString, token)).toString(),
				ReginParams.class);
	}

	public boolean getFlag(Map<String,Object> par){

		ReginParams  reginParams=	getCurrentAllInfo();
		boolean authFalg= false;
		if(reginParams!=null&&reginParams.getPersonIdentity()!=null&&reginParams.getPersonIdentity().getBizOrgCode()!=null) {
			authFalg=true;
		}
		if(authFalg&&par.containsKey("bizOrgCode")&& par.get("bizOrgCode")!=null&&!(par.get("bizOrgCode").toString()).equals("")){
          return true;
		}
		return false;
	}


}
