/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import com.yifu.cloud.plus.v1.check.entity.TCheckBankNo;
import com.yifu.cloud.plus.v1.check.entity.TCheckIdCard;
import com.yifu.cloud.plus.v1.check.entity.TCheckMobile;
import com.yifu.cloud.plus.v1.check.vo.CheckBatchVo;
import com.yifu.cloud.plus.v1.yifu.archives.constants.EmployeeConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.*;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.util.IdCardUtil;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.*;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.ExcelColumnVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.ExcelSheetVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSalaryProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.vo.ListStringVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TBankNameMapVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 人员档案表
 *
 * @author hgw
 * @date 2022-06-20 09:55:06
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties({DaprUpmsProperties.class, DaprCheckProperties.class, DaprSalaryProperties.class})
public class TEmployeeInfoServiceImpl extends ServiceImpl<TEmployeeInfoMapper, TEmployeeInfo> implements TEmployeeInfoService {

	// 缓存信息
	private final CacheManager cacheManager;
	private final TEmployeeProjectService tEmployeeProjectService;
	private final DaprUpmsProperties daprUpmsProperties;
	// // 档案批量更新校验开户行
	private final DaprSalaryProperties salaryProperties;
	// 档案批量更新校验身份证、卡号、手机号
	private final DaprCheckProperties daprCheckProperties;

	private final TEmployeeLogService tEmployeeLogService;
	private final TEmpEducationService tEmpEducationService;
	// 档案批量更新使用的紧急联系人
	private final TEmpContactInfoService tEmpContactInfoService;
	private final TSettleDomainService tSettleDomainService;

	private final TEmployeeContractAuditMapper contractAuditMapper;

	private final TEmployeeContractInfoService contractServicer;

	private final TEmpOtherFileService otherFileService;

	private final TAttaInfoService attaInfoService;

	private final TEmpOtherFileService empOtherFileService;

	private final TPreEmpDeclarationMapper declarationMapper;
	private final TArchivesLimitMapper tArchivesLimitMapper;
	private final AtomicInteger updateAtomicInteger = new AtomicInteger(0);

	private final TCompleteMonitorService completeMonitorService;

	private final TEmpBadRecordService tEmpBadRecordService;
	private final TEmpWorkRecordingService tEmpWorkRecordingService;
	private final TEmpFamilyService tEmpFamilyService;
	private final TEmpProfessionalQualificationService tEmpProfessionalQualificationService;
	private final TEmpDisabilityInfoService tEmpDisabilityInfoService;

	private final EmployeeRegistrationPreService registrationPreService;

	private final LGuaziOfferRecordService lGuaziOfferRecordService;

	private final TGzContractService tGzContractService;

	private final TGzPushEntryService tGzPushEntryService;

	private final TEmployeeContractPreMapper contractPreMapper;

	@Autowired
	private OSSUtil ossUtil;

	ExcelUtil<Object> excelUtil = new ExcelUtil<>(Object.class);

	private final TGzOfferInfoMapper gzOfferInfoMapper;

	@Override
	public IPage<TEmployeeInfo> getPage(Page<TEmployeeInfo> page, TEmployeeInfo employeeInfo) {
		return baseMapper.getPage(page, employeeInfo);
	}

	@Override
	public IPage<TEmployeeInfo> getLeavePage(Page<TEmployeeInfo> page, TEmployeeInfo employeeInfo) {
		long leavePageCount;
		if (Common.isEmpty(employeeInfo.getUnitName()) && Common.isEmpty(employeeInfo.getDeptName())
				&& Common.isEmpty(employeeInfo.getDeptNo()) && Common.isEmpty(employeeInfo.getAuthSql())) {
			leavePageCount = baseMapper.getLeavePageCount(employeeInfo);
			page.setTotal(leavePageCount);
			if (leavePageCount > 0L) {
				page.setPages((long) Math.ceil(1.0 * leavePageCount / page.getSize()));
			}
			if (page.getCurrent() < 1) {
				page.setCurrent(1L);
			}
			if (page.getSize() < 1) {
				page.setSize(10L);
			}
			List<TEmployeeInfo> list = baseMapper.getLeavePage(employeeInfo, (page.getCurrent() - 1) * page.getSize(), page.getSize());
			page.setRecords(list);
			return page;
		} else {
			return baseMapper.getLeaveIPage(page, employeeInfo);
		}
	}

	@Override
	public List<TEmployeeInfo> getList(TEmployeeInfo employeeInfo) {
		return baseMapper.getList(employeeInfo);
	}

	@Override
	public R<TEmployeeInfo> checkIdCard(TEmployeeInfo employeeInfo) {
		List<TEmployeeInfo> list = baseMapper.getList(employeeInfo);
		if (list != null && !list.isEmpty()) {
			employeeInfo = list.get(0);
			if (employeeInfo.getFileStatus() == CommonConstants.ZERO_INT) {
				return R.failed("该人员已存在，禁止重复添加");
			} else {
				return new R<>(CommonConstants.dingleDigitIntArray[2], "该人员在离职库已存在，是否'恢复档案'?", employeeInfo);
			}
		} else {
			// 调用校验服务
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(employeeInfo.getEmpName());
			checkIdCard.setIdCard(employeeInfo.getEmpIdcard());
			R<TCheckIdCard> checkListR = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
					, "/tcheckidcard/inner/checkIdCardSingle", checkIdCard, TCheckIdCard.class, SecurityConstants.FROM_IN);
			if (checkListR != null && checkListR.getData() != null) {
				TCheckIdCard check = checkListR.getData();
				if (check == null || Common.isEmpty(check.getIsTrue())) {
					return R.failed(EmployeeConstants.CHECK_NO_RESPONSE);
				} else if (check.getIsTrue() == CommonConstants.ZERO_INT) {
					return R.failed(check.getReason());
				}
			} else {
				return R.failed(EmployeeConstants.CHECK_NO_RESPONSE);
			}
			return R.ok();
		}
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取五位字符型数字
	 * @Author: hgw
	 * @Date: 2022/6/21 17:35
	 * @return: 五位字符型数字
	 **/
	private String getFiveNum(String nowNums) {
		if (nowNums.length() >= 5) {
			return nowNums.substring(0, 5);
		}
		String[] zeroArr = {"0", "00", "000", "0000"};
		int num = 4 - nowNums.length();
		return zeroArr[num] + nowNums;
	}

	@Override
	public R<Boolean> updateEmployee(TEmployeeInfo employeeInfo) {

		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		if (Common.isEmpty(employeeInfo) || Common.isEmpty(employeeInfo.getId())) {
			return R.failed("请传ID");
		}
		TEmployeeInfo old = this.getById(employeeInfo.getId());
		if (old == null || Common.isEmpty(old.getId())) {
			return R.failed("根据id未找到档案！" + employeeInfo.getId());
		}
		// 获取历史附件信息   fxj 2024-09-09
		getAttaInfo(old);

		// 校验手机号：
		if (Common.isEmpty(employeeInfo.getEmpPhone())) {
			return R.failed("手机号必填！");
		} else {
			TEmployeeInfo check = new TEmployeeInfo();
			check.setDeleteFlag(CommonConstants.STATUS_NORMAL);
			check.setEmpPhone(employeeInfo.getEmpPhone());
			List<TEmployeeInfo> list = baseMapper.getList(check);
			if (list != null && !list.isEmpty()) {
				for (TEmployeeInfo e : list) {
					if (!e.getEmpIdcard().equals(employeeInfo.getEmpIdcard())) {
						return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR, employeeInfo.getEmpIdcard()));
					}
				}
			}
			// 调用校验服务-校验手机号
			TCheckMobile checkMobile = new TCheckMobile();
			checkMobile.setMobile(employeeInfo.getEmpPhone());
			R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
					, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
			if (a != null && a.getData() != null) {
				checkMobile = a.getData();
				if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
					if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
						return R.failed(checkMobile.getMessage());
					}
				} else {
					return R.failed("校验服务错误，请联系管理员！");
				}
			}
		}

		employeeInfo.setUpdateBy(user.getId());
		employeeInfo.setUpdateTime(LocalDateTime.now());

		// 更新学历-房
		TEmpEducation education = new TEmpEducation();
		this.doUpdateEducationCore(education, employeeInfo);

		// 更新其他附件信息  fxj 2024-09-09
		if (updateOtherAtta(employeeInfo)) {
			// 获取最新附件信息  fxj 2024-09-09
			getAttaInfo(employeeInfo);
		} else {
			old.setOtherFiles(null);
			employeeInfo.setOtherFiles(null);
		}
		// 更新附件信息  hgw 2024-10-15
		updateAtta(employeeInfo, old);
		// 更新成功或失败，都清空list，日志分在每个对象里了 hgw 2024-10-16
		old.setAttaList(null);
		employeeInfo.setAttaList(null);
		// 记录变更日志
		tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], old.getId(), "", old, employeeInfo);
		return R.ok(this.updateById(employeeInfo));
	}

	private boolean updateOtherAtta(TEmployeeInfo employeeInfo) {
		List<TEmpOtherFile> otherFileList = employeeInfo.getOtherFiles();
		boolean flag = false;
		if (Common.isNotNull(otherFileList)) {
			List<TAttaInfo> attaInfos = new ArrayList<>();
			for (TEmpOtherFile otherFile : otherFileList) {
				//处理新增或删除其他附件分租的逻辑
				if (!flag) {
					flag = handleOtherFile(otherFile);
				} else {
					handleOtherFile(otherFile);
				}
				if (Common.isNotNull(otherFile.getAttaList())) {
					attaInfos.addAll(otherFile.getAttaList());
				}
			}
			if (Common.isNotNull(attaInfos)) {
				List<String> deleteIds = new ArrayList<>();
				List<TAttaInfo> adds = new ArrayList<>();
				for (TAttaInfo attaInfo : attaInfos) {
					if (CommonConstants.ZERO_STRING.equals(attaInfo.getHandleType())) {
						adds.add(attaInfo);
					}
					if (CommonConstants.TWO_STRING.equals(attaInfo.getHandleType())) {
						deleteIds.add(attaInfo.getId());
					}
				}
				if (Common.isNotNull(deleteIds)) {
					attaInfoService.removeBatchByIds(deleteIds);
					flag = true;
				}
				if (Common.isNotNull(adds)) {
					attaInfoService.updateBatchById(adds);
					flag = true;
				}
			}
		}
		return flag;
	}

	// 仿写房工更新附件
	private boolean updateAtta(TEmployeeInfo employeeInfo, TEmployeeInfo old) {
		List<TAttaInfo> attaInfos = employeeInfo.getAttaList();
		boolean flag = false;
		if (Common.isNotNull(attaInfos)) {
			List<String> deleteIds = new ArrayList<>();
			List<TAttaInfo> adds = new ArrayList<>();
			for (TAttaInfo attaInfo : attaInfos) {
				if (CommonConstants.ZERO_STRING.equals(attaInfo.getHandleType())) {
					setAttaLogByRelationType(employeeInfo, attaInfo);
					adds.add(attaInfo);
				}
				if (CommonConstants.TWO_STRING.equals(attaInfo.getHandleType())) {
					setAttaLogByRelationType(old, attaInfo);
					deleteIds.add(attaInfo.getId());
				}
				if (CommonConstants.ONE_STRING.equals(attaInfo.getHandleType())
						|| CommonConstants.THREE_STRING.equals(attaInfo.getHandleType())) {
					setAttaLogByRelationType(employeeInfo, attaInfo);
					setAttaLogByRelationType(old, attaInfo);
				}
			}
			if (Common.isNotNull(deleteIds)) {
				attaInfoService.removeBatchByIds(deleteIds);
				flag = true;
			}
			if (Common.isNotNull(adds)) {
				attaInfoService.updateBatchById(adds);
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * @param employeeInfo
	 * @param attaInfo
	 * @Description: 根据类型塞附件，记录变更日志使用的
	 * @Author: hgw
	 * @Date: 2024/10/16 10:34
	 * @return: void
	 **/
	private void setAttaLogByRelationType(TEmployeeInfo employeeInfo, TAttaInfo attaInfo) {
		/**
		 * 关系类型(0客户附件1联系人附件2跟进记录附件3合同附件4合同归档附件5报价单6招投标7业务评估8二维码9身份证 10 户口本
		 * ；21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)；0（最高教育经历)；2（执业资格证书)；24 身份证国徽
		 * 25 户口本本人页26学信27预入职其他附件
		 */
		switch (attaInfo.getRelationType()) {
			case "9":
				employeeInfo.setAttaIdCardOne(attaInfo);
				break;
			case "24":
				employeeInfo.setAttaIdCardTwo(attaInfo);
				break;
			case "10":
				employeeInfo.setAttaRegistrationOne(attaInfo);
				break;
			case "25":
				employeeInfo.setAttaRegistrationTwo(attaInfo);
				break;
			case "21":
				employeeInfo.setAttaDeclearOne(attaInfo);
				break;
			case "22":
				employeeInfo.setAttaDeclearTwo(attaInfo);
				break;
			default:
				break;
		}
	}

	private boolean handleOtherFile(TEmpOtherFile otherFile) {
		boolean flag = false;
		// 新增时先增加 empOtherFile
		if (CommonConstants.ZERO_STRING.equals(otherFile.getHandleType())) {
			empOtherFileService.save(otherFile);
			flag = true;
			if (Common.isNotNull(otherFile.getAttaList())) {
				for (TAttaInfo info : otherFile.getAttaList()) {
					info.setDomainId(otherFile.getId());
				}
			}
			// 更新
		}
		if (CommonConstants.ONE_STRING.equals(otherFile.getHandleType())) {
			flag = true;
			if (Common.isNotNull(otherFile.getId())) {
				empOtherFileService.updateById(otherFile);
				if (Common.isNotNull(otherFile.getAttaList())) {
					for (TAttaInfo info : otherFile.getAttaList()) {
						info.setDomainId(otherFile.getId());
					}
				}
			}
			// 删除时
		}
		if (CommonConstants.THREE_STRING.equals(otherFile.getHandleType())) {
			if (Common.isNotNull(otherFile.getId())) {
				if (Common.isNotNull(otherFile.getAttaList())) {
					for (TAttaInfo info : otherFile.getAttaList()) {
						info.setDomainId(otherFile.getId());
					}
				}
			}
			// 删除时
		} else if (CommonConstants.TWO_STRING.equals(otherFile.getHandleType())) {
			empOtherFileService.removeById(otherFile.getId());
			flag = true;
		}
		return flag;
	}

	private void getAttaInfo(TEmployeeInfo emp) {
		List<TEmpOtherFile> otherFiles = otherFileService.getListByEmpId(emp.getId());
		if (Common.isNotNull(otherFiles)) {
			List<TAttaInfo> attaInfos;
			for (TEmpOtherFile file : otherFiles) {
				attaInfos = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, file.getId()));
				if (Common.isNotNull(attaInfos)) {
					URL url;
					for (TAttaInfo atta : attaInfos) {
						url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
						if (Common.isNotNull(url)) {
							atta.setAttaUrl(url.toString());
						}
					}
				}
				file.setAttaList(attaInfos);
			}
		}
		emp.setOtherFiles(otherFiles);
	}

	// 仿写房工附件接口
	private void getEmpAttaInfo(TEmployeeInfo emp) {
		List<TAttaInfo> attaInfos = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, emp.getId()));
		if (Common.isNotNull(attaInfos)) {
			URL url;
			for (TAttaInfo atta : attaInfos) {
				url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
				if (Common.isNotNull(url)) {
					atta.setAttaUrl(url.toString());
				}
			}
		}
		emp.setAttaList(attaInfos);
	}

	@Override
	public R<String> deleteEmployee(String id) {
		TEmployeeInfo employee = this.getById(id);
		if (employee != null) {
			if (employee.getStatus() != CommonConstants.ZERO_INT) {
				return R.failed("非草稿状态，无法删除！");
			}
			if (employee.getContractStatus() != CommonConstants.ZERO_INT) {
				return R.failed("合同状态非初始，无法删除！");
			}
			if (employee.getInsuranceStatus() != CommonConstants.ZERO_INT) {
				return R.failed("商险状态非初始，无法删除！");
			}
			if (employee.getSocialStatus() != CommonConstants.ZERO_INT) {
				return R.failed("社保状态非初始，无法删除！");
			}
			if (employee.getFundStatus() != CommonConstants.ZERO_INT) {
				return R.failed("公积金状态非初始，无法删除！");
			}
			if (employee.getSalaryStatus() != CommonConstants.ZERO_INT) {
				return R.failed("工资状态非初始，无法删除！");
			}
			employee.setDeleteFlag(CommonConstants.STATUS_DEL);
			// 获取项目档案，传参1，不过滤项目状态
			List<TEmployeeProject> projectList = tEmployeeProjectService.getListByEmpId(id, CommonConstants.ONE_INT);
			if (projectList != null && !projectList.isEmpty()) {
				for (TEmployeeProject project : projectList) {
					project.setDeleteFlag(CommonConstants.STATUS_DEL);
				}
				tEmployeeProjectService.updateBatchById(projectList);
			}
			this.updateById(employee);
			return R.ok("已删除");
		} else {
			return R.failed("未找到人员档案信息");
		}
	}

	@Override
	public R<List<ErrorMessageVO>> batchDeleteEmployee(List<String> idList) {
		if (idList == null || idList.isEmpty()) {
			return R.failed("请选择！");
		}
		List<ErrorMessageVO> errorMessageList = new ArrayList<>();
		TEmployeeInfo employee;
		String id;
		List<TEmployeeInfo> canDeleteList = new ArrayList<>();
		ErrorMessageVO errorMessageVO;
		Set<String> errorMsg;
		boolean isTrue = true;
		for (int i = 0; i < idList.size(); i++) {
			errorMsg = new HashSet<>();
			id = idList.get(i);
			employee = this.getById(id);
			if (employee != null) {
				if (employee.getStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("非草稿状态！");
				}
				if (employee.getContractStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("合同状态非初始！");
				}
				if (employee.getInsuranceStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("商险状态非初始！");
				}
				if (employee.getSocialStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("社保状态非初始！");
				}
				if (employee.getFundStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("公积金状态非初始！");
				}
				if (employee.getSalaryStatus() != CommonConstants.ZERO_INT) {
					errorMsg.add("工资状态非初始！");
				}
				// 数据合法情况
				if (CollUtil.isNotEmpty(errorMsg)) {
					isTrue = false;
					errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ZERO_INT, employee.getEmpName()
							, employee.getEmpIdcard(), errorMsg);
					// 数据不合法
				} else {
					errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ONE_INT, employee.getEmpName()
							, employee.getEmpIdcard(), errorMsg);
					canDeleteList.add(employee);
				}
				errorMessageList.add(errorMessageVO);
			} else {
				isTrue = false;
				errorMsg.add("未找到人员！");
				errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ZERO_INT, null, null, errorMsg);
				errorMessageList.add(errorMessageVO);
			}
		}
		if (!isTrue) {
			return R.failed(errorMessageList);
		} else {
			List<TEmployeeProject> projectList;
			for (TEmployeeInfo employeeInfo : canDeleteList) {
				employeeInfo.setDeleteFlag(CommonConstants.STATUS_DEL);
				// 获取项目档案，传参1，不过滤项目状态
				projectList = tEmployeeProjectService.getListByEmpId(employeeInfo.getId(), CommonConstants.ONE_INT);
				if (projectList != null && !projectList.isEmpty()) {
					for (TEmployeeProject project : projectList) {
						project.setDeleteFlag(CommonConstants.STATUS_DEL);
					}
					tEmployeeProjectService.updateBatchById(projectList);
				}
				this.updateById(employeeInfo);
			}
			return R.ok();
		}
	}

	private ErrorMessageVO getErrorMessageVO(int i, int result, String empName, String idCard, Set<String> errorMsg) {
		ErrorMessageVO errorMessageVO = new ErrorMessageVO();
		errorMessageVO.setLineNum(i + 2);
		// 结果：0错误；1正确
		errorMessageVO.setResult(result);
		errorMessageVO.setEmpName(empName);
		errorMessageVO.setEmpIdCard(idCard);
		errorMessageVO.setErrorSet(errorMsg);
		return errorMessageVO;
	}

	@Override
	public R<String> restoreEmployee(String id, String projectIds) {
		TEmployeeInfo employee = this.getById(id);
		if (employee != null) {
			if (employee.getFileStatus() != CommonConstants.ONE_INT) {
				return R.failed("该人员已不在离职档案中！");
			}
			TEmployeeInfo old = this.getById(id);
			int projectNum = 0;
			if (Common.isNotNull(projectIds)) {
				String[] idArr = projectIds.split(",");
				// 获取项目档案，传参1，不过滤项目状态
				List<TEmployeeProject> projectList = tEmployeeProjectService.getListByEmpId(id, CommonConstants.ONE_INT);
				if (projectList != null && !projectList.isEmpty()) {
					for (String pid : idArr) {
						for (TEmployeeProject project : projectList) {
							if (project.getId().equals(pid)) {
								project.setLeaveReason("");
								project.setLeaveRemark("");
								project.setLeaveUser("");
								project.setLeaveTime(null);
								project.setProjectStatus(CommonConstants.ZERO_INT);
								tEmployeeProjectService.updateById(project);

								// 增-同步处理CSP入离职申请为已处理，加日志
								tEmployeeProjectService.doSaveBelongDept(project, CommonConstants.ONE_STRING);
								// 更新入职待建档状态为已完成
								registrationPreService.updatePreStatusToEnd(project.getDeptNo(),project.getEmpIdcard());

								projectNum++;
							}
						}
					}
				}
			}
			employee.setFileStatus(CommonConstants.ZERO_INT);
			employee.setLeaveReason("");
			employee.setLeaveRemark("");
			employee.setLeaveUser("");
			employee.setLeaveUserName("");
			employee.setLeaveTime(null);
			employee.setProjectNum(projectNum);
			this.updateById(employee);

			// 记录变更日志
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], old.getId(), "", old, employee);

			return R.ok("已复档");
		} else {
			return R.failed("未找到离职档案信息");
		}
	}

	@Override
	public R<List<ErrorMessageVO>> batchMinusEmployee(InputStream inputStream) {
		List<ErrorMessageVO> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeLeaveVO> util1 = new ExcelUtil<>(EmployeeLeaveVO.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcel.read(inputStream, EmployeeLeaveVO.class, new ReadListener<EmployeeLeaveVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmployeeLeaveVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeLeaveVO data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						Set<String> errors = new HashSet<>();
						errors.add(errorMessage.getMessage());
						ErrorMessageVO errorMessageVO = getErrorMessageVO(errorMessage.getLineNum(), CommonConstants.ZERO_INT, "-"
								, "-", errors);
						errorMessageList.add(errorMessageVO);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					if (!cachedDataList.isEmpty()) {
						batchMinusEmployeeCore(cachedDataList, errorMessageList);
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (errorMessageList.isEmpty()) {
			return R.ok();
		} else {
			return R.failed(errorMessageList);
		}
	}

	/**
	 * @param excelVOList
	 * @param errorMessageList
	 * @Description: 批量减档-核心
	 * @Author: hgw
	 * @Date: 2022/7/11 10:45
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.archives.vo.ErrorMessageVO>>
	 **/
	public R<List<ErrorMessageVO>> batchMinusEmployeeCore(List<EmployeeLeaveVO> excelVOList
			, List<ErrorMessageVO> errorMessageList) {
		if (excelVOList == null || excelVOList.isEmpty()) {
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		ErrorMessageVO errorMessageVO;
		Map<Integer, Integer> errorMsgMap = new HashMap<>();

		TEmployeeInfo oldEmployee;
		TEmployeeInfo employee;
		// 可以更新的列表
		List<TEmployeeInfo> canDeleteList = new ArrayList<>();
		// 为了记录变更日志而加的
		List<TEmployeeInfo> deleteOldList = new ArrayList<>();
		Set<String> errorMsg;
		EmployeeLeaveVO excel;

		List<String> idCardList = new ArrayList<>();
		String idCard;
		boolean isTrue = true;
		for (int i = 0; i < excelVOList.size(); i++) {
			errorMsg = new HashSet<>();
			excel = excelVOList.get(i);
			// 判空
			idCard = excel.getEmpIdcard();
			if (Common.isEmpty(idCard)) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_IDCARD_MUST, excel.getEmpIdcard()));
				errorMsgMap.put(i + 2, CommonConstants.ZERO_INT);
			} else {
				idCardList.add(idCard);
			}
			if (Common.isEmpty(excel.getEmpName())) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EMPNAME_MUST, excel.getEmpIdcard()));
				errorMsgMap.put(i + 2, CommonConstants.ZERO_INT);
			}
			if (Common.isEmpty(excel.getLeaveReason())) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_LEAVEREASON_MUST, excel.getEmpIdcard()));
				errorMsgMap.put(i + 2, CommonConstants.ZERO_INT);
			}
			if (Common.isNotNull(excel.getLeaveRemark()) && excel.getLeaveRemark().length() > 200) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_LEAVEREMARK_LENGTH, excel.getEmpIdcard()));
				errorMsgMap.put(i + 2, CommonConstants.ZERO_INT);
			}
			// 数据不合法
			if (!CollUtil.isEmpty(errorMsg)) {
				isTrue = false;
				errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ZERO_INT, excel.getEmpName()
						, idCard, errorMsg);
				errorMessageList.add(errorMessageVO);
			}
		}
		// 查找档案库
		Map<String, TEmployeeInfo> existEmpMap = new HashMap<>();
		if (!idCardList.isEmpty()) {
			List<TEmployeeInfo> cards = baseMapper.getListByIdCard(idCardList);
			for (TEmployeeInfo employeeInfo : cards) {
				existEmpMap.put(employeeInfo.getEmpIdcard(), employeeInfo);
			}
		}
		List<TEmployeeProject> projectList;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get(i + 2))) {
				continue;
			}
			errorMsg = new HashSet<>();
			excel = excelVOList.get(i);
			employee = existEmpMap.get(excel.getEmpIdcard());
			// 档案存在
			if (employee != null) {
				// 档案在职
				if (employee.getFileStatus() == CommonConstants.ZERO_INT) {
					projectList = tEmployeeProjectService.getListByEmpId(employee.getId(), CommonConstants.ZERO_INT);
					if (projectList != null && !projectList.isEmpty()) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_HAVE_PROJECT, employee.getEmpIdcard()));
					} else {
						oldEmployee = new TEmployeeInfo();
						BeanUtil.copyProperties(employee, oldEmployee);
						// 开始减档
						employee.setFileStatus(CommonConstants.ONE_INT);
						employee.setLeaveUser(user.getId());
						employee.setLeaveUserName(user.getNickname());
						employee.setLeaveTime(new Date());
						employee.setLeaveReason(excel.getLeaveReason());
						employee.setLeaveRemark(excel.getLeaveRemark());
						canDeleteList.add(employee);
						deleteOldList.add(oldEmployee);
					}
				} else {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NOT_EXISTS, excel.getEmpIdcard()));
				}
			} else {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NOT_EXISTS, excel.getEmpIdcard()));
			}
			// 数据不合法
			if (!CollUtil.isEmpty(errorMsg)) {
				isTrue = false;
				errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ZERO_INT, excel.getEmpName()
						, excel.getEmpIdcard(), errorMsg);
			} else {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_TRUE, excel.getEmpIdcard()));
				errorMessageVO = this.getErrorMessageVO(i, CommonConstants.ONE_INT, excel.getEmpName()
						, excel.getEmpIdcard(), errorMsg);
			}
			errorMessageList.add(errorMessageVO);
		}
		if (!isTrue) {
			return R.failed(errorMessageList);
		} else {
			// 仅更新自己
			this.updateBatchById(canDeleteList);
			for (int i = 0; i < canDeleteList.size(); i++) {
				this.updateById(canDeleteList.get(i));
				// 记录变更日志
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], canDeleteList.get(i).getId(), "", deleteOldList.get(i), canDeleteList.get(i));
			}
			errorMessageList.clear();
			return R.ok();
		}
	}

	@Override
	public R<String> minusEmployee(String id, String leaveReason, String leaveRemark) {
		TEmployeeInfo oldEmp = this.getById(id);
		TEmployeeInfo employee = this.getById(id);
		if (employee != null) {
			// 获取项目档案，传参0，过滤项目状态
			List<TEmployeeProject> projectList = tEmployeeProjectService.getListByEmpId(id, CommonConstants.ZERO_INT);
			if (projectList != null && !projectList.isEmpty()) {
				return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_HAVE_PROJECT, employee.getEmpIdcard()));
			}
			YifuUser user = SecurityUtils.getUser();
			if (user == null || Common.isEmpty(user.getId())) {
				return R.failed("请登录！");
			}
			employee.setFileStatus(CommonConstants.ONE_INT);
			employee.setLeaveUser(user.getId());
			employee.setLeaveUserName(user.getNickname());
			employee.setLeaveTime(new Date());
			employee.setLeaveReason(leaveReason);
			employee.setLeaveRemark(leaveRemark);
			this.updateById(employee);
			// 记录变更日志
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], id, "", oldEmp, employee);
			return R.ok("已减档");
		} else {
			return R.failed("未找到人员档案信息");
		}
	}

	@Override
	//@GlobalTransactional // 分布式事务注解
	//@Transactional(rollbackFor = Exception)
	@Transactional
	public R<String> addNewEmployee(TEmployeeInfo employeeInfo) {
		// 新建人员档案
		R<TEmployeeInfo> checks = this.saveNewEmpLoyee(employeeInfo, CommonConstants.dingleDigitStrArray[4]);
		if (checks != null && checks.getCode() != CommonConstants.SUCCESS) return R.failed(checks.getMsg());

		// 新建项目-雨辰
		tEmployeeProjectService.saveEmployeeProjectInfo(employeeInfo);

		// 新建学历-房
		TEmpEducation education = new TEmpEducation();
		this.doUpdateEducationCore(education, employeeInfo);

		return R.ok();
	}


	/**
	 * @param employeeInfo 姓名、身份证、手机号、员工类型
	 * @param fileSource   4人员档案新建、5项目档案新建、1社保/公积金、3商险、2薪酬
	 * @Description: 新增档案
	 * @Author: hgw
	 * @Date: 2022/6/21 18:07
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo>
	 **/
	public R<TEmployeeInfo> saveNewEmpLoyee(TEmployeeInfo employeeInfo, String fileSource) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed("请登录！");
		}
		R<TEmployeeInfo> failed = this.checkEmployeeInfoR(employeeInfo);
		if (failed != null) return failed;
		if (Common.isEmpty(fileSource)) {
			return R.failed("人员档案来源必填！(4人员档案新建、5项目档案新建、1社保/公积金、3商险、2薪酬)");
		}
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, employeeInfo.getDeptNo())
				.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
				.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
		if (Common.isEmpty(tSettleDomain)) {
			return R.failed("对应项目编码的项目已停止合作");
		}
		TEmployeeInfo check = new TEmployeeInfo();
		check.setEmpName(employeeInfo.getEmpName());
		check.setEmpIdcard(employeeInfo.getEmpIdcard());
		check.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		R<TEmployeeInfo> checks = this.checkIdCard(check);
		if (checks.getCode() != CommonConstants.SUCCESS) {
			return R.failed(checks.getMsg());
		}
		// 校验手机号：
		if (Common.isEmpty(employeeInfo.getEmpPhone())) {
			return R.failed("手机号必填！");
		} else {
			check = new TEmployeeInfo();
			check.setDeleteFlag(CommonConstants.STATUS_NORMAL);
			check.setEmpPhone(employeeInfo.getEmpPhone());
			List<TEmployeeInfo> list = baseMapper.getList(check);
			if (list != null && !list.isEmpty()) {
				return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR, employeeInfo.getEmpIdcard()));
			}

			// 调用校验服务-校验手机号
			TCheckMobile checkMobile = new TCheckMobile();
			checkMobile.setMobile(employeeInfo.getEmpPhone());
			R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
					, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
			if (a != null && a.getData() != null) {
				checkMobile = a.getData();
				if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
					if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
						return R.failed(checkMobile.getMessage());
					}
				} else {
					return R.failed("校验服务错误，请联系管理员！");
				}
			}
		}
		// 字典：4人员档案新建、5项目档案新建、1社保/公积金、3商险、2薪酬
		this.setBaseData(employeeInfo, fileSource, user);

		// 生成主码：
		if (Common.isEmpty(employeeInfo.getEmpCode())) {
			employeeInfo.setEmpCode(this.getCode());
		}
		this.save(employeeInfo);
		return R.ok(employeeInfo);
	}

	/**
	 * @param employeeInfo
	 * @Description: 生成基础性别等信息
	 * @Author: hgw
	 * @Date: 2022/6/24 16:51
	 * @return: void
	 **/
	private void setBaseSexInfo(TEmployeeInfo employeeInfo) {
		String idCard = employeeInfo.getEmpIdcard();
		if (Common.isNotNull(idCard) && Common.isEmpty(employeeInfo.getEmpSex()) && idCard.length() > 14) {

			// 出生日期
			java.sql.Date date = IdCardUtil.getBirthdate(idCard);
			employeeInfo.setEmpBirthday(date);

			// 性别
			if (idCard.length() > 17) {
				if (Integer.parseInt(idCard.substring(16, 17)) % 2 == 1) {
					employeeInfo.setEmpSex(CommonConstants.SEX_MAN);
				} else {
					employeeInfo.setEmpSex(CommonConstants.SEX_WONMAN);
				}
			}

			// 年龄
			int idCardYear = Integer.parseInt(idCard.substring(6, 10));
			employeeInfo.setEmpAge(DateUtil.getAge(idCardYear));
		}
	}

	/**
	 * @param employeeInfo
	 * @Description: 校验空值
	 * @Author: hgw
	 * @Date: 2022/6/22 17:14
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo>
	 **/
	private R<TEmployeeInfo> checkEmployeeInfoR(TEmployeeInfo employeeInfo) {
		if (Common.isEmpty(employeeInfo.getEmpName())) {
			return R.failed("员工姓名必填！");
		}
		if (Common.isEmpty(employeeInfo.getEmpIdcard())) {
			return R.failed("员工身份证必填！");
		}
		if (Common.isEmpty(employeeInfo.getEmpPhone())) {
			return R.failed("手机号必填！");
		}
		if (Common.isEmpty(employeeInfo.getEmpNatrue())) {
			return R.failed("员工类型必填！");
		}
		return null;
	}

	private void checkEmployeeVOR(long lineNum, EmployeeInsertVO employeeInfo, Map<Long, ErrorMessage> errorMsgMap, Set<String> errorMsg) {
		if (Common.isEmpty(employeeInfo.getEmpIdcard())) {
			errorMsg.add("身份证号必填");
			errorMsgMap.put(lineNum, new ErrorMessage("身份证号必填"));
		}
		if (Common.isEmpty(employeeInfo.getDeptNo())) {
			errorMsg.add("项目编码必填");
			errorMsgMap.put(lineNum, new ErrorMessage("项目编码必填"));
		} else if (employeeInfo.getDeptNo().length() > 20) {
			errorMsg.add("项目编码超长");
			errorMsgMap.put(lineNum, new ErrorMessage("项目编码超长"));
		}
		if (Common.isEmpty(employeeInfo.getEmpName())) {
			errorMsg.add("员工姓名必填");
			errorMsgMap.put(lineNum, new ErrorMessage("员工姓名必填"));
		}
		if (Common.isEmpty(employeeInfo.getEmpPhone())) {
			errorMsg.add("手机号码必填");
			errorMsgMap.put(lineNum, new ErrorMessage("手机号码必填"));
		}
		if (Common.isEmpty(employeeInfo.getEmpRegisType())) {
			errorMsg.add("户口性质必填");
			errorMsgMap.put(lineNum, new ErrorMessage("户口性质必填"));
		}
		//婚姻状态不可为空
		if (Common.isEmpty(employeeInfo.getEmpMarriStatus())) {
			errorMsg.add(EmployeeConstants.MARRY_STATUS_NOT_NULL);
			errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.MARRY_STATUS_NOT_NULL));
		}
		//政治面貌不可为空
		if (Common.isEmpty(employeeInfo.getPoliticalStatus())) {
			errorMsg.add(EmployeeConstants.POLITICAL_STATUS_NOT_NULL);
			errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.POLITICAL_STATUS_NOT_NULL));
		}
		if (Common.isEmpty(employeeInfo.getEmpNatrue())) {
			errorMsg.add("员工类型必填！");
			errorMsgMap.put(lineNum, new ErrorMessage("员工类型必填！"));
		} else if (EmployeeConstants.EMP_NATRUE_ZERO.equals(employeeInfo.getEmpNatrue())
				|| EmployeeConstants.EMP_NATRUE_ONE.equals(employeeInfo.getEmpNatrue())
				|| EmployeeConstants.EMP_NATRUE_THREE.equals(employeeInfo.getEmpNatrue())) {
			// 2.员工类型为外包和派遣和内部员工，额外必填项有：身份证开始日期、身份证截止日期、民族、户籍所在（省市县）、户口性质、档案所在地（省市县）、是否大专及以上、通信地址
			if (Common.isEmpty(employeeInfo.getValidityStart())) {
				errorMsg.add(EmployeeConstants.VALIDITY_START);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.VALIDITY_START));
			}
			if (Common.isEmpty(employeeInfo.getValidityEnd())) {
				errorMsg.add(EmployeeConstants.VALIDITY_END);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.VALIDITY_END));
			}
			if (Common.isEmpty(employeeInfo.getEmpNational())) {
				errorMsg.add(EmployeeConstants.EMP_NATIONAL);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.EMP_NATIONAL));
			}
			/*if (Common.isEmpty(employeeInfo.getIdProvince())) {
				errorMsg.add(EmployeeConstants.ID_PROVINCE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.ID_PROVINCE));
			}*/
			if (Common.isEmpty(employeeInfo.getFileProvince())) {
				errorMsg.add(EmployeeConstants.FILE_PROVINCE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.FILE_PROVINCE));
			}
			//2024-09-26 fxj 档案地县选填 MVP1.6.11
			if (Common.isEmpty(employeeInfo.getFileCity())) {
				errorMsg.add(EmployeeConstants.FILE_PROVINCE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.FILE_PROVINCE));
			}

			if (Common.isEmpty(employeeInfo.getContactTown())) {
				errorMsg.add(EmployeeConstants.CONTACT_PROVINCE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.CONTACT_PROVINCE));
			}
			if (Common.isEmpty(employeeInfo.getContactAddress())) {
				errorMsg.add(EmployeeConstants.CONTACT_ADDRESS);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.CONTACT_ADDRESS));
			}
			if (Common.isEmpty(employeeInfo.getIsCollege())) {
				errorMsg.add(EmployeeConstants.IS_COLLEGE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.IS_COLLEGE));
			} else if (CommonConstants.IS_TRUE.equals(employeeInfo.getIsCollege())) {
				// 3.员工类型为外包和派遣，并且是否大专及以上为是，再增加必填项：最高学历、学校、专业、入学时间、毕业时间
				if (Common.isEmpty(employeeInfo.getHignEducation())) {
					errorMsg.add(EmployeeConstants.HIGN_EDUCATION);
					errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.HIGN_EDUCATION));
				}
				if (Common.isEmpty(employeeInfo.getSchool())) {
					errorMsg.add(EmployeeConstants.SCHOOL);
					errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.SCHOOL));
				}
				if (Common.isEmpty(employeeInfo.getMajor())) {
					errorMsg.add(EmployeeConstants.MAJOR);
					errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.MAJOR));
				}
				if (Common.isEmpty(employeeInfo.getAdmissionDate())) {
					errorMsg.add(EmployeeConstants.ADMISSION_DATE);
					errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.ADMISSION_DATE));
				}
				if (Common.isEmpty(employeeInfo.getGradutionDate())) {
					errorMsg.add(EmployeeConstants.GRADUTION_DATE);
					errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.GRADUTION_DATE));
				}
			}
		}
		if (Common.isEmpty(employeeInfo.getPost())) {
			errorMsg.add("就职岗位必填！");
			errorMsgMap.put(lineNum, new ErrorMessage("就职岗位必填！"));
		}
		//MVP1.6.7-huyc-身份证期限截止日期调整-校验日期
		if (Common.isNotNull(employeeInfo.getValidityEnd()) && !"长期".equals(employeeInfo.getValidityEnd()) &&
				!DateUtil.checkStringToDate(employeeInfo.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT)) {
			errorMsg.add(EmployeeConstants.VALIDITY_END_FORMAT);
			errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.VALIDITY_END_FORMAT));
		}
	}

	@Override
	public R<List<ErrorMessage>> batchImportEmployee(InputStream inputStream, int isCanAdd) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeInsertVO> util1 = new ExcelUtil<>(EmployeeInsertVO.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcel.read(inputStream, EmployeeInsertVO.class, new ReadListener<EmployeeInsertVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmployeeInsertVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeInsertVO data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						Set<String> errors = new HashSet<>();
						errors.add(errorMessage.getMessage());
						errorMessageList.add(new ErrorMessage(errorMessage.getLineNum() + 0L, errors));
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					if (!cachedDataList.isEmpty()) {
						batchImportCore(cachedDataList, isCanAdd, errorMessageList);
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (errorMessageList.isEmpty()) {
			return R.ok();
		} else {
			return R.failed(errorMessageList);
		}
	}


	private R<List<ErrorMessage>> batchImportCore(List<EmployeeInsertVO> excelVOList, int isCanAdd, List<ErrorMessage> errorMessageList) {
		if (excelVOList == null || excelVOList.isEmpty()) {
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		Set<String> errorMsg;
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			errorMsg = new HashSet<>();
			errorMsg.add(CommonConstants.PLEASE_LOG_IN);
			errorMessageList.add(new ErrorMessage(2L, errorMsg));
			return R.failed(errorMessageList);
		}
		Map<Long, ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorMessageList)) {
			errorMessageList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(), errorMessage));
		}

		// 获取身份证、手机号列表，批量查询档案
		List<String> idCardList = new ArrayList<>();
		List<String> phoneList = new ArrayList<>();
		Map<String, Integer> idCardMap = new HashMap<>();
		String idCard;
		// 个性化校验逻辑
		List<String> deptNoList = new ArrayList<>();
		TSettleDomain settleDomain;
		for (int i = 0; i < excelVOList.size(); i++) {
			errorMsg = new HashSet<>();
			// 判空
			this.checkEmployeeVOR((i + 2L), excelVOList.get(i), errorMsgMap, errorMsg);

			idCard = excelVOList.get(i).getEmpIdcard();
			if (Common.isEmpty(idCard)) {
				errorMsg.add("第" + (i + 2) + "行身份证号为空！");
				errorMsgMap.put((i + 2L), new ErrorMessage("第" + (i + 2) + "行身份证号为空！"));
			} else {
				if (idCardMap.get(idCard) != null) {
					errorMsg.add("第" + (excelVOList.get(i).getRowIndex()) + "行身份证号与第" + idCardMap.get(idCard) + "行重复！");
					errorMsgMap.put((excelVOList.get(i).getRowIndex().longValue()), new ErrorMessage("第" + (i + 2) + "行身份证号与第" + idCardMap.get(idCard) + "行重复！"));
				} else {
					idCardMap.put(idCard, i + 2);
					idCardList.add(idCard);
				}
			}
			if (Common.isNotNull(excelVOList.get(i).getEmpPhone())) {
				phoneList.add(excelVOList.get(i).getEmpPhone());
			}
			if (Common.isNotNull(excelVOList.get(i).getDeptNo())) {
				deptNoList.add(excelVOList.get(i).getDeptNo());
			}
			// 数据合法情况
			if (!CollUtil.isEmpty(errorMsg)) {
				// 数据不合法
				errorMessageList.add(new ErrorMessage((excelVOList.get(i).getRowIndex().longValue()), errorMsg));
			}
		}

		Map<String, Integer> deptMap = new HashMap<>();
		if (!deptNoList.isEmpty()) {
			List<TSettleDomain> deptList = tSettleDomainService.list(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.in(TSettleDomain::getDepartNo, deptNoList)
			);
			if (deptList == null || deptList.isEmpty()) {
				errorMsg = new HashSet<>();
				errorMsg.add(EmployeeConstants.DEPT_NO_EXIST);
				errorMessageList.add(new ErrorMessage(-1L, errorMsg));
				return R.failed(errorMessageList);
			} else {
				for (TSettleDomain dept : deptList) {
					deptMap.put(dept.getDepartNo(), CommonConstants.ONE_INT);
				}
			}
		}

		// 查找档案库
		Map<String, TEmployeeInfo> existEmpMap = new HashMap<>();
		Map<String, TEmployeeInfo> existPhoneMap = new HashMap<>();
		if (!idCardList.isEmpty()) {
			List<TEmployeeInfo> cards = baseMapper.getListByIdCard(idCardList);
			for (TEmployeeInfo employeeInfo : cards) {
				existEmpMap.put(employeeInfo.getEmpIdcard(), employeeInfo);
			}
		}
		if (!phoneList.isEmpty()) {
			List<TEmployeeInfo> phones = baseMapper.getListByPhone(phoneList);
			for (TEmployeeInfo employeeInfo : phones) {
				existPhoneMap.put(employeeInfo.getEmpPhone(), employeeInfo);
			}
		}

		EmployeeInsertVO excel;
		// 已存在的档案信息
		TEmployeeInfo existEmp;
		// 需要保存的档案信息
		TEmployeeInfo saveEmp;
		// 存储可保存的档案信息
		List<TEmployeeInfo> saveList = new ArrayList<>();

		// 调用字典服务，渲染字典值
		R<Map<String, Map<String, Map<String, String>>>> dictR = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
				, "/dict/inner/getDictToLable", null, Map.class, SecurityConstants.FROM_IN);
		Map<String, Map<String, Map<String, String>>> dictDataMap;
		Map<String, Map<String, String>> dictMap;
		// 婚姻状况
		Map<String, String> empMarriMap;
		// 民族
		Map<String, String> empNationalMap;
		// 政治面貌
		Map<String, String> empPoliticalMap;
		// 户口性质
		Map<String, String> regisTypeMap;
		// 最高学历
		Map<String, String> educationMap;
		// 员工类型
		Map<String, String> empNatrueMap;
		if (dictR == null || dictR.getData() == null) {
			return R.failed("获取字典失败！");
		} else {
			dictDataMap = dictR.getData();
			dictMap = dictDataMap.get("data");
			if (dictMap == null) {
				return R.failed("获取字典失败！！");
			}
			empMarriMap = dictMap.get("emp_married");
			empNationalMap = dictMap.get("emp_national");
			empPoliticalMap = dictMap.get("emp_political");
			regisTypeMap = dictMap.get("emp_registype");
			educationMap = dictMap.get("education");
			empNatrueMap = dictMap.get("emp_natrue");
		}

		// 调用区域服务，渲染区域值
		/*R<Map<String, Map<String, String>>> areaR = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
				, "/area/inner/getAreaToName", null, Map.class, SecurityConstants.FROM_IN)*/

		TEmployeeInfo checkPhone;
		List<TEmployeeInfo> phoneEmpList;
		String areaStr;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get((i + 2L)))) {
				continue;
			}
			saveEmp = new TEmployeeInfo();
			errorMsg = new HashSet<>();
			excel = excelVOList.get(i);

			if (deptMap.get(excel.getDeptNo()) == null) {
				errorMsg.add(EmployeeConstants.DEPT_NO_ERROR);
			}
			existEmp = existEmpMap.get(excel.getEmpIdcard());
			// 档案存在
			if (existEmp != null) {
				// 档案在职
				if (existEmp.getFileStatus() == CommonConstants.ZERO_INT) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_IDCARD_EXISTING, excel.getEmpIdcard()));
				} else if (isCanAdd == 0) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_ERROR_STATUS_EXISTS, excel.getEmpIdcard()));
				} else {
					saveEmp = existEmpMap.get(excel.getEmpIdcard());
					saveEmp.setProjectNum(CommonConstants.ONE_INT);
					if (Common.isNotNull(excel.getDeptNo())) {
						if (excel.getDeptNo().length() > 20) {
							errorMsg.add(EmployeeConstants.DEPT_NO_LENGTH);
						} else {
							saveEmp.setDeptNo(excel.getDeptNo());
						}
					}
					if (Common.isNotNull(excel.getPost())) {
						if (excel.getPost().length() > 20) {
							errorMsg.add(EmployeeConstants.POST_LENGTH);
						} else {
							saveEmp.setPost(excel.getPost());
						}
					}
					if (!Common.isNotNull(excel.getFileTown())) {
						saveEmp.setFileTown(null);
					}
					saveList.add(saveEmp);
				}
			} else {
				settleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
						.eq(TSettleDomain::getDepartNo, excel.getDeptNo())
						.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
						.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isEmpty(settleDomain)) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.PROJECT_SEARCH_NOT_EXIST, excel.getEmpIdcard()));
				}
				// 档案不存在
				// 校验身份证实名
				TCheckIdCard checkIdCard = new TCheckIdCard();
				checkIdCard.setName(excel.getEmpName());
				checkIdCard.setIdCard(excel.getEmpIdcard());
				R<TCheckIdCard> checkListR = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
						, "/tcheckidcard/inner/checkIdCardSingle", checkIdCard, TCheckIdCard.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					TCheckIdCard check = checkListR.getData();
					if (check == null || Common.isEmpty(check.getIsTrue())) {
						errorMsg.add("校验服务器未返回，请联系管理员！！");
					} else if (check.getIsTrue() == CommonConstants.ZERO_INT) {
						errorMsg.add(check.getReason());
					}
				}
				saveEmp.setEmpName(excel.getEmpName());
				saveEmp.setEmpIdcard(excel.getEmpIdcard());
				saveEmp.setEmpPhone(excel.getEmpPhone());

				// 校验手机号
				checkPhone = new TEmployeeInfo();
				checkPhone.setDeleteFlag(CommonConstants.STATUS_NORMAL);
				checkPhone.setEmpPhone(excel.getEmpPhone());
				phoneEmpList = baseMapper.getList(checkPhone);
				if (phoneEmpList != null && !phoneEmpList.isEmpty()) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR, excel.getEmpIdcard()));
				}

				existEmp = existPhoneMap.get(excel.getEmpPhone());
				// 手机号已存在
				if (existEmp != null) {
					// 非自己使用的
					if (!existEmp.getEmpIdcard().equals(excel.getEmpIdcard())) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR, existEmp.getEmpIdcard()));
					}
				} else {
					// 调用校验服务-校验手机号
					TCheckMobile checkMobile = new TCheckMobile();
					checkMobile.setMobile(excel.getEmpPhone());
					R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
							, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
					if (a != null && a.getData() != null) {
						checkMobile = a.getData();
						if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
							if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
								errorMsg.add(checkMobile.getMessage());
							}
						} else {
							errorMsg.add("校验服务错误，请联系管理员！");
						}
					}
				}

				// 校验字典数据是否正确-婚姻
				if (Common.isNotNull(excel.getEmpMarriStatus())) {
					if (empMarriMap.get(excel.getEmpMarriStatus()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_MARRIED_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setEmpMarriStatus(empMarriMap.get(excel.getEmpMarriStatus()));
					}
				}
				// 校验字典数据是否正确-民族
				if (Common.isNotNull(excel.getEmpNational())) {
					if (empNationalMap.get(excel.getEmpNational()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NATIONAL_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setEmpNational(empNationalMap.get(excel.getEmpNational()));
					}
				}
				// 校验字典数据是否正确-政治面貌
				if (Common.isNotNull(excel.getPoliticalStatus())) {
					if (empPoliticalMap.get(excel.getPoliticalStatus()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_POLITICAL_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setPoliticalStatus(empPoliticalMap.get(excel.getPoliticalStatus()));
					}
				}
				// 校验字典数据是否正确-户口性质
				if (Common.isNotNull(excel.getEmpRegisType())) {
					if (regisTypeMap.get(excel.getEmpRegisType()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_REGISTYPE_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setEmpRegisType(regisTypeMap.get(excel.getEmpRegisType()));
					}
				}
				// 校验字典数据是否正确-最高学历
				if (Common.isNotNull(excel.getHignEducation())) {
					if (educationMap.get(excel.getHignEducation()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EDUCATION_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setHignEducation(educationMap.get(excel.getHignEducation()));
					}
				}
				// 校验字典数据是否正确-员工类型
				if (Common.isNotNull(excel.getEmpNatrue())) {
					if (empNatrueMap.get(excel.getEmpNatrue()) == null) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NATRUE_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setEmpNatrue(empNatrueMap.get(excel.getEmpNatrue()));
					}
				}
				// 户籍所在地
				if (Common.isNotNull(excel.getIdProvince())) {
					areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdProvince().trim());
					if (Common.isEmpty(areaStr)) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setIdProvince(Integer.parseInt(areaStr));
					}
					if (Common.isNotNull(excel.getIdCity())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdCity().trim() + CommonConstants.DOWN_LINE_STRING + excel.getIdProvince().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setIdCity(Integer.parseInt(areaStr));
						}
					}
					if (Common.isNotNull(excel.getIdTown())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdTown().trim() + CommonConstants.DOWN_LINE_STRING + excel.getIdCity().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setIdTown(Integer.parseInt(areaStr));
						}
					}
				}

				// 档案所在地
				if (Common.isNotNull(excel.getFileProvince())) {
					saveEmp.setFileProvince(Integer.parseInt(excel.getFileProvince()));
				}
				if (Common.isNotNull(excel.getFileCity())) {
					saveEmp.setFileCity(Integer.parseInt(excel.getFileCity()));
				}
				if (Common.isNotNull(excel.getFileTown())) {
					saveEmp.setFileTown(Integer.parseInt(excel.getFileTown()));
				} else {
					saveEmp.setFileTown(null);
				}
				if (Common.isNotNull(excel.getIsCollege())) {
					if (CommonConstants.IS_TRUE.equals(excel.getIsCollege())) {
						saveEmp.setIsCollege(CommonConstants.ONE_INT);
					} else if (CommonConstants.IS_FALSE.equals(excel.getIsCollege())) {
						saveEmp.setIsCollege(CommonConstants.ZERO_INT);
					} else {
						errorMsg.add(EmployeeConstants.IS_OR_NOT);
					}
				}
				saveEmp.setValidityStart(excel.getValidityStart());
				if ("长期".equals(excel.getValidityEnd())) {
					saveEmp.setValidityEnd(DateUtil.stringToDate("2999-12-31", DateUtil.ISO_EXPANDED_DATE_FORMAT));
				} else {
					saveEmp.setValidityEnd(DateUtil.stringToDate(excel.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT));
				}
				// 身份证起止有效期 都有值 且 截止日期正常
				if (Common.isNotNull(excel.getValidityStart())
						&& !"长期".equals(excel.getValidityEnd())
						&& DateUtil.checkStringToDate(excel.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT)
						&& !DateUtil.stringToDate(excel.getValidityEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT).after(excel.getValidityStart())){
					errorMsg.add(EmployeeConstants.EMP_VALIDITY_END_START_DATE);
				}
				// 邮箱
				if (Common.isNotNull(excel.getEmpEmail())) {
					if (excel.getEmpEmail().contains("@")) {
						if (excel.getEmpEmail().length() < 50) {
							saveEmp.setEmpEmail(excel.getEmpEmail());
						} else {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EMAIL_LENGTH, excel.getEmpIdcard()));
						}
					} else {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EMAIL_CHECK, excel.getEmpIdcard()));
					}
				}

				if (Common.isNotNull(excel.getSchool())) {
					if (excel.getSchool().length() > 50) {
						errorMsg.add(EmployeeConstants.SCHOOL_LENGTH);
					} else {
						saveEmp.setSchool(excel.getSchool());
					}
				}
				if (Common.isNotNull(excel.getMajor())) {
					if (excel.getMajor().length() > 50) {
						errorMsg.add(EmployeeConstants.MAJOR_LENGTH);
					} else {
						saveEmp.setMajor(excel.getMajor());
					}
				}
				// 通信地址所在地
				if (Common.isNotNull(excel.getContactProvince())) {
					saveEmp.setContactProvince(excel.getContactProvince());
				}
				if (Common.isNotNull(excel.getContactCity())) {
					saveEmp.setContactCity(excel.getContactCity());
				}
				if (Common.isNotNull(excel.getContactTown())) {
					saveEmp.setContactTown(excel.getContactTown());
				}
				if (Common.isNotNull(excel.getContactAddress())) {
					if (excel.getContactAddress().length() > 200) {
						errorMsg.add(EmployeeConstants.CONTACT_ADDRESS_LENGTH);
					} else {
						saveEmp.setContactAddress(excel.getContactAddress());
					}
				}
				if (Common.isNotNull(excel.getRemark())) {
					if (excel.getRemark().length() > 200) {
						errorMsg.add(EmployeeConstants.REMARL_LENGTH);
					} else {
						saveEmp.setRemark(excel.getRemark());
					}
				}
				if (Common.isNotNull(excel.getAdmissionDate())) {
					saveEmp.setAdmissionDate(excel.getAdmissionDate());
				}
				if (Common.isNotNull(excel.getGradutionDate())) {
					saveEmp.setGradutionDate(excel.getGradutionDate());
				}
				if (Common.isNotNull(excel.getPost())) {
					if (excel.getPost().length() > 20) {
						errorMsg.add(EmployeeConstants.POST_LENGTH);
					} else {
						saveEmp.setPost(excel.getPost());
					}
				}
				if (Common.isNotNull(excel.getDeptNo())) {
					if (excel.getDeptNo().length() > 20) {
						errorMsg.add(EmployeeConstants.DEPT_NO_LENGTH);
					} else {
						saveEmp.setDeptNo(excel.getDeptNo());
					}
				}
				this.setBaseData(saveEmp, CommonConstants.dingleDigitStrArray[5], user);
				saveList.add(saveEmp);
			}
			// 数据合法情况
			if (!CollUtil.isEmpty(errorMsg)) {
				// 数据不合法
				errorMessageList.add(new ErrorMessage((i + 2L), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		} else {
			// 仅新增、复档、更新学历
			this.saveOrUpdateData(saveList);
		}
		return R.ok();
	}

	/**
	 * @Description: // 字典：1=社保、公积金派单,2=人员发薪,3=商险派单,4=档案新建,5=批量导入
	 * @Description: 加载初始数据
	 * @Author: hgw
	 * @Date: 2022/6/22 20:21
	 * @return: void
	 **/
	public void setBaseData(TEmployeeInfo employeeInfo, String fileSource, YifuUser user) {
		// 新增档案
		employeeInfo.setCreateBy(user.getId());
		employeeInfo.setCreateName(user.getNickname());
		employeeInfo.setCreateTime(LocalDateTime.now());

		employeeInfo.setFileSource(fileSource);
		employeeInfo.setStatus(CommonConstants.ZERO_INT);
		employeeInfo.setFileStatus(CommonConstants.ZERO_INT);
		employeeInfo.setProjectNum(CommonConstants.ONE_INT);
		employeeInfo.setDeleteFlag(CommonConstants.STATUS_NORMAL);

		employeeInfo.setContractStatus(CommonConstants.ZERO_INT);
		employeeInfo.setInsuranceStatus(CommonConstants.ZERO_INT);
		employeeInfo.setSocialStatus(CommonConstants.ZERO_INT);
		employeeInfo.setFundStatus(CommonConstants.ZERO_INT);
		employeeInfo.setSalaryStatus(CommonConstants.ZERO_INT);
		// 生成性别年龄等：
		this.setBaseSexInfo(employeeInfo);
	}

	/**
	 * @param saveList
	 * @Description: 真正的保存
	 * @Author: hgw
	 * @Date: 2022/6/22 17:44
	 * @return: void
	 **/
	@Transactional
	public void saveOrUpdateData(List<TEmployeeInfo> saveList) {
		TEmpEducation education;
		for (TEmployeeInfo employeeInfo : saveList) {
			// 新增档案
			if (Common.isEmpty(employeeInfo.getId())) {
				// 生成主码：
				if (Common.isEmpty(employeeInfo.getEmpCode())) {
					employeeInfo.setEmpCode(this.getCode());
				}
				this.save(employeeInfo);
				// 新增项目档案
				tEmployeeProjectService.saveEmployeeProjectInfo(employeeInfo);

				// 更新学历-房
				education = new TEmpEducation();
				this.doUpdateEducationCore(education, employeeInfo);
			} else {
				// 复档复项
				employeeInfo.setFileStatus(CommonConstants.ZERO_INT);
				this.updateById(employeeInfo);
				List<TEmployeeProject> projectList = tEmployeeProjectService.getListByEmpIdAndDeptNo(employeeInfo.getId(), employeeInfo.getDeptNo());
				if (projectList != null && !projectList.isEmpty()) {
					for (TEmployeeProject project : projectList) {
						project.setProjectStatus(CommonConstants.ZERO_INT);
					}
					tEmployeeProjectService.updateBatchById(projectList);
				} else {
					// 新增项目档案
					tEmployeeProjectService.saveEmployeeProjectInfo(employeeInfo);
				}
			}
		}
	}

	/**
	 * @param
	 * @Description: 获取员工主码
	 * @Author: hgw
	 * @Date: 2022/6/22 17:52
	 * @return: java.lang.String
	 **/
	@Lock4j(expire = 60000, acquireTimeout = 1000)
	@Override
	public String getCode() {
		String nowDay = DateUtil.getThisDay();
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_EMP_CODE);
		Object nowNumObj = cache.get(nowDay);
		int nowNums = 1;
		if (Common.isNotNull(nowNumObj)) {
			SimpleValueWrapper value = (SimpleValueWrapper) nowNumObj;
			nowNums = (Integer) value.get() + 1;
		} else {
			String empCode = null;
			try {
				empCode = baseMapper.getMaxEmpCode();
				nowNums = Integer.parseInt(empCode) + 1;
			} catch (NumberFormatException e) {
				log.error("获取人员档案当日最大编码时出错：" + empCode);
				nowNums = 1;
			}
		}
		cache.put(nowDay, nowNums);
		return "ZM" + nowDay + this.getFiveNum(String.valueOf(nowNums));
	}

	@Override
	public void updateEducationOfEmp(EmpEducationUpdateVO education) {
		baseMapper.updateEducationOfEmp(education);
	}

	@Override
	public R<List<ErrorMessage>> batchUpdateEmployee(InputStream inputStream, String[] exportFields) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeInsertVO> util1 = new ExcelUtil<>(EmployeeInsertVO.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcel.read(inputStream, EmployeeInsertVO.class, new ReadListener<EmployeeInsertVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmployeeInsertVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeInsertVO data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						Set<String> errors = new HashSet<>();
						errors.add(errorMessage.getMessage());
						errorMessageList.add(new ErrorMessage(errorMessage.getLineNum() + 0L, errors));
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					if (!cachedDataList.isEmpty()) {
						batchUpdateCore(cachedDataList, errorMessageList, exportFields);
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (errorMessageList.isEmpty()) {
			return R.ok();
		} else {
			return R.failed(errorMessageList);
		}
	}

	private R<List<ErrorMessage>> batchUpdateCore(List<EmployeeInsertVO> excelVOList,
												  List<ErrorMessage> errorMessageList,
												  String[] exportFields) {
		YifuUser user = SecurityUtils.getUser();
		Set<String> errorMsg;
		if (user == null || Common.isEmpty(user.getId())) {
			errorMsg = new HashSet<>();
			errorMsg.add(CommonConstants.PLEASE_LOG_IN);
			errorMessageList.add(new ErrorMessage(2L, errorMsg));
			return R.failed(errorMessageList);
		}
		if (excelVOList == null || excelVOList.isEmpty()) {
			errorMsg = new HashSet<>();
			errorMsg.add(CommonConstants.DATA_CAN_NOT_EMPTY);
			errorMessageList.add(new ErrorMessage(2L, errorMsg));
			return R.failed(errorMessageList);
		}
		//初试化表头用于校验省市县
		HashMap<String, String> headMap = new HashMap<>();
		if (Common.isNotNull(exportFields)) {
			for (int i = 0; i < exportFields.length; i++) {
				headMap.put(exportFields[i], exportFields[i]);
			}
		}

		// 通用校验获取失败的数据
		Map<Long, ErrorMessage> errorMsgMap = new HashMap<>();

		// 获取身份证、手机号列表，批量查询档案
		List<String> idCardList = new ArrayList<>();
		List<String> phoneList = new ArrayList<>();
		long lineNum;
		for (int i = 0; i < excelVOList.size(); i++) {
			lineNum = i + 2L;
			// 判空
			if (Common.isEmpty(excelVOList.get(i).getEmpIdcard())) {
				errorMsgMap.put(lineNum, new ErrorMessage("员工身份证必填"));
			} else {
				idCardList.add(excelVOList.get(i).getEmpIdcard());
			}
			if (Common.isNotNull(excelVOList.get(i).getEmpPhone())) {
				phoneList.add(excelVOList.get(i).getEmpPhone());
			}
			if (Common.isEmpty(excelVOList.get(i).getEmpName())) {
				errorMsgMap.put(lineNum, new ErrorMessage("员工姓名必填"));
			}
		}
		if (Common.isNotNull(errorMessageList)) {
			errorMessageList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(), errorMessage));
		}
		// 查找档案库
		Map<String, TEmployeeInfo> existEmpMap = new HashMap<>();
		Map<String, TEmployeeInfo> existPhoneMap = new HashMap<>();
		if (!idCardList.isEmpty()) {
			List<TEmployeeInfo> cards = baseMapper.getListByIdCard(idCardList);
			for (TEmployeeInfo employeeInfo : cards) {
				existEmpMap.put(employeeInfo.getEmpIdcard(), employeeInfo);
			}
		}
		if (!phoneList.isEmpty()) {
			List<TEmployeeInfo> phones = baseMapper.getListByPhone(phoneList);
			for (TEmployeeInfo employeeInfo : phones) {
				existPhoneMap.put(employeeInfo.getEmpPhone(), employeeInfo);
			}
		}

		// 个性化校验逻辑
		EmployeeInsertVO excel;
		// 需要保存的档案信息
		TEmployeeInfo saveEmp;
		// 原先的档案信息
		TEmployeeInfo oldEmp;
		// 已存在的档案
		TEmployeeInfo existEmp;
		// 存储可保存的档案信息
		List<TEmployeeInfo> saveList = new ArrayList<>();
		// 新老档案vo
		EmployeeNewOldVO newOld;
		// 新老档案List
		List<EmployeeNewOldVO> updateList = new ArrayList<>();

		// 调用字典服务，渲染字典值
		R<Map<String, Map<String, Map<String, String>>>> dictR = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
				, "/dict/inner/getDictToLable", null, Map.class, SecurityConstants.FROM_IN);
		Map<String, Map<String, Map<String, String>>> dictDataMap;
		Map<String, Map<String, String>> dictMap;
		// 婚姻状况
		Map<String, String> empMarriMap;
		// 民族
		Map<String, String> empNationalMap;
		// 政治面貌
		Map<String, String> empPoliticalMap;
		// 户口性质
		Map<String, String> regisTypeMap;
		// 最高学历
		Map<String, String> educationMap;
		// 员工类型
		Map<String, String> empNatrueMap;
		if (dictR == null || dictR.getData() == null) {
			return R.failed("获取字典失败！");
		} else {
			dictDataMap = dictR.getData();
			dictMap = dictDataMap.get("data");
			empMarriMap = dictMap.get("emp_married");
			empNationalMap = dictMap.get("emp_national");
			empPoliticalMap = dictMap.get("emp_political");
			regisTypeMap = dictMap.get("emp_registype");
			educationMap = dictMap.get("education");
			empNatrueMap = dictMap.get("emp_natrue");
		}

		String areaStr;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get((excel.getRowIndex())))) {
				continue;
			}
			errorMsg = new HashSet<>();
			saveEmp = existEmpMap.get(excel.getEmpIdcard());
			// 档案存在
			if (saveEmp != null) {
				// 档案在职
				if (saveEmp.getFileStatus() == CommonConstants.ZERO_INT) {
					// 可以更新
					oldEmp = new TEmployeeInfo();
					BeanUtil.copyProperties(saveEmp, oldEmp);

					if (Common.isNotNull(excel.getEmpPhone())) {
						saveEmp.setEmpPhone(excel.getEmpPhone());
					}

					// 校验手机号
					if (Common.isNotNull(excel.getEmpPhone())) {
						existEmp = existPhoneMap.get(excel.getEmpPhone());
						// 手机号已存在
						if (existEmp != null) {
							// 非自己使用的
							if (!existEmp.getEmpIdcard().equals(excel.getEmpIdcard())) {
								errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR, existEmp.getEmpIdcard()));
							}
						} else {
							// 调用校验服务-校验手机号
							TCheckMobile checkMobile = new TCheckMobile();
							checkMobile.setMobile(excel.getEmpPhone());
							R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
									, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
							if (a != null && a.getData() != null) {
								checkMobile = a.getData();
								if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
									if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
										errorMsg.add(checkMobile.getMessage());
									}
								} else {
									errorMsg.add(EmployeeConstants.CHECK_ERROR);
								}
							} else {
								errorMsg.add(EmployeeConstants.CHECK_ERROR);
							}
						}
					}

					// 校验字典数据是否正确-婚姻
					if (Common.isNotNull(excel.getEmpMarriStatus())) {
						if (empMarriMap.get(excel.getEmpMarriStatus()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_MARRIED_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setEmpMarriStatus(empMarriMap.get(excel.getEmpMarriStatus()));
						}
					}
					// 校验字典数据是否正确-民族
					if (Common.isNotNull(excel.getEmpNational())) {
						if (empNationalMap.get(excel.getEmpNational()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NATIONAL_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setEmpNational(empNationalMap.get(excel.getEmpNational()));
						}
					}
					// 校验字典数据是否正确-政治面貌
					if (Common.isNotNull(excel.getPoliticalStatus())) {
						if (empPoliticalMap.get(excel.getPoliticalStatus()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_POLITICAL_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setPoliticalStatus(empPoliticalMap.get(excel.getPoliticalStatus()));
						}
					}
					// 校验字典数据是否正确-户口性质
					if (Common.isNotNull(excel.getEmpRegisType())) {
						if (regisTypeMap.get(excel.getEmpRegisType()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_REGISTYPE_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setEmpRegisType(regisTypeMap.get(excel.getEmpRegisType()));
						}
					}
					// 校验字典数据是否正确-最高学历
					if (Common.isNotNull(excel.getHignEducation())) {
						if (educationMap.get(excel.getHignEducation()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EDUCATION_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setHignEducation(educationMap.get(excel.getHignEducation()));
						}
					}
					// 校验字典数据是否正确-员工类型
					if (Common.isNotNull(excel.getEmpNatrue())) {
						if (empNatrueMap.get(excel.getEmpNatrue()) == null) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NATRUE_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setEmpNatrue(empNatrueMap.get(excel.getEmpNatrue()));
						}
					}
					// 户籍所在地
					if (Common.isNotNull(excel.getIdProvince())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdProvince().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setIdProvince(Integer.parseInt(areaStr));
						}
						if (Common.isNotNull(excel.getIdCity())) {
							areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdCity().trim() + CommonConstants.DOWN_LINE_STRING + excel.getIdProvince().trim());
							if (Common.isEmpty(areaStr)) {
								errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
							} else {
								saveEmp.setIdCity(Integer.parseInt(areaStr));
							}
							if (Common.isNotNull(excel.getIdTown())) {
								areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getIdTown().trim() + CommonConstants.DOWN_LINE_STRING + excel.getIdCity().trim());
								if (Common.isEmpty(areaStr)) {
									errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_AREA_ERROR, excel.getEmpIdcard()));
								} else {
									saveEmp.setIdTown(Integer.parseInt(areaStr));
								}
							}
						}
					}

					if (Common.isNotNull(excel.getIsCollege())) {
						if (CommonConstants.IS_TRUE.equals(excel.getIsCollege())) {
							saveEmp.setIsCollege(CommonConstants.ONE_INT);
						} else if (CommonConstants.IS_FALSE.equals(excel.getIsCollege())) {
							saveEmp.setIsCollege(CommonConstants.ZERO_INT);
						} else {
							errorMsg.add(EmployeeConstants.IS_OR_NOT);
						}
					}

					if (Common.isNotNull(excel.getValidityStart())) {
						saveEmp.setValidityStart(excel.getValidityStart());
					}
					if (Common.isNotNull(excel.getValidityEnd())) {
						//MVP1.6.7-huyc-身份证期限截止日期调整-校验日期
						if (!"长期".equals(excel.getValidityEnd()) && !DateUtil.checkStringToDate(
								excel.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_IDCARD_END, excel.getEmpIdcard()));
						} else {
							if ("长期".equals(excel.getValidityEnd())) {
								saveEmp.setValidityEnd(DateUtil.stringToDate("2999-12-31", DateUtil.ISO_EXPANDED_DATE_FORMAT));
							} else {
								saveEmp.setValidityEnd(DateUtil.stringToDate(excel.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT));
							}
						}
						// 身份证起止有效期 都有值 且 截止日期正常
						if (Common.isNotNull(excel.getValidityStart())
								&& !"长期".equals(excel.getValidityEnd())
								&& DateUtil.checkStringToDate(excel.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT)
								&& !DateUtil.stringToDate(excel.getValidityEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT).after(excel.getValidityStart())){
							errorMsg.add(EmployeeConstants.EMP_VALIDITY_END_START_DATE);
						}
					}
					// 档案所在地
					if (Common.isNotNull(excel.getFileProvince())) {
						saveEmp.setFileProvince(Integer.parseInt(excel.getFileProvince()));
					}
					if (Common.isNotNull(excel.getFileCity())) {
						saveEmp.setFileCity(Integer.parseInt(excel.getFileCity()));
					}
					if (Common.isNotNull(excel.getFileTown())) {
						saveEmp.setFileTown(Integer.parseInt(excel.getFileTown()));
					} else {
						saveEmp.setFileTown(null);
					}
					// 邮箱
					if (Common.isNotNull(excel.getEmpEmail())) {
						if (excel.getEmpEmail().contains("@")) {
							if (excel.getEmpEmail().length() < 50) {
								saveEmp.setEmpEmail(excel.getEmpEmail());
							} else {
								errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EMAIL_LENGTH, excel.getEmpIdcard()));
							}
						} else {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_EMAIL_CHECK, excel.getEmpIdcard()));
						}
					}

					if (Common.isNotNull(excel.getSchool())) {
						if (excel.getSchool().length() > 50) {
							errorMsg.add(EmployeeConstants.SCHOOL_LENGTH);
						} else {
							saveEmp.setSchool(excel.getSchool());
						}
					}
					if (Common.isNotNull(excel.getMajor())) {
						if (excel.getMajor().length() > 50) {
							errorMsg.add(EmployeeConstants.MAJOR_LENGTH);
						} else {
							saveEmp.setMajor(excel.getMajor());
						}
					}
					// 通信地址所在地
					if (Common.isNotNull(excel.getContactProvince())) {
						saveEmp.setContactProvince(excel.getContactProvince());
					}
					if (Common.isNotNull(excel.getContactCity())) {
						saveEmp.setContactCity(excel.getContactCity());
					}
					if (Common.isNotNull(excel.getContactTown())) {
						saveEmp.setContactTown(excel.getContactTown());
					}
					if (Common.isNotNull(excel.getContactAddress())) {
						if (excel.getContactAddress().length() > 200) {
							errorMsg.add(EmployeeConstants.CONTACT_ADDRESS_LENGTH);
						} else {
							saveEmp.setContactAddress(excel.getContactAddress());
						}
					}
					// 档案地和通信地址 校验
					if (Common.isNotNull(headMap.get("档案所在省"))
							|| Common.isNotNull(headMap.get("档案所在市"))) {
						if (Common.isEmpty(excel.getFileProvince())) {
							errorMsg.add(EmployeeConstants.FILE_PROVINCE);
						}
						if (Common.isEmpty(excel.getFileCity())) {
							errorMsg.add(EmployeeConstants.FILE_PROVINCE);
						}
					}
					if (Common.isNotNull(headMap.get("通信地址-省"))
							|| Common.isNotNull(headMap.get("通信地址-市"))
							|| Common.isNotNull(headMap.get("通信地址-区/县"))) {
						if (Common.isEmpty(excel.getContactTown())) {
							errorMsg.add(EmployeeConstants.CONTACT_PROVINCE);
						}
					}
					if (Common.isNotNull(headMap.get("通信地址-详细地址"))) {
						if (Common.isEmpty(excel.getContactAddress())) {
							errorMsg.add(EmployeeConstants.CONTACT_ADDRESS);
						}
					}

					if (Common.isNotNull(excel.getRemark())) {
						if (excel.getRemark().length() > 200) {
							errorMsg.add(EmployeeConstants.REMARL_LENGTH);
						} else {
							saveEmp.setRemark(excel.getRemark());
						}
					}
					if (Common.isNotNull(excel.getAdmissionDate())) {
						saveEmp.setAdmissionDate(excel.getAdmissionDate());
					}
					if (Common.isNotNull(excel.getGradutionDate())) {
						saveEmp.setGradutionDate(excel.getGradutionDate());
					}
					if (Common.isNotNull(excel.getPost())) {
						if (excel.getPost().length() > 20) {
							errorMsg.add(EmployeeConstants.POST_LENGTH);
						} else {
							saveEmp.setPost(excel.getPost());
						}
					}
					if (Common.isNotNull(excel.getDeptNo())) {
						if (excel.getDeptNo().length() > 20) {
							errorMsg.add(EmployeeConstants.DEPT_NO_LENGTH);
						} else {
							saveEmp.setDeptNo(excel.getDeptNo());
						}
					}
					// 判断空值
					//this.judgeNull(errorMsg, saveEmp);

					// 更新时，不需要更新其余信息
					newOld = new EmployeeNewOldVO();
					newOld.setNewEmployee(saveEmp);
					newOld.setOldEmployee(oldEmp);
					updateList.add(newOld);
					saveEmp.setUpdateBy(user.getId());
					saveEmp.setUpdateTime(LocalDateTime.now());
					saveList.add(saveEmp);
				} else if (saveEmp.getFileStatus() == CommonConstants.ONE_INT) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NOT_EXISTS, excel.getEmpIdcard()));
				}
			} else {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_NOT_EXISTS, excel.getEmpIdcard()));
			}

			// 数据合法情况
			if (!CollUtil.isEmpty(errorMsg)) {
				// 数据不合法
				errorMessageList.add(new ErrorMessage(excel.getRowIndex().longValue(), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		} else {
			// 更新
			this.updateBatchById(saveList);

			// 更新学历-房
			this.saveOrUpdateEducation(saveList);

			// 记录变更日志
			for (EmployeeNewOldVO newOldInfo : updateList) {
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0]
						, newOldInfo.getOldEmployee().getId(), ""
						, newOldInfo.getOldEmployee(), newOldInfo.getNewEmployee());
			}
		}
		return R.ok();
	}

	/**
	 * @Description: 批量更新的判断
	 * @Author: hgw
	 * @Date: 2022/7/6 15:10
	 * @return: void
	 **/
	private void judgeNull(Set<String> errorMsg, TEmployeeInfo employeeInfo) {
		if (Common.isNotNull(employeeInfo.getEmpNatrue())
				&& (CommonConstants.ZERO_STRING.equals(employeeInfo.getEmpNatrue())
				|| CommonConstants.ONE_STRING.equals(employeeInfo.getEmpNatrue())
				|| CommonConstants.THREE_STRING.equals(employeeInfo.getEmpNatrue()))) {
			// 2.员工类型为外包和派遣，额外必填项有：身份证开始日期、身份证截止日期、民族、户籍所在（省市县）、户口性质、档案所在地（省市县）、是否大专及以上、通信地址
			if (Common.isEmpty(employeeInfo.getValidityStart())) {
				errorMsg.add(EmployeeConstants.VALIDITY_START);
			}
			if (Common.isEmpty(employeeInfo.getValidityEnd())) {
				errorMsg.add(EmployeeConstants.VALIDITY_END);
			}
			if (Common.isEmpty(employeeInfo.getEmpNational())) {
				errorMsg.add(EmployeeConstants.EMP_NATIONAL);
			}
			/*if (Common.isEmpty(employeeInfo.getIdProvince())) {
				errorMsg.add(EmployeeConstants.ID_PROVINCE);
			}*/
			if (Common.isEmpty(employeeInfo.getFileProvince())) {
				errorMsg.add(EmployeeConstants.FILE_PROVINCE);
			}
			if (Common.isEmpty(employeeInfo.getContactAddress())) {
				errorMsg.add(EmployeeConstants.CONTACT_ADDRESS);
			}
			if (Common.isEmpty(employeeInfo.getIsCollege())) {
				errorMsg.add(EmployeeConstants.IS_COLLEGE);
			} else if (CommonConstants.ONE_INT == employeeInfo.getIsCollege()) {
				// 3.员工类型为外包和派遣，并且是否大专及以上为是，再增加必填项：最高学历、学校、专业、入学时间、毕业时间
				if (Common.isEmpty(employeeInfo.getHignEducation())) {
					errorMsg.add(EmployeeConstants.HIGN_EDUCATION);
				}
				if (Common.isEmpty(employeeInfo.getSchool())) {
					errorMsg.add(EmployeeConstants.SCHOOL);
				}
				if (Common.isEmpty(employeeInfo.getMajor())) {
					errorMsg.add(EmployeeConstants.MAJOR);
				}
				if (Common.isEmpty(employeeInfo.getAdmissionDate())) {
					errorMsg.add(EmployeeConstants.ADMISSION_DATE);
				}
				if (Common.isEmpty(employeeInfo.getGradutionDate())) {
					errorMsg.add(EmployeeConstants.GRADUTION_DATE);
				}
			}
		}
		/*if (Common.isNotNull(employeeInfo.getIdCity()) && Common.isEmpty(employeeInfo.getIdProvince())) {
			errorMsg.add(EmployeeConstants.ID_ROVINCE_MUST);
		}*/
		if (Common.isNotNull(employeeInfo.getIdTown()) && Common.isEmpty(employeeInfo.getIdCity())) {
			errorMsg.add(EmployeeConstants.ID_CITY_MUST);
		}
		if (Common.isNotNull(employeeInfo.getFileCity()) && Common.isEmpty(employeeInfo.getFileProvince())) {
			errorMsg.add(EmployeeConstants.FILE_ROVINCE_MUST);
		}
		if (Common.isNotNull(employeeInfo.getFileTown()) && Common.isEmpty(employeeInfo.getFileCity())) {
			errorMsg.add(EmployeeConstants.FILE_CITY_MUST);
		}
	}

	// 更新学历-房
	private void saveOrUpdateEducation(List<TEmployeeInfo> saveList) {
		TEmpEducation education;
		for (TEmployeeInfo employeeInfo : saveList) {
			education = new TEmpEducation();
			this.doUpdateEducationCore(education, employeeInfo);
		}
	}

	// 更新学历-核心
	private void doUpdateEducationCore(TEmpEducation education, TEmployeeInfo employeeInfo) {
		// 派遣/外包+大专及以上=是   才根据学历（本科、大专这些）去更新 或者新建一条学历信息
		if (Common.isNotNull(employeeInfo.getEmpNatrue())
				&& (CommonConstants.ZERO_STRING.equals(employeeInfo.getEmpNatrue())
				|| CommonConstants.ONE_STRING.equals(employeeInfo.getEmpNatrue()))
				&& Common.isNotNull(employeeInfo.getIsCollege())
				&& employeeInfo.getIsCollege() == CommonConstants.ONE_INT) {
			education.setEmpId(employeeInfo.getId());
			education.setEmpName(employeeInfo.getEmpName());
			education.setEmpCode(employeeInfo.getEmpCode());
			education.setEmpIdcard(employeeInfo.getEmpIdcard());
			education.setEducationName(employeeInfo.getHignEducation());
			education.setHighIdentification(CommonConstants.ZERO_STRING);
			education.setSchool(employeeInfo.getSchool());
			education.setMajor(employeeInfo.getMajor());
			education.setEntryDate(employeeInfo.getAdmissionDate());
			education.setGradutionDate(employeeInfo.getGradutionDate());
			tEmpEducationService.insertEducationOfEmp(education);
		}
	}

	/**
	 * 获取导出的人员档案列表
	 */
	@Override
	public void exportEmployee(EmployeeInfoSearchVo searchVo, HttpServletResponse response) {
		if (searchVo != null && searchVo.getExportFields() != null && !searchVo.getExportFields().isEmpty()) {
			String fileName = "人员档案批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
			//获取要导出的列表
			List<EmployeeExportVO> list = new ArrayList<>();
			//获取要导出的列表
			searchVo.setFileStatus(CommonConstants.ZERO_INT);
			long count = noPageCountDiy(searchVo);
			ServletOutputStream out = null;
			try {
				out = response.getOutputStream();
				response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
				response.setCharacterEncoding("utf-8");
				response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
				// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
				//EasyExcel.write(out, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
				ExcelUtil<EmployeeExportVO> util = new ExcelUtil<>(EmployeeExportVO.class);
				// 获取所有字典type
				Map<String, String> nameAndDicTypeMap = util.getConverterDicType();
				// 获取所有字典对应的值
				Map<String, String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
				ExcelWriter excelWriter = EasyExcel.write(out, EmployeeExportVO.class)
						.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
						.includeColumnFieldNames(searchVo.getExportFields()).build();
				int index = 0;
				if (count > CommonConstants.ZERO_INT) {
					WriteSheet writeSheet;
					for (int i = 0; i <= count; ) {
						// 获取实际记录
						searchVo.setLimitStart(i);
						searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
						list = noPageDiy(searchVo);
						if (Common.isNotNull(list)) {
							writeSheet = EasyExcel.writerSheet("人员档案批量导出" + index).build();
							excelWriter.write(list, writeSheet);
							index++;
						}
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
						if (Common.isNotNull(list)) {
							list.clear();
						}
					}
				} else {
					WriteSheet writeSheet = EasyExcel.writerSheet("人员档案批量导出" + index).build();
					excelWriter.write(list, writeSheet);
				}
				if (Common.isNotNull(list)) {
					list.clear();
				}
				out.flush();
				excelWriter.finish();
			} catch (Exception e) {
				log.error("执行异常", e);
			} finally {
				try {
					if (null != out) {
						out.close();
					}
				} catch (IOException e) {
					log.error("执行异常", e);
				}
			}
		}
	}

	private List<EmployeeExportVO> noPageDiy(EmployeeInfoSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo);
	}

	private long noPageCountDiy(EmployeeInfoSearchVo searchVo) {
		return baseMapper.noPageCountDiy(searchVo);
	}

	/**
	 * 获取导出的离职档案列表
	 */
	@Override
	public void exportLeaveEmployee(EmployeeInfoSearchVo searchVo, HttpServletResponse response) {
		if (searchVo != null && searchVo.getExportFields() != null && !searchVo.getExportFields().isEmpty()) {
			String fileName = "离职档案批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
			//获取要导出的列表
			List<EmployeeLeaveExportVO> list = new ArrayList<>();
			//获取要导出的列表
			searchVo.setFileStatus(CommonConstants.ONE_INT);
			long count = noPageCountLeaveDiy(searchVo);
			// baseMapper.getTEmployeeLeaveExportList(employeeInfo);
			ServletOutputStream out = null;
			try {
				out = response.getOutputStream();
				response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
				response.setCharacterEncoding("utf-8");
				response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
				// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
				ExcelWriter excelWriter = EasyExcel.write(out, EmployeeLeaveExportVO.class).includeColumnFieldNames(searchVo.getExportFields()).build();
				int index = 0;
				if (count > CommonConstants.ZERO_INT) {
					WriteSheet writeSheet;
					ExcelUtil<EmployeeLeaveExportVO> util;
					for (int i = 0; i <= count; ) {
						// 获取实际记录
						searchVo.setLimitStart(i);
						searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
						list = noPageLeaveDiy(searchVo);
						if (Common.isNotNull(list)) {
							writeSheet = EasyExcel.writerSheet("离职档案批量导出" + index).build();
							excelWriter.write(list, writeSheet);
							index++;
						}
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
						if (Common.isNotNull(list)) {
							list.clear();
						}
					}
				} else {
					WriteSheet writeSheet = EasyExcel.writerSheet("离职档案批量导出" + index).build();
					excelWriter.write(list, writeSheet);
				}
				if (Common.isNotNull(list)) {
					list.clear();
				}
				out.flush();
				excelWriter.finish();
			} catch (Exception e) {
				log.error("执行异常", e);
			} finally {
				try {
					if (null != out) {
						out.close();
					}
				} catch (IOException e) {
					log.error("执行异常", e);
				}
			}
		}
	}

	private List<EmployeeLeaveExportVO> noPageLeaveDiy(EmployeeInfoSearchVo searchVo) {
		return baseMapper.noPageLeaveDiy(searchVo);
	}

	private long noPageCountLeaveDiy(EmployeeInfoSearchVo searchVo) {
		return baseMapper.noPageCountLeaveDiy(searchVo);
	}

	@Override
	public Map<String, DispatchEmpVo> getDispatchEmpVo(DispatchCheckVo checkVo) {
		List<DispatchEmpVo> voList = baseMapper.getDispatchEmpVo(checkVo);
		if (Common.isNotNull(voList)) {
			Map<String, DispatchEmpVo> voMap = new HashMap<>();
			for (DispatchEmpVo vo : voList) {
				voMap.put(vo.getEmpIdcard(), vo);
			}
			return voMap;
		}
		return null;
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 新增派单的档案 项目档案 合同
	 * @Date 21:51 2022/7/20
	 * @Param
	 **/
	@Override
	public EmpDispatchAddVo addDispatchInfo(EmpDispatchAddVo addVo) {
		if (Common.isEmpty(addVo)) {
			return new EmpDispatchAddVo();
		}
		//员工档案
		Map<String, EmpAddDispatchVo> empAddsMap = addVo.getEmpAddsMap();
		//员工合同
		Map<String, EmpContractDispatchVo> contractsMap = addVo.getContractsMap();
		//员工项目档案
		Map<String, EmpProjectDispatchVo> projectsMap = addVo.getProjectsMap();
		//员工项目档案更新岗位等信息
		Map<String, EmpProjectDispatchVo> projectsUpdateMap = addVo.getProjectsUpdateMap();
		// 新增档案
		saveEmp(empAddsMap);
		// 更新项目档案的岗位信息
		updateProjectPost(projectsUpdateMap);
		// 新增项目档案不需要返回ID
		saveProject(empAddsMap, projectsMap);
		// 新增合同
		saveContract(projectsMap, contractsMap, empAddsMap);
		addVo.setProjectsMap(projectsMap);
		addVo.setEmpAddsMap(empAddsMap);
		addVo.setContractsMap(contractsMap);
		return addVo;
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 派单审核通过 同步人员档案 项目档案 合同状态信息
	 * @Date 19:30 2022/8/1
	 * @Param
	 **/
	@Override
	public Boolean updateEmpInfo(UpdateEmpVo vo) throws IllegalAccessException {
		if (Common.isNotNull(vo)) {
			TEmployeeInfo employeeInfo = null;
			TEmployeeProject p = null;
			if (Common.isNotNull(vo.getEmpIdCard())) {
				if (CommonConstants.ZERO_STRING.equals(vo.getType())) {
					employeeInfo = baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
							.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
							.eq(TEmployeeInfo::getEmpIdcard, vo.getEmpIdCard())
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(employeeInfo)) {
						if (Common.isNotNull(vo.getContactAddress())) {
							employeeInfo.setContactAddress(vo.getContactAddress());
						}
						employeeInfo.setStatus(CommonConstants.ONE_INT);
					}

					if (Common.isNotNull(vo.getProjectNo())) {
						p = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
								.eq(TEmployeeProject::getDeleteFlag, CommonConstants.ZERO_INT)
								.eq(TEmployeeProject::getEmpIdcard, vo.getEmpIdCard())
								.eq(TEmployeeProject::getDeptNo, vo.getProjectNo())
								.eq(TEmployeeProject::getStatus, CommonConstants.ZERO_INT)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Common.isNotNull(p)) {
							p.setStatus(CommonConstants.ONE_INT);
							p.setOperationUserId(vo.getCreateBy());
							p.setOperationUserName(vo.getCreateName());
							// hgw加所属部门逻辑：
							tEmployeeProjectService.doSaveBelongDept(p, CommonConstants.ONE_STRING);
							// 更新入职待建档状态为已完成
							registrationPreService.updatePreStatusToEnd(p.getDeptNo(),p.getEmpIdcard());
						}
					}
				}
				if (Common.isNotNull(vo.getContractId())) {
					//2025.10.28同倩倩确认：电子签合同社保审核不同步变更状态
					TEmployeeContractInfo c = contractServicer.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TEmployeeContractInfo::getId, vo.getContractId())
							.and(
									wrapper -> wrapper.eq(TEmployeeContractInfo::getSignType, CommonConstants.ONE_STRING)
											.or().isNull(TEmployeeContractInfo::getSignType)
							)
							.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(c)) {
						TEmployeeContractAudit contractAudit = new TEmployeeContractAudit();
						contractAudit.setLinkId(c.getId());
						contractAudit.setLinkType(CommonConstants.ONE_INT);
						contractAudit.setCreateBy(vo.getCreateBy());
						contractAudit.setCreateName(vo.getCreateName());
						contractAudit.setCreateTime(LocalDateTime.now());
						//审核通过
						c.setAuditUserName(vo.getCreateName());
						if (CommonConstants.ZERO_STRING.equals(vo.getType())) {
							c.setAuditStatus(CommonConstants.TWO_INT);
							c.setInUse(CommonConstants.ZERO_STRING);
							c.setAuditTimeLast(LocalDateTime.now());
							contractAudit.setAuditStatus("审核通过");
							contractAudit.setRemark(vo.getRemarkTemp());
							contractAudit.setRootName("合同审核");
							contractServicer.updateInUseStatusById(c.getEmpId(), c.getDeptNo(), c.getId());
							if (p != null) {
								p.setContractStatus(CommonConstants.ONE_INT);
							}
							if (Common.isNotNull(employeeInfo)) {
								employeeInfo.setContractStatus(CommonConstants.ONE_INT);
							}
							//tEmployeeProjectService.updateContractStatus(c.getEmpId(), c.getSettleDomain(), CommonConstants.ONE_INT)
							baseMapper.updateContractStatus(c.getEmpId(), CommonConstants.ONE_INT);
							//更新合同状态为4线下签待归档
							TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
									.eq(TEmployeeContractPre::getContractId, c.getId())
									.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
									.last(CommonConstants.LAST_ONE_SQL));
							if (Common.isNotNull(contractPre)) {
								contractPre.setProcessStatus(CommonConstants.FOUR_STRING);
								contractPreMapper.updateById(contractPre);
							}
							//瓜子项目编码：皖A694302
							if (CommonConstants.GZ_DEPT_NO.equals(c.getDeptNo())) {
								//审核通过瓜子合同状态更新合同审核通过
								TGzOfferInfo gzOfferInfo = gzOfferInfoMapper.selectOne(Wrappers.<TGzOfferInfo>query()
										.lambda().eq(TGzOfferInfo::getNationalId, c.getEmpIdcard())
										.eq(TGzOfferInfo::getOfferStatus, CommonConstants.THIRTEEN_STRING)
										.eq(TGzOfferInfo::getDelFlag,CommonConstants.ZERO_STRING)
										.last(CommonConstants.LAST_ONE_SQL));
								if (Common.isNotNull(gzOfferInfo)) {
									gzOfferInfo.setOfferStatus(CommonConstants.EIGHT_STRING);
									gzOfferInfoMapper.updateById(gzOfferInfo);

									// 合同审核通过 生成瓜子档案里的合同信息
									tGzContractService.saveContractInfoToGzEmpInfo(c, gzOfferInfo.getId(), gzOfferInfo.getWorkLocation(),gzOfferInfo.getWorkLocationDescr());

									// 1.7.13： 合同审核通过：推送瓜子 合同信息
									TGzPushEntry tGzPushEntry = new TGzPushEntry();
									tGzPushEntry.setCreateBy(vo.getCreateBy());
									tGzPushEntry.setCreateName(vo.getCreateName());
									tGzPushEntry.setBizId(gzOfferInfo.getBizId());
									tGzPushEntry.setTaskType(CommonConstants.EIGHT_STRING);
									tGzPushEntry.setName(gzOfferInfo.getName());
									tGzPushEntry.setNationalId(gzOfferInfo.getNationalId());
									tGzPushEntryService.addPushEntry(tGzPushEntry);

									// 瓜子状态变更增加操作日志
									LGuaziOfferRecordVo lGuaziOfferRecordVo = new LGuaziOfferRecordVo();
									// 存变更前后的状态到 状态数组里
									List<String> changeStatusList = new ArrayList<>();
									changeStatusList.add(CommonConstants.THIRTEEN_STRING);
									changeStatusList.add(CommonConstants.EIGHT_STRING);

									if(changeStatusList.size() > 0){
										lGuaziOfferRecordVo.setOfferId(gzOfferInfo.getId());
										// 记录来源: 10：合同审核通过
										lGuaziOfferRecordVo.setRecordFrom(CommonConstants.TEN_STRING);
										lGuaziOfferRecordVo.setChangeStatusList(changeStatusList);
										lGuaziOfferRecordVo.setCreateBy(vo.getCreateBy());
										lGuaziOfferRecordVo.setCreateName(vo.getCreateName());
										lGuaziOfferRecordService.saveRecordOne(lGuaziOfferRecordVo, null);
									}
								}
							}
							//审核不同
						} else if (CommonConstants.ONE_STRING.equals(vo.getType())) {
							//更新合同状态为2线下签审核不通过
							TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
									.eq(TEmployeeContractPre::getContractId, c.getId())
									.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
									.last(CommonConstants.LAST_ONE_SQL));
							if (Common.isNotNull(contractPre)) {
								contractPre.setProcessStatus(CommonConstants.THREE_STRING);
								contractPreMapper.updateById(contractPre);
							}
							c.setAuditStatus(CommonConstants.THREE_INT);
							c.setInUse(CommonConstants.ONE_STRING);
							contractAudit.setAuditStatus("审核不通过");
							contractAudit.setRemark(vo.getRemarkTemp());
							contractAudit.setRootName("合同审核");
						}
						contractAuditMapper.insert(contractAudit);
						contractServicer.updateById(c);

						if (Common.isNotNull(p)) {
							//审核通过更新项目档案合同信息
							if (Common.isEmpty(p.getContractType())) {
								p.setContractType(excelUtil.getDicValueByDataType(c.getContractName(), ExcelAttributeConstants.PERSONNEL_TYPE));
							}
							if (Common.isEmpty(p.getPost())) {
								p.setPost(c.getPost());
							}
							if (Common.isEmpty(p.getWorkingHours())) {
								p.setWorkingHours(c.getWorkingHours());
							}
							if (Common.isEmpty(p.getTryPeriod())) {
								p.setTryPeriod(null == c.getTryPeriod() ? "无" : c.getTryPeriod());
							}
							if (Common.isEmpty(p.getEnjoinDate())) {
								p.setEnjoinDate(null != c.getContractStart() ? c.getContractStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : null);
							}
						}
					}
				}
				if (Common.isNotNull(employeeInfo)) {
					baseMapper.updateById(employeeInfo);
				}
				if (Common.isNotNull(p)) {
					tEmployeeProjectService.updateById(p);
				}
			}
		}
		return true;
	}

	@Override
	public Boolean checkMobile(String mobile) {
		if (Common.isEmpty(mobile)) {
			return true;
		}
		return baseMapper.selectCount(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_STRING)
				.eq(TEmployeeInfo::getEmpPhone, mobile)
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ZERO_STRING)) > 0;
	}

	@Override
	public TEmployeeInfo getInfoByIdcard(String idcard) {
		return baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, idcard)
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
	}

	@Override
	public TEmployeeInfo getInfoByDelete(String idcard) {
		return baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, idcard)
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ONE_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
	}

	private void saveContract(Map<String, EmpProjectDispatchVo> projectsMap,
							  Map<String, EmpContractDispatchVo> contractsMap,
							  Map<String, EmpAddDispatchVo> empAddsMap) {
		if (Common.isNotNull(contractsMap)) {
			EmpContractDispatchVo contractAdd;
			TEmployeeContractInfo contract;
			EmpAddDispatchVo emp;
			EmpProjectDispatchVo project;
			TEmployeeContractAudit audit;
			for (Map.Entry<String, EmpContractDispatchVo> entry : contractsMap.entrySet()) {
				contractAdd = entry.getValue();
				try {
					if (Common.isNotNull(contractAdd)) {
						contract = new TEmployeeContractInfo();
						BeanUtil.copyProperties(contractAdd, contract);
						if (Common.isEmpty(contract.getEmpId()) && Common.isNotNull(projectsMap)) {
							project = projectsMap.get(contract.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + contract.getDeptNo());
							if (Common.isNotNull(project)) {
								contract.setEmpId(project.getId());
								contract.setEmpNo(project.getEmpNo());
							}
							emp = empAddsMap.get(contract.getEmpIdcard());
							if (Common.isNotNull(emp)) {
								contract.setEmpId(emp.getId());
								contract.setEmpNatrue(emp.getEmpNatrue());
								contract.setFileProvince(emp.getFileProvince());
								contract.setFileCity(emp.getFileCity());
								contract.setFileTown(emp.getFileTown());
							}
						}
						contract.setAuditStatus(CommonConstants.ONE_INT);
						contract.setApplyNo(contractServicer.getCode(false));
						contract.setInUse(CommonConstants.ONE_STRING);
						contract.setIsObsolete(CommonConstants.ZERO_STRING);
						contract.setDispatchFlag(CommonConstants.ONE_STRING);
						contract.setType(CommonConstants.ZERO_STRING);
						contractServicer.save(contract);
						//瓜子项目编码：皖A694302
						if (CommonConstants.GZ_DEPT_NO.equals(contract.getDeptNo())) {
							//合同申请瓜子合同状态更新成待签署
							TGzOfferInfo gzOfferInfo = gzOfferInfoMapper.selectOne(Wrappers.<TGzOfferInfo>query()
									.lambda().eq(TGzOfferInfo::getNationalId, contract.getEmpIdcard())
									.eq(TGzOfferInfo::getOfferStatus, "97")
									.eq(TGzOfferInfo::getDelFlag,CommonConstants.ZERO_STRING)
									.last(CommonConstants.LAST_ONE_SQL));
							if (Common.isNotNull(gzOfferInfo)) {
								// 13：待签署 更新 入职日期为合同开始时间
								gzOfferInfo.setExpEntryDate(contract.getContractStart());
								gzOfferInfo.setOfferStatus(CommonConstants.THIRTEEN_STRING);
								gzOfferInfoMapper.updateById(gzOfferInfo);

								// 1.7.13： 合同提交申请：推送瓜子 更新状态
								TGzPushEntry tGzPushEntry = new TGzPushEntry();
								tGzPushEntry.setCreateBy(contract.getCreateBy());
								tGzPushEntry.setCreateName(contract.getCreateName());
								tGzPushEntry.setBizId(gzOfferInfo.getBizId());
								tGzPushEntry.setTaskType(CommonConstants.THIRTEEN_STRING);
								tGzPushEntry.setName(gzOfferInfo.getName());
								tGzPushEntry.setNationalId(gzOfferInfo.getNationalId());
								tGzPushEntryService.addPushEntry(tGzPushEntry);

								// 瓜子状态变更增加操作日志
								LGuaziOfferRecordVo lGuaziOfferRecordVo = new LGuaziOfferRecordVo();
								// 存变更前后的状态到 状态数组里
								List<String> changeStatusList = new ArrayList<>();
								changeStatusList.add("97");
								changeStatusList.add(CommonConstants.THIRTEEN_STRING);

								if(changeStatusList.size() > 0){
									lGuaziOfferRecordVo.setOfferId(gzOfferInfo.getId());
									// 记录来源: 9：发起合同申请
									lGuaziOfferRecordVo.setRecordFrom(CommonConstants.NINE_STRING);
									lGuaziOfferRecordVo.setChangeStatusList(changeStatusList);
									lGuaziOfferRecordVo.setCreateBy(contract.getCreateBy());
									lGuaziOfferRecordVo.setCreateName(contract.getCreateName());
									lGuaziOfferRecordService.saveRecordOne(lGuaziOfferRecordVo, null);
								}
							}
						}
						audit = new TEmployeeContractAudit();
						addContractAudit(contract, audit);
						contractAdd.setId(contract.getId());
						contractAdd.setEmpNo(contract.getEmpNo());
						contractsMap.put(contractAdd.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + contractAdd.getDeptNo(), contractAdd);
					}
				} catch (Exception e) {
					log.error(contractAdd.getEmpIdcard() + CommonConstants.COLON_STRING + "派单新增合同失败", e);
				}
			}
		}

	}

	private void addContractAudit(TEmployeeContractInfo contract, TEmployeeContractAudit audit) {
		audit.setCreateBy(contract.getCreateBy());
		audit.setCreateName(contract.getCreateName());
		audit.setCreateTime(LocalDateTime.now());
		audit.setUpdateBy(contract.getUpdateBy());
		audit.setUpdateTime(LocalDateTime.now());
		audit.setLinkId(contract.getId());
		audit.setLinkType(CommonConstants.ONE_INT);
		audit.setRootName("提交申请");
		contractAuditMapper.insert(audit);
	}

	private void saveEmp(Map<String, EmpAddDispatchVo> empAddsMap) {
		if (Common.isNotNull(empAddsMap)) {
			EmpAddDispatchVo empAdd;
			TEmployeeInfo employeeInfo;
			java.sql.Date date;
			for (Map.Entry<String, EmpAddDispatchVo> entry : empAddsMap.entrySet()) {
				empAdd = entry.getValue();
				try {
					if (Common.isNotNull(empAdd)) {
						employeeInfo = new TEmployeeInfo();
						BeanUtil.copyProperties(empAdd, employeeInfo);
						employeeInfo.setEmpCode(getCode());
						employeeInfo.setContactAddress(empAdd.getContactAddress());
						if (empAdd.getHignEducation().equals("文盲")) {
							employeeInfo.setHignEducation("1");
						}else if (empAdd.getHignEducation().equals("小学")) {
							employeeInfo.setHignEducation("2");
						}else if (empAdd.getHignEducation().equals("初中")) {
							employeeInfo.setHignEducation("3");
						}else if (empAdd.getHignEducation().equals("高中")) {
							employeeInfo.setHignEducation("4");
						}else if (empAdd.getHignEducation().equals("大专")) {
							employeeInfo.setHignEducation("5");
						}else if (empAdd.getHignEducation().equals("本科")) {
							employeeInfo.setHignEducation("6");
						}else if (empAdd.getHignEducation().equals("硕士")) {
							employeeInfo.setHignEducation("7");
						}else if (empAdd.getHignEducation().equals("博士")) {
							employeeInfo.setHignEducation("8");
						}else if (empAdd.getHignEducation().equals("技工")) {
							employeeInfo.setHignEducation("9");
						}else if (empAdd.getHignEducation().equals("职高")) {
							employeeInfo.setHignEducation("10");
						}else if (empAdd.getHignEducation().equals("中专")) {
							employeeInfo.setHignEducation("11");
						}else {
							//优化 如果非设定的最高学历 直接默认空
							employeeInfo.setHignEducation(null);
						}
						if ("5".equals(employeeInfo.getHignEducation())
								|| "6".equals(employeeInfo.getHignEducation())
								|| "7".equals(employeeInfo.getHignEducation())
								|| "8".equals(employeeInfo.getHignEducation())) {
							employeeInfo.setIsCollege(CommonConstants.ONE_INT);
						} else {
							employeeInfo.setIsCollege(CommonConstants.ZERO_INT);
						}
						employeeInfo.setStatus(CommonConstants.ZERO_INT);
						date = IdCardUtil.getBirthdate(employeeInfo.getEmpIdcard());
						if (Common.isNotNull(date)) {
							//初始化年龄
							employeeInfo.setEmpAge(IdCardUtil.IdNOToAge(employeeInfo.getEmpIdcard()));
							employeeInfo.setEmpBirthday(date);
						}
						employeeInfo.setEmpSex(IdCardUtil.getSex(employeeInfo.getEmpIdcard()));
						baseMapper.insert(employeeInfo);
						empAdd.setId(employeeInfo.getId());
						empAdd.setEmpCode(employeeInfo.getEmpCode());
						empAddsMap.put(empAdd.getEmpIdcard(), empAdd);
					}
				} catch (Exception e) {
					log.error(empAdd.getEmpIdcard() + CommonConstants.COLON_STRING + "派单新增档案失败", e);
				}
			}
		}
	}

	private void saveProject(Map<String, EmpAddDispatchVo> empAddsMap, Map<String, EmpProjectDispatchVo> projectsMap) {
		if (Common.isNotNull(projectsMap)) {
			EmpProjectDispatchVo projectAdd;
			TEmployeeProject project;
			EmpAddDispatchVo emp;
			for (Map.Entry<String, EmpProjectDispatchVo> entry : projectsMap.entrySet()) {
				projectAdd = entry.getValue();
				if (Common.isNotNull(projectAdd.getNeedUpdate()) && projectAdd.getNeedUpdate()) {
					continue;
				}
				try {
					if (Common.isNotNull(projectAdd)) {
						project = new TEmployeeProject();
						BeanUtil.copyProperties(projectAdd, project);
						if (Common.isEmpty(project.getEmpId()) && Common.isNotNull(empAddsMap)) {
							emp = empAddsMap.get(project.getEmpIdcard());
							if (Common.isNotNull(emp)) {
								project.setEmpCode(emp.getEmpCode());
								project.setEmpId(emp.getId());
							}
						}
						project.setProjectSource(CommonConstants.ONE_STRING);
						project.setEmpNo(tEmployeeProjectService.getEmpNo(project.getDeptNo()));
						tEmployeeProjectService.save(project);
						// 增加，同步CSP
						tEmployeeProjectService.doSaveBelongDept(project, CommonConstants.ONE_STRING);
						// 更新入职待建档状态为已完成
						registrationPreService.updatePreStatusToEnd(project.getDeptNo(),project.getEmpIdcard());
						projectAdd.setId(project.getId());
						projectAdd.setEmpNo(project.getEmpNo());
						projectsMap.put(project.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + project.getDeptNo(), projectAdd);
						//查询人员档案
						TEmployeeInfo tEmployeeInfo = baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
								.eq(TEmployeeInfo::getEmpIdcard, project.getEmpIdcard())
								.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL)
								.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT).last(CommonConstants.LAST_ONE_SQL));
						if (Common.isNotNull(tEmployeeInfo)) {
							TEmployeeInfo tEmployeeInfoCompare = baseMapper.selectById(tEmployeeInfo.getId());
							if (Common.isNotNull(tEmployeeInfo.getProjectNum())) {
								tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() + CommonConstants.ONE_INT);
							} else {
								tEmployeeInfo.setProjectNum(CommonConstants.ONE_INT);
							}

							tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],
									tEmployeeInfoCompare.getId(), "", tEmployeeInfoCompare, tEmployeeInfo);
							baseMapper.updateById(tEmployeeInfo);
						}
					}
				} catch (Exception e) {
					log.error(projectAdd.getEmpIdcard() + CommonConstants.COLON_STRING + "派单新增项目档案失败", e);
				}
			}
		}
	}

	private void updateProjectPost(Map<String, EmpProjectDispatchVo> projectsMap) {
		if (Common.isNotNull(projectsMap)) {
			EmpProjectDispatchVo projectAdd;
			for (Map.Entry<String, EmpProjectDispatchVo> entry : projectsMap.entrySet()) {
				projectAdd = entry.getValue();
				if (Common.isNotNull(projectAdd.getNeedUpdate()) && projectAdd.getNeedUpdate()) {
					tEmployeeProjectService.updatePostByEmpDeptNo(projectAdd.getDeptNo(), projectAdd.getTryPeriod(), projectAdd.getPost(), projectAdd.getEmpIdcard());
				}
			}
		}
	}

	/**
	 * @Description: 更新人员档案的商险状态
	 * @Author: hgw
	 * @Date: 2022/11/23 17:45
	 * @return: java.lang.Boolean
	 **/
	@Override
	public Boolean updateEmployeeInfoInsuranceStatus(EmpStatusVo vo) {
		if (Common.isEmpty(vo) || null == vo.getEmpInfo() || vo.getEmpInfo().isEmpty()) {
			return false;
		}
		for (EmpIdCardAndDeptVo emp : vo.getEmpInfo()) {
			baseMapper.updateEmployeeInfoInsuranceStatus(emp);
		}
		return true;
	}

	/**
	 * @Description: 更新人员档案的薪资状态
	 * @Author: hgw
	 * @Date: 2022/11/23 17:45
	 * @return: java.lang.Boolean
	 **/
	@Override
	public Boolean updateEmployeeInfoSalaryStatus(EmpStatusVo vo) {
		if (Common.isEmpty(vo) || null == vo.getEmpInfo() || vo.getEmpInfo().isEmpty()) {
			return false;
		}
		for (EmpIdCardAndDeptVo emp : vo.getEmpInfo()) {
			baseMapper.updateEmployeeInfoSalaryStatus(emp);
		}
		return true;
	}

	/**
	 * @Description: 每月1号更新人员档案、项目档案的薪资状态
	 * @Author: hgw
	 * @Date: 2022/11/23 17:45
	 * @return: java.lang.Boolean
	 **/
	@Override
	public void everyMonthUpdateSalaryStatus() {
		baseMapper.everyMonthUpdateEmployeeInfoSalaryStatus();
		tEmployeeProjectService.everyMonthUpdateEmployeeSalaryStatus();
	}

	/**
	 * @Description: 每天更新人员档案、项目档案的过期合同为2不在用
	 * @Author: hgw
	 * @Date: 2022/11/23 17:45
	 * @return: java.lang.Boolean
	 **/
	@Override
	public void everyDayUpdateEmployeeContractStatus() {
		baseMapper.everyDayUpdateEmployeeInfoContractStatus();
		tEmployeeProjectService.everyDayUpdateEmployeContractStatus();
	}

	@Override
	public void updateContractStatus(String empId, int status) {
		baseMapper.updateContractStatus(empId, status);
	}

	@Override
	public R<HcmEmployeeInfoVO> getHcmEmpInfo(String idCard) {
		HcmEmployeeInfoVO a = this.getHcmEmployeeInfoVoByIdCard(idCard);
		return R.ok(a);
	}

	/**
	 * HCM获取人员信息列表
	 * @param idCardList 身份证列表
	 *
	 * @author chenyuxi
	 * @date 2025/8/6
	 * @since v1.7.14
	 * @return R<List<HcmEmployeeInfoVO>>
	 **/
	@Override
	public R<List<HcmEmployeeInfoVO>> getHcmEmpInfoList(List<String> idCardList) {

		if(idCardList.size() > 100){
			return R.failed("单次档案信息查询不能超过100条");
		}
		if(idCardList.size() == 0){
			return R.failed("暂无数据查询");
		}

		Set<String> idCardSet = idCardList.stream().collect(Collectors.toSet());

		List<HcmEmployeeInfoVO> list = new ArrayList<>();
		HcmEmployeeInfoVO vo;

		// 获取个人信息列表
		List<HcmArchiveBasicVo> basicList = baseMapper.getHcmArchiveBasicList(idCardSet);
		if(Common.isEmpty(basicList)){
			return R.failed("暂无数据返回");
		}

		// 收集区域Id集合信息
		Set<Integer> areaIdSet = new HashSet<>();
		Map<Integer, String> areaMap = new HashMap<>();
		// 收集身份证集合
		Set<String> empIdCardSet = new HashSet<>();

		for (HcmArchiveBasicVo basicInfo : basicList) {
			areaIdSet.add(basicInfo.getIdProvince());
			areaIdSet.add(basicInfo.getContactProvince());
			areaIdSet.add(basicInfo.getIdCity());
			areaIdSet.add(basicInfo.getContactCity());
			areaIdSet.add(basicInfo.getIdTown());
			areaIdSet.add(basicInfo.getContactTown());

			empIdCardSet.add(basicInfo.getEmpIdCard());
		}
		// 获取地区的中文名
		List<SysAreaVo> areaList = baseMapper.getSysAreaList(areaIdSet);
		if(Common.isNotNull(areaList)){
			areaMap = areaList.stream().collect(Collectors.toMap(SysAreaVo::getId, SysAreaVo::getName));
		}

		// 调用字典服务，渲染字典值
		R<Map<String, Map<String, Map<String, String>>>> dictR = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
				, "/dict/inner/getDictToValue", null, Map.class, SecurityConstants.FROM_IN);
		Map<String, Map<String, Map<String, String>>> dictDataMap;
		Map<String, Map<String, String>> dictMap;
		// 婚姻状况
		Map<String, String> empMarriMap = new HashMap<>();
		// 民族
		Map<String, String> empNationalMap = new HashMap<>();
		// 政治面貌
		Map<String, String> empPoliticalMap = new HashMap<>();
		// 户口性质
		Map<String, String> regisTypeMap = new HashMap<>();
		// 最高学历
		Map<String, String> educationMap = new HashMap<>();
		// 学历类型
		Map<String, String> educationTypeMap = new HashMap<>();
		// 与本人关系
		Map<String, String> familyRelationMap = new HashMap<>();
		// 资格证书名称
		Map<String, String> qualificationTypeMap = new HashMap<>();

		if (dictR == null || dictR.getData() == null) {
			return R.failed("获取字典失败！");
		} else {
			dictDataMap = dictR.getData();
			dictMap = dictDataMap.get("data");
			empMarriMap = dictMap.get("emp_married");
			empNationalMap = dictMap.get("emp_national");
			empPoliticalMap = dictMap.get("emp_political");
			regisTypeMap = dictMap.get("emp_registype");
			educationMap = dictMap.get("education");
			educationTypeMap = dictMap.get("education_type");
			familyRelationMap = dictMap.get("family_relation");
			qualificationTypeMap = dictMap.get("qualification_type");
		}

		// 获取紧急联系人
		List<TEmpContactInfo> contactList = tEmpContactInfoService.list(Wrappers.<TEmpContactInfo>query().lambda()
				.in(TEmpContactInfo::getEmpIdcard, empIdCardSet));
		Map<String, TEmpContactInfo> contactMap = new HashMap<>();
		if(Common.isNotNull(contactList)){
			contactMap = contactList.stream().collect(Collectors.toMap(TEmpContactInfo::getEmpIdcard, v -> v, (v1, v2) -> v1));
		}

		// 获取社保户信息
		Map<String,String> socialFundMap = tEmployeeProjectService.getSocialFundByEmpIdcardSet(empIdCardSet);

		// 赋值个人信息
		for (HcmArchiveBasicVo basicInfo : basicList) {
			// 赋值字典值
			if(Common.isNotNull(basicInfo.getEducationValue())
					&& Common.isNotNull(educationMap) && Common.isNotNull(educationMap.get(basicInfo.getEducationValue()))){
				basicInfo.setEducation(educationMap.get(basicInfo.getEducationValue()));
			}
			if(Common.isNotNull(basicInfo.getResidentTypeValue())
					&& Common.isNotNull(regisTypeMap) && Common.isNotNull(regisTypeMap.get(basicInfo.getResidentTypeValue()))){
				basicInfo.setResidentType(regisTypeMap.get(basicInfo.getResidentTypeValue()));
			}
			if(Common.isNotNull(basicInfo.getMaritalStatusValue())
					&& Common.isNotNull(empMarriMap) && Common.isNotNull(empMarriMap.get(basicInfo.getMaritalStatusValue()))){
				basicInfo.setMaritalStatus(empMarriMap.get(basicInfo.getMaritalStatusValue()));
			}
			if(Common.isNotNull(basicInfo.getNationValue())
					&& Common.isNotNull(empNationalMap) && Common.isNotNull(empNationalMap.get(basicInfo.getNationValue()))){
				basicInfo.setNation(empNationalMap.get(basicInfo.getNationValue()));
			}
			if(Common.isNotNull(basicInfo.getPoliticalValue())
					&& Common.isNotNull(empPoliticalMap) && Common.isNotNull(empPoliticalMap.get(basicInfo.getPoliticalValue()))){
				basicInfo.setPolitical(empPoliticalMap.get(basicInfo.getPoliticalValue()));
			}
			// 赋值户籍地区
			String idProvinceName = "";
			String idCityName = "";
			String idTownName = "";

			if(Common.isNotNull(basicInfo.getIdProvince()) &&
					Common.isNotNull(areaMap.get(basicInfo.getIdProvince()))){
				idProvinceName = areaMap.get(basicInfo.getIdProvince());
			}
			if(Common.isNotNull(basicInfo.getIdCity()) &&
					Common.isNotNull(areaMap.get(basicInfo.getIdCity()))){
				idCityName = areaMap.get(basicInfo.getIdCity());
			}
			if(Common.isNotNull(basicInfo.getIdTown()) &&
					Common.isNotNull(areaMap.get(basicInfo.getIdTown()))){
				idTownName = areaMap.get(basicInfo.getIdTown());
			}
			basicInfo.setNativePlace(idProvinceName+idCityName+idTownName);
			basicInfo.setHouseholdPlace(idProvinceName+idCityName+idTownName);
			// 赋值联系地址
			String contactProvinceName = "";
			String contactCityName = "";
			String contactTownName = "";
			String contactAddress = basicInfo.getContactAddress();

			if(Common.isNotNull(basicInfo.getContactProvince()) &&
					Common.isNotNull(areaMap.get(basicInfo.getContactProvince()))){
				contactProvinceName = areaMap.get(basicInfo.getContactProvince());
			}
			if(Common.isNotNull(basicInfo.getContactCity()) &&
					Common.isNotNull(areaMap.get(basicInfo.getContactCity()))){
				contactCityName = areaMap.get(basicInfo.getContactCity());
			}
			if(Common.isNotNull(basicInfo.getContactTown()) &&
					Common.isNotNull(areaMap.get(basicInfo.getContactTown()))){
				contactTownName = areaMap.get(basicInfo.getContactTown());
			}
			basicInfo.setContactAddress(contactProvinceName+contactCityName+contactTownName+contactAddress);

			if(Common.isNotNull(basicInfo.getEmpIdCard())){
				// 赋值紧急联系人信息
				if(Common.isNotNull(contactMap) && Common.isNotNull(contactMap.get(basicInfo.getEmpIdCard()))){
					TEmpContactInfo contactInfo = contactMap.get(basicInfo.getEmpIdCard());
					basicInfo.setEmergencyContactName(contactInfo.getEmpName());
					basicInfo.setEmergencyContactRelation(contactInfo.getRelationType());
					basicInfo.setEmergencyContactPhone(contactInfo.getTel());
				}
				// 赋值社保户
				if(Common.isNotNull(socialFundMap) && Common.isNotNull(socialFundMap.get(basicInfo.getEmpIdCard()))){
					basicInfo.setSocialHouseholdName(socialFundMap.get(basicInfo.getEmpIdCard()));
				}
			}
		}

		// 身份证做key，个人信息做value
		Map<String, HcmArchiveBasicVo> basicMap = basicList.stream().collect(Collectors.toMap(HcmArchiveBasicVo::getEmpIdCard, v -> v, (v1, v2) -> v1));

		// 获取家庭信息列表
		List<HcmArchiveFamilyVo> familyList = baseMapper.getHcmArchiveFamilyList(empIdCardSet);
		Map<String, List<HcmArchiveFamilyVo>> familyMap = new HashMap<>();
		if(Common.isNotNull(familyList)){
			for (HcmArchiveFamilyVo familyInfo : familyList) {
				// 赋值字典值
				if(Common.isNotNull(familyInfo.getRelation())
						&& Common.isNotNull(familyRelationMap) && Common.isNotNull(familyRelationMap.get(familyInfo.getRelation()))){
					familyInfo.setRelationName(familyRelationMap.get(familyInfo.getRelation()));
				}
				List<HcmArchiveFamilyVo> familyVoList = familyMap.get(familyInfo.getEmpIdCard());
				if(Common.isEmpty(familyVoList)){
					familyVoList = new ArrayList<>();
				}
				familyVoList.add(familyInfo);
				familyMap.put(familyInfo.getEmpIdCard(),familyVoList);
			}
		}
		// 获取教育信息列表
		List<HcmArchiveEducationVo> educationList = baseMapper.getHcmArchiveEducationList(empIdCardSet);
		Map<String, List<HcmArchiveEducationVo>> educationEmpMap = new HashMap<>();
		if(Common.isNotNull(educationList)){
			for (HcmArchiveEducationVo educationInfo : educationList) {
				// 赋值字典值
				if(Common.isNotNull(educationInfo.getEducationTypeValue())
						&& Common.isNotNull(educationTypeMap) && Common.isNotNull(educationTypeMap.get(educationInfo.getEducationTypeValue()))){
					educationInfo.setIsFullTime(educationTypeMap.get(educationInfo.getEducationTypeValue()));
				}
				// 赋值字典值
				if(Common.isNotNull(educationInfo.getEducationValue())
						&& Common.isNotNull(educationMap) && Common.isNotNull(educationMap.get(educationInfo.getEducationValue()))){
					educationInfo.setEducation(educationMap.get(educationInfo.getEducationValue()));
				}

				List<HcmArchiveEducationVo> educationVoList = educationEmpMap.get(educationInfo.getEmpIdCard());
				if(Common.isEmpty(educationVoList)){
					educationVoList = new ArrayList<>();
				}
				educationVoList.add(educationInfo);
				educationEmpMap.put(educationInfo.getEmpIdCard(),educationVoList);
			}
		}

		// 获取工作经历列表
		List<HcmArchiveJobVo> workList = baseMapper.getHcmArchiveJobList(empIdCardSet);
		Map<String, List<HcmArchiveJobVo>> workMap = new HashMap<>();
		if(Common.isNotNull(workList)){
			for (HcmArchiveJobVo workInfo : workList) {
				List<HcmArchiveJobVo> workVoList = workMap.get(workInfo.getEmpIdCard());
				if(Common.isEmpty(workVoList)){
					workVoList = new ArrayList<>();
				}
				workVoList.add(workInfo);
				workMap.put(workInfo.getEmpIdCard(),workVoList);
			}
		}

		// 获取不良记录列表
		List<HcmArchiveBadRecordVo> badRecordList = baseMapper.getHcmArchiveBadRecordList(empIdCardSet);
		Map<String, List<HcmArchiveBadRecordVo>> badRecordMap = new HashMap<>();
		if(Common.isNotNull(badRecordList)){
			for (HcmArchiveBadRecordVo badRecordInfo : badRecordList) {
				List<HcmArchiveBadRecordVo> badRecordVoList = badRecordMap.get(badRecordInfo.getEmpIdCard());
				if(Common.isEmpty(badRecordVoList)){
					badRecordVoList = new ArrayList<>();
				}
				badRecordVoList.add(badRecordInfo);
				badRecordMap.put(badRecordInfo.getEmpIdCard(), badRecordVoList);
			}
		}

		// 获取资格证书列表
		List<HcmArchiveCertificateVo> certificateList = baseMapper.getHcmArchiveCertificateList(empIdCardSet);
		Map<String, List<HcmArchiveCertificateVo>> certificateMap = new HashMap<>();
		if(Common.isNotNull(certificateList)){
			for (HcmArchiveCertificateVo certificateInfo : certificateList) {
				// 赋值字典值： 资格类型 找 证件名称
				if(Common.isNotNull(certificateInfo.getCertificateType())
						&& Common.isNotNull(qualificationTypeMap) && Common.isNotNull(qualificationTypeMap.get(certificateInfo.getCertificateType()))){
					certificateInfo.setCertificateName(qualificationTypeMap.get(certificateInfo.getCertificateType()));
				}
				List<HcmArchiveCertificateVo> certificateVoList = certificateMap.get(certificateInfo.getEmpIdCard());
				if(Common.isEmpty(certificateVoList)){
					certificateVoList = new ArrayList<>();
				}
				certificateVoList.add(certificateInfo);
				certificateMap.put(certificateInfo.getEmpIdCard(),certificateVoList);
			}
		}

		// 组装返回给E人事的档案信息
		for (String idCard : idCardList) {
			vo = new HcmEmployeeInfoVO();
			vo.setArchiveBasic(basicMap.get(idCard));
			vo.setArchiveFamily(familyMap.get(idCard));
			vo.setArchiveEducation(educationEmpMap.get(idCard));
			vo.setArchiveJob(workMap.get(idCard));
			vo.setArchiveCertificate(certificateMap.get(idCard));
			vo.setArchiveBadRecord(badRecordMap.get(idCard));

			list.add(vo);
		}

		return R.ok(list);
	}

	/**
	 * @param idCard
	 * @Description: 组装vo
	 * @Author: hgw
	 * @Date: 2023/11/23 15:24
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.vo.HcmEmployeeInfoVO
	 **/
	private HcmEmployeeInfoVO getHcmEmployeeInfoVoByIdCard(String idCard) {
		HcmEmployeeInfoVO vo = new HcmEmployeeInfoVO();
		// 基础信息
		vo.setArchiveBasic(baseMapper.getHcmArchiveBasicVo(idCard));
		vo.setArchiveJob(baseMapper.getHcmArchiveJobVo(idCard));
		vo.setArchiveEducation(baseMapper.getHcmArchiveEducationVo(idCard));
		vo.setArchiveCertificate(baseMapper.getHcmArchiveCertificateVo(idCard));
		vo.setArchiveFamily(baseMapper.getHcmArchiveFamilyVo(idCard));
		vo.setContract(baseMapper.getHcmContractVo(idCard));
		return vo;
	}

	/**
	 * @Author fxj
	 * @Description 每年1月1号刷新在职和离职人员的年龄信息  公式：当前年-出生年
	 * @Date 17:30 2024/8/21
	 **/
	@Override
	public void updateEmployeeAgeTask() {
		baseMapper.updateEmployeeAgeTask();
	}

	@Override
	public IPage<TEmployeeInfo> getPageAsso(Page<TEmployeeInfo> page, TEmployeeInfo employeeInfo) {
		return baseMapper.getPageAsso(page, employeeInfo);
	}

	@Override
	public R<TEmployeeInfo> getByIdAssociate(String id) {
		if (Common.isEmpty(id)) {
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		TEmployeeInfo employeeInfo = baseMapper.selectById(id);
		if (Common.isEmpty(employeeInfo)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		TPreEmpDeclaration tPreEmpDeclaration = declarationMapper.getTPreEmpDeclarationList();
		employeeInfo.setTPreEmpDeclaration(tPreEmpDeclaration);
		getAttaInfo(employeeInfo);
		getEmpAttaInfo(employeeInfo);
		return R.ok(employeeInfo);
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 获取人员档案附件信息下载ZIP
	 * @Date 11:13 2024/9/10
	 * @Param
	 **/
	@Override
	public void exportEmployeeFile(String id, HttpServletResponse response) throws Exception {
		if (Common.isEmpty(id)) {
			throw new RuntimeException(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		TEmployeeInfo emp = baseMapper.selectById(id);
		if (Common.isEmpty(emp)) {
			throw new RuntimeException(CommonConstants.NO_DATA_TO_HANDLE);
		}
		List<TAttaInfo> handles = new ArrayList<>();
		HttpGet httpGet;
		//初始化导出 response
		response.setContentType("application/octet-stream");
		response.setHeader("content-type", "application/octet-stream");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(emp.getEmpName() + emp.getEmpIdcard(), "UTF-8") + ".zip");
		ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(response.getOutputStream());
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 获取人员档案所有的附件信息
		getFilesInfo(id, handles);
		// 处理附件 压缩并下载
		if (Common.isNotNull(handles)) {
			try {
				CloseableHttpResponse response1;
				HttpEntity entity;
				byte[] data;
				HashMap<String, Integer> groupNameMap = new HashMap<>();
				ZipArchiveEntry entry;
				for (TAttaInfo fileAtta : handles) {
					httpGet = new HttpGet(fileAtta.getAttaUrl());
					response1 = httpClient.execute(httpGet);
					entity = response1.getEntity();
					data = EntityUtils.toByteArray(entity);
					entry = new ZipArchiveEntry(initFileName(fileAtta, groupNameMap));
					zipOutput.putArchiveEntry(entry);
					zipOutput.write(data);
					zipOutput.closeArchiveEntry();
				}
				zipOutput.finish();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void getFilesInfo(String id, List<TAttaInfo> handles) {
		List<TAttaInfo> attas;
		URL url;
		// 获取其他附件
		List<TEmpOtherFile> otherFiles = otherFileService.list(Wrappers.<TEmpOtherFile>query().lambda().eq(TEmpOtherFile::getEmpId, id));
		if (Common.isNotNull(otherFiles)) {
			try {
				for (TEmpOtherFile otherFile : otherFiles) {
					attas = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, otherFile.getId()));
					if (Common.isNotNull(attas)) {
						for (TAttaInfo atta : attas) {
							url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
							atta.setAttaUrl(url.toString().replace("http", "https"));
							atta.setGroupName(otherFile.getAttaName());
							handles.add(atta);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 获取其他附件以外的附件如身份证正反面
		attas = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, id));
		if (Common.isNotNull(attas)) {
			for (TAttaInfo atta : attas) {
				if (CommonConstants.TWENTY_THREE_STRING.equals(atta.getRelationType())) {
					continue;
				}
				url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
				atta.setAttaUrl(url.toString().replace("http", "https"));
				handles.add(atta);
			}
		}
	}

	private String initFileName(TAttaInfo fileAtta, HashMap<String, Integer> groupNameMap) {
		/**
		 * 关系类型(0客户附件1联系人附件2跟进记录附件3合同附件4合同归档附件5报价单6招投标7业务评估8二维码9身份证 10 户口本
		 * ；21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)；0（最高教育经历)；2（执业资格证书)；24 身份证国徽
		 * 25 户口本本人页26学信27预入职其他附件
		 */
		if (CommonConstants.NINE_STRING.equals(fileAtta.getRelationType())) {
			return "身份证1" + fileAtta.getAttaType();
		} else if (CommonConstants.TWENTY_FOUR_STRING.equals(fileAtta.getRelationType())) {
			return "身份证2" + fileAtta.getAttaType();
		} else if (CommonConstants.TWENTY_ONE_STRING.equals(fileAtta.getRelationType())) {
			return "签名1" + fileAtta.getAttaType();
		} else if (CommonConstants.TWENTY_TWO_STRING.equals(fileAtta.getRelationType())) {
			return "签名2" + fileAtta.getAttaType();
		} else if (CommonConstants.TEN_STRING.equals(fileAtta.getRelationType())) {
			return "户口本1" + fileAtta.getAttaType();
		} else if (CommonConstants.TWENTY_FIVE_STRING.equals(fileAtta.getRelationType())) {
			return "户口本2" + fileAtta.getAttaType();
		} else if (CommonConstants.TWENTY_SEVEN_STRING.equals(fileAtta.getRelationType())) {
			if (Common.isNotNull(fileAtta.getGroupName())) {
				if (Common.isNotNull(groupNameMap.get(fileAtta.getGroupName()))) {
					groupNameMap.put(fileAtta.getGroupName(), groupNameMap.get(fileAtta.getGroupName()) + 1);
				} else {
					groupNameMap.put(fileAtta.getGroupName(), 1);
				}
				return fileAtta.getGroupName() + groupNameMap.get(fileAtta.getGroupName()) + fileAtta.getAttaType();
			}
			return fileAtta.getGroupName() + fileAtta.getAttaType();
		} else {
			return fileAtta.getAttaName();
		}
	}


	@Override
	public List<TEmployeeInfo> getListByIdCardList(List<String> idList) {
		return baseMapper.getListByIdCardList(idList);
	}

	@Override
	public R<List<PreUploadEmpImportTwoVo>> batchUpdateEmployeeAndBank(MultipartFile file, PreUploadImportParamVo paramVo) throws Exception {
		TArchivesLimit archivesLimit = tArchivesLimitMapper.selectById(CommonConstants.TWO_INT);
		Integer maxLimit = 10;
		if (Common.isNotNull(archivesLimit) && Common.isNotNull(archivesLimit.getMaxNum())) {
			maxLimit = archivesLimit.getMaxNum();
		}
		if (updateAtomicInteger.incrementAndGet() <= maxLimit) {
			try {
				return batchUpdateEmployeeAndBankCore(file, paramVo);
			} catch (Exception e) {
				log.error("新批量更新人员异常：", e);
			} finally {
				updateAtomicInteger.decrementAndGet();
			}
		} else {
			// 前面做了+1（atomicInteger.incrementAndGet()）这里也要-1
			updateAtomicInteger.decrementAndGet();
			log.error("新批量更新人员超出阈值");
			return R.failed("新批量更新，" + ResultConstants.IMPORT_DOWN_LOAD_DATA);
		}
		return R.failed("新批量更新中，" + ResultConstants.IMPORT_DOWN_LOAD_DATA);
	}
	/**
	 * @Description: 批量更新人员和银行信息
	 * @Author: hgw
	 * @Date: 2024/10/16 17:43
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.pig4cloud.plugin.excel.vo.ErrorMessage>>
	 **/
	private R<List<PreUploadEmpImportTwoVo>> batchUpdateEmployeeAndBankCore(MultipartFile file, PreUploadImportParamVo paramVo) throws Exception {
		// 自定义解析Excel，判断表头、必填、格式；
		// 按项目查项目人员、档案人员、预入职人员；
		// 有项目人员，仅更新，否则看预入职人员，新增或更新，加导入标签；
		// 返回结果list。

		//对前端传递的文件进行校验
		if (paramVo == null || Common.isEmpty(paramVo.getDeptId())) {
			return R.failed("请前端传参！");
		}
		String deptId = paramVo.getDeptId();
		TSettleDomain dept = tSettleDomainService.getById(deptId);
		if (dept == null || Common.isEmpty(dept.getId())) {
			return R.failed("未找到项目！");
		}
		//对前端传递的文件进行校验
		if (file == null || file.isEmpty()) {
			return R.failed("文件为空，重新上传");
		}
		//获取文件名称 判断文件是否为 Execl
		String filename = file.getOriginalFilename();
		if (filename == null || Common.isEmpty(filename)) {
			return R.failed("文件名称为空，请重新上传！");
		}
		if (!(filename.endsWith(".xls") || filename.endsWith(".xlsx"))) {
			return R.failed("文件名称格式有误，请重新上传！" + filename);
		}
		InputStream inputStream = file.getInputStream();
		R<ExcelSheetVo> voR;
		ExcelSheetVo vo;
		List<String> specialIdCardList = null;
		R<ListStringVo> specialRes = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl()
				, salaryProperties.getAppId(), "/tsalarystandardoriginal/inner/getSpecialIdCardList", null, ListStringVo.class, SecurityConstants.FROM_IN);
		if (Common.isNotNull(specialRes) && specialRes.getData() != null && specialRes.getData().getListVo() != null){
			specialIdCardList = specialRes.getData().getListVo();
		}
		int maxRow = 1000;
		if (filename.endsWith(".xlsx")) {
			voR = DiyExcelImportUtil.readXlsx(inputStream, specialIdCardList, false, paramVo.getSheetName(), maxRow);
		} else {
			return R.failed("请使用标准模板（高版本的EXCEL）导入！");
		}
		if (voR != null && voR.getCode() == CommonConstants.SUCCESS) {
			vo = voR.getData();
		} else {
			return R.failed(voR == null ? "人员批量更新识别表格异常！" : voR.getMsg());
		}
		String[] modelTitle = {"员工姓名", "身份证号", "员工类型", "身份证开始日期", "身份证截止日期", "婚姻状况", "民族"
				, "政治面貌", "手机号码", "邮箱", "户籍所在地-省", "户籍所在地-市", "户籍所在地-区/县", "户口性质", "档案所在地-省"
				, "档案所在地-市", "档案所在地-区/县", "通信地址-省", "通信地址-市", "通信地址-区/县", "通信地址-详细地址", "备注"
				, "是否大专及以上", "最高学历", "学校", "专业", "入学时间", "毕业时间"
				, "是否为首份工作", "工作单位", "工作岗位", "开始工作日期", "结束工作日期"
				, "家庭成员姓名", "家庭成员与本人关系", "手机号码（家庭成员）"
				, "是否有职业资格证书", "申报年度", "职业资格名称"
				, "是否曾被认定为工伤", "是否有职业病", "职业病名称", "是否有传染性疾病", "传染病名称", "是否被劳动能力鉴定委员会鉴定为具有伤残等级", "伤残病名称", "伤残等级", "是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种"
				, "是否有不良记录"
				, "紧急联系人姓名", "紧急联系人与本人关系", "联系地址-省", "联系地址-市", "联系地址-区/县", "联系地址-详细地址"
				, "手机号码（紧急联系人）", "银行卡号", "开户总行", "开户省", "开户市", "开户支行", "计税月份"};
		Map<String, String> modelTitleMap = new HashMap<>();
		for (String title : modelTitle) {
			modelTitleMap.put(title, title);
		}
		int modelLength = vo.getTitleList().size();

		// 需要成对出现的表头
		Map<String, Integer> pairsSchool = new HashMap<>();
		pairsSchool.put("入学时间", CommonConstants.ZERO_INT);
		pairsSchool.put("毕业时间", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsIdCard = new HashMap<>();
		pairsIdCard.put("身份证开始日期", CommonConstants.ZERO_INT);
		pairsIdCard.put("身份证截止日期", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsHuJi = new HashMap<>();
		pairsHuJi.put("户籍所在地-省", CommonConstants.ZERO_INT);
		pairsHuJi.put("户籍所在地-市", CommonConstants.ZERO_INT);
		pairsHuJi.put("户籍所在地-区/县", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsDang = new HashMap<>();
		pairsDang.put("档案所在地-省", CommonConstants.ZERO_INT);
		pairsDang.put("档案所在地-市", CommonConstants.ZERO_INT);
		pairsDang.put("档案所在地-区/县", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsTong = new HashMap<>();
		pairsTong.put("通信地址-省", CommonConstants.ZERO_INT);
		pairsTong.put("通信地址-市", CommonConstants.ZERO_INT);
		pairsTong.put("通信地址-区/县", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsLian = new HashMap<>();
		pairsLian.put("联系地址-省", CommonConstants.ZERO_INT);
		pairsLian.put("联系地址-市", CommonConstants.ZERO_INT);
		pairsLian.put("联系地址-区/县", CommonConstants.ZERO_INT);
		Map<String, Integer> pairsKai = new HashMap<>();
		pairsKai.put("开户省", CommonConstants.ZERO_INT);
		pairsKai.put("开户市", CommonConstants.ZERO_INT);
		// 1.9.7: 主要工作经历 表头需要成对的
		Map<String, Integer> pairsWork = new HashMap<>();
		pairsWork.put("开始工作日期", CommonConstants.ZERO_INT);
		pairsWork.put("结束工作日期", CommonConstants.ZERO_INT);

		// 1 验证表头：
		ExcelColumnVo title;
		// 标题行的内容
		String titleStr;
		if (vo.getTitleList() != null && !vo.getTitleList().isEmpty()) {
			StringBuilder errorTitle = new StringBuilder();
			for (int i = 0; i < vo.getTitleList().size(); i++) {
				title = vo.getTitleList().get(i);
				titleStr = title.getContent();
				if (modelTitleMap.get(titleStr) == null) {
					errorTitle.append("第").append((i + 1)).append("列表头：").append(titleStr).append("不存在模板中；");
				}
				// 验证联动表头
				if (pairsSchool.get(titleStr) != null) {
					pairsSchool.remove(titleStr);
				}
				if (pairsIdCard.get(titleStr) != null) {
					pairsIdCard.remove(titleStr);
				}
				if (pairsHuJi.get(titleStr) != null) {
					pairsHuJi.remove(titleStr);
				}
				if (pairsDang.get(titleStr) != null) {
					pairsDang.remove(titleStr);
				}
				if (pairsTong.get(titleStr) != null) {
					pairsTong.remove(titleStr);
				}
				if (pairsLian.get(titleStr) != null) {
					pairsLian.remove(titleStr);
				}
				if (pairsKai.get(titleStr) != null) {
					pairsKai.remove(titleStr);
				}
				// 1.9.7: 主要工作经历 表头需要成对的
				if (pairsWork.get(titleStr) != null) {
					pairsWork.remove(titleStr);
				}
			}
			if (pairsSchool.size() == 1) {
				errorTitle.append("入学时间与毕业时间需要成对出现；");
			}
			if (pairsIdCard.size() == 1) {
				errorTitle.append("身份证开始与截止日期需要成对出现；");
			}
			if (pairsHuJi.size() == 1 || pairsHuJi.size() == 2) {
				errorTitle.append("户籍所在地省市县需要成对出现；");
			}
			if (pairsDang.size() == 1 || pairsDang.size() == 2) {
				errorTitle.append("档案所在地省市县需要成对出现；");
			}
			if (pairsTong.size() == 1 || pairsTong.size() == 2) {
				errorTitle.append("通信地址省市县需要成对出现；");
			}
			if (pairsLian.size() == 1 || pairsLian.size() == 2) {
				errorTitle.append("联系地址省市县需要成对出现；");
			}
			if (pairsKai.size() == 1) {
				errorTitle.append("开户省市需要成对出现；");
			}
			// 1.9.7: 主要工作经历 表头需要成对的
			if (pairsWork.size() == 1) {
				errorTitle.append("开始工作日期与结束工作日期需要成对出现；");
			}

			if (errorTitle.length() > 0) {
				return R.failed("表头错误：" + errorTitle + " 请检查调整后再次导入");
			}
		} else {
			return R.failed("表格没有表头，请检查表格数据！");
		}

		// 2 读取内容：
		if (vo.getContentList() != null && !vo.getContentList().isEmpty()) {
			// 薪资服务的开户行
			R<TBankNameMapVo> bankRes = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl()
					, salaryProperties.getAppId(), "/tbankset/inner/getBankMap", null, TBankNameMapVo.class, SecurityConstants.FROM_IN);
			Map<String, String> bankMap;
			if (Common.isEmpty(bankRes) || bankRes.getData() == null || bankRes.getData().getBankMap() == null) {
				return R.failed("获取薪资服务开户行信息失败！");
			} else {
				bankMap = bankRes.getData().getBankMap();
			}
			PreUploadEmpImportTwoVo detail;
			List<String> mobileList = new ArrayList<>();
			List<TCheckBankNo> bankList = new ArrayList<>();
			YifuUser user = SecurityUtils.getUser();
			TCheckBankNo bankCheck;

			Map<Integer, String> titleMap = new HashMap<>();
			Map<String, String> fieldMap = new HashMap<>();
			// 得到类的所有field
			Field[] allFields = PreUploadEmpImportTwoVo.class.getDeclaredFields();
			// 从map中得到对应列的field
			Field field;
			// 将有注解的field存放到fieldsMap中
			Map<String, Field> fieldsMap = new HashMap<>();
			ExcelAttribute attr;  //获取属性对应的注解属性
			for (int i = 0; i < allFields.length; i++) {
				field = allFields[i];
				if (field.isAnnotationPresent(ExcelAttribute.class)) {
					// 设置类的私有字段属性可访问
					field.setAccessible(true);
					fieldsMap.put(field.getName(), field);
					attr = field.getAnnotation(ExcelAttribute.class);
					if (attr != null) {
						fieldMap.put(attr.name(), field.getName());
					}
				}
			}
			// 组装表头与内容的对应
			for (int i = 0; i < vo.getTitleList().size(); i++) {
				title = vo.getTitleList().get(i);
				titleStr = title.getContent();
				if (Common.isNotNull(titleStr) && fieldMap.get(titleStr) != null) {
					titleMap.put(i, fieldMap.get(titleStr));
				}
			}

			Class<?> fieldType;  // 取得类型,并根据对象类型设置值

			List<PreUploadEmpImportTwoVo> excelList = new ArrayList<>();
			String idNumber = "empIdcard";
			Map<String, Integer> phoneTitleMap = new HashMap<>();
			phoneTitleMap.put("empPhone", CommonConstants.ZERO_INT);
			phoneTitleMap.put("tel", CommonConstants.ZERO_INT);
			phoneTitleMap.put("contractTel", CommonConstants.ZERO_INT);
			String shuName;
			String shuValue;
			String dictValue;
			// 必填项未填写
			StringBuilder errorMust;
			// 格式不正确
			StringBuilder errorFormat;
			// 校验是否通过
			StringBuilder errorCheck;
			// 不存在档案，则仅返回这个信息
			String errorCur;
			// 已存在的主档案Map
			//Map<String, String> empMap = new HashMap<>();
			// 已存在的主档案
			//String curVo
			// 档案map
			Map<String, TEmployeeInfo> existEmpMap = this.getMapByDeptId(paramVo.getDeptId());
			Map<String, TEmpContactInfo> existContactMap = this.getTEmpContactInfoMapByDeptId(paramVo.getDeptId());
			TEmployeeInfo saveEmp;
			// 字典Map
			Map<String, String> dictMap = new HashMap<>();
			// 存放父级area的值
			Map<String, String> parentAreaMap = new HashMap<>();
			Map<String, Date> startDateMap;

			// 手机号是否已存在
			List<String> phoneList = new ArrayList<>();
			String errorCurInfo = "该项目下无此员工，请核实";
			String errorCurInfoStatus = "该人员档案状态未在档，请核实";
			int lineNum = 2;
			for (Map<String, String> rowMap : vo.getContentList()) {
				// curVo = null
				errorMust = new StringBuilder();
				errorFormat = new StringBuilder();
				errorCheck = new StringBuilder();
				// 每一行都要初始化起始时间
				startDateMap = new HashMap<>();
				detail = new PreUploadEmpImportTwoVo();
				detail.setLineNum(lineNum++);
				for (int i = 0; i < modelLength; i++) {
					shuName = titleMap.get(i);
					shuValue = rowMap.get(String.valueOf(i));
					if (Common.isNotNull(shuName)) {
						// 忽略Value的值
						if (!shuName.contains("Value")) {
							if (idNumber.equals(shuName)) {
								if (Common.isEmpty(shuValue)) {
									errorMust.append("身份证号;");
								}
							}
							if (phoneTitleMap.get(shuName) != null && Common.isNotNull(shuValue)) {
								phoneList.add(shuValue);
							}
							field = fieldsMap.get(shuName);
							if (field != null) {
								attr = field.getAnnotation(ExcelAttribute.class);
								//if (curVo == null) {
									// 必填
									if (attr.isNotEmpty() && Common.isEmpty(shuValue)) {
										errorMust.append(attr.name()).append(";");
									}
								//}
								if (Common.isNotNull(shuValue)) {
									shuValue = shuValue.trim();
									//校验字段是否符合要求 返回错误信息
									dictValue = DiyExcelImportUtil.validateUtil(shuValue, attr, errorFormat, dictMap, parentAreaMap, shuName, false, startDateMap);
									//校验字段是否符合要求2 开户行
									if ("bankName".equals(shuName) && bankMap.get(shuValue) == null) {
										errorFormat.append(attr.name()).append("_不符合财务要求，请查薪资配置；");
									}
									// 1.9.7 : 校验年份不可为未来年份
									if ("declareYear".equals(shuName) && Common.isNotNull(shuValue)){
										Boolean isNum = true;
										shuValue = shuValue.replaceAll("\\..*", "");
										for (char c : shuValue.toCharArray()) {
											if (!Character.isDigit(c)) {
												errorFormat.append(attr.name()).append("_只能是纯数字；");
												isNum = false;
												break;
											}
										}
										if(isNum && shuValue.length() != 4){
											errorFormat.append(attr.name()).append("_不符合年份格式；");
										}
										if(isNum && shuValue.length() == 4 && (Integer.parseInt(shuValue) > DateUtil.getYearOfInt(new Date()))){
											errorFormat.append(attr.name()).append("_不可为未来年份；");
										}
									}

									fieldType = field.getType();
									if (Common.isNotNull(fieldType)) {
										DiyExcelImportUtil.setFields(field, shuValue, fieldType, detail);
									}
									// 塞字典返回的值
									if (Common.isNotNull(dictValue)) {
										field = fieldsMap.get(shuName + "Value");
										if (field != null) {
											fieldType = field.getType();
											if (Common.isNotNull(fieldType)) {
												DiyExcelImportUtil.setFieldsValue(field, dictValue, fieldType, detail);
											}
										}
									}
								} else {
									// 为空的检查一下起始时间有没有值，有值，截止日期不可为空
									DiyExcelImportUtil.validateUtilEmpty(shuValue, attr, errorFormat, startDateMap);
								}
							}
						}
					}
				}
				// 第一步：校验是否通过：身份证号是否有（反馈信息：身份证号不存在）→人员是否已在项（或已导入待审核）
				// （反馈信息：人员已在项，如需更新信息，请点击“批量更新”入口更新；人员“待审核”，如需更新，可“审核不通过”再次导入）
				if (Common.isNotNull(detail.getEmpIdcard())) {
					saveEmp = existEmpMap.get(detail.getEmpIdcard());
					errorCur = null;
					// 档案存在
					if (saveEmp != null) {
						if (saveEmp.getFileStatus() == CommonConstants.ZERO_INT) {
							// 第二步：其他信息并行校验
							// 1必填项未填写：紧急联系人
							// 2格式不正确：计税月份
							// 3校验是否通过：姓名&身份证号是否一致、手机号是否真实、姓名&银行卡号是否一致

							// 1必填项未填写：紧急联系人
							// 有主档案，则判断附属信息是否联动必填
							// 主的其他信息必填校验
							if (Common.isEmpty(detail.getEmpIdcard())) {
								errorMust.append("身份证号;");
							}
							// 2格式不正确：在循环里已经判断了
							// 3校验是否通过：姓名&身份证号是否一致、手机号是否真实、姓名&身份证&银行卡号是否一致
							if (Common.isNotNull(detail.getBankNo())) {
								if (Common.isNotNull(detail.getEmpName())) {
									bankCheck = new TCheckBankNo();
									bankCheck.setBankNo(detail.getBankNo());
									bankCheck.setName(detail.getEmpName());
									bankCheck.setIdNum(detail.getEmpIdcard());
									bankList.add(bankCheck);
								} else {
									errorMust.append("有银行卡号则员工姓名必填;");
								}
							}
							// 联动必填校验：
							if (Common.isNotNull(detail.getFileProvince()) && Common.isEmpty(detail.getFileCity())) {
								errorMust.append("档案所在地-省、市联动必填;");
							}
							if (Common.isNotNull(detail.getContactProvince()) && (Common.isEmpty(detail.getContactCity()) || Common.isEmpty(detail.getContactTown()))) {
								errorMust.append("通信地址-省、市、区/县联动必填;");
							}
							if (Common.isNotNull(detail.getRelationProvince()) && (Common.isEmpty(detail.getRelationCity()) || Common.isEmpty(detail.getRelationTown()))) {
								errorMust.append("联系地址-省、市、区/县联动必填;");
							}
							if (Common.isNotNull(detail.getBankProvince()) && Common.isEmpty(detail.getBankCity())) {
								errorMust.append("开户省、市联动必填;");
							}
							// 手机号码
							if (Common.isNotNull(detail.getEmpPhone())) {
								mobileList.add(detail.getEmpPhone());
							}
							// 手机号码（紧急联系人）
							if (Common.isNotNull(detail.getTel())) {
								mobileList.add(detail.getTel());
							}
							// 1.9.7 手机号真实性校验加 ：手机号码（家庭成员）
							if (Common.isNotNull(detail.getContractTel())) {
								mobileList.add(detail.getContractTel());
							}

							// 1.9.7 新增必填校验
							// 1.9.7 工作经历必填校验
							if ("否".equals(detail.getIsFirstWork())) {
								if(Common.isEmpty(detail.getWorkUnit())|| Common.isEmpty(detail.getWorkJob())
										||Common.isEmpty(detail.getStartDate())||Common.isEmpty(detail.getEndDate())){
									errorMust.append("首份工作为【否】时，工作单位、工作岗位、开始工作日期、结束工作日期同时必填！");
								}
							}
							// 1.9.7家庭成员信息必填校验
							if (Common.isNotNull(detail.getFamilyName())) {
								if(Common.isEmpty(detail.getRelationshipSelf())|| Common.isEmpty(detail.getContractTel())){
									errorMust.append("有成员姓名时，家庭成员与本人关系、手机号码（家庭成员）同时必填！");
								}
							}
							// 1.9.7 职业资格信息必填校验
							if ("是".equals(detail.getHaveQualification())) {
								if(Common.isEmpty(detail.getDeclareYear()) || Common.isEmpty(detail.getQualificationType())){
									errorMust.append("是否有职业资格证书为【是】时，申报年度、职业资格名称同时必填！");
								}
							}
							// 1.9.7 伤残信息必填校验
							if (Common.isEmpty(detail.getInjuryIdentification()) && Common.isEmpty(detail.getOccupationalDiseaseFlag()) &&
									Common.isEmpty(detail.getInfectiousDiseaseFlag()) && Common.isEmpty(detail.getDisabilityFlag()) &&
									Common.isEmpty(detail.getOtherFlag())
							) {

							} else{
								if (Common.isNotNull(detail.getInjuryIdentification()) && Common.isNotNull(detail.getOccupationalDiseaseFlag()) &&
										Common.isNotNull(detail.getInfectiousDiseaseFlag()) && Common.isNotNull(detail.getDisabilityFlag()) &&
										Common.isNotNull(detail.getOtherFlag())
								) {
									if ("是".equals(detail.getOccupationalDiseaseFlag()) && Common.isEmpty(detail.getOccupationalDisease())) {
										errorMust.append("是否有职业病为【是】时，职业病名称必填！");
									}
									if ("是".equals(detail.getInfectiousDiseaseFlag()) && Common.isEmpty(detail.getInfectiousName())) {
										errorMust.append("是否有传染性疾病为【是】时，传染病名称必填！");
									}
									if ("是".equals(detail.getDisabilityFlag())) {
										if(Common.isEmpty(detail.getDisabilityLevel())|| Common.isEmpty(detail.getDisabilityName())){
											errorMust.append("是否被劳动能力鉴定委员会鉴定为具有伤残等级为【是】时，伤残病名称、伤残等级同时必填！");
										}
									}
								} else {
									errorMust.append("是否曾被认定为工伤，是否有职业病、是否有传染性疾病、是否被劳动能力鉴定委员会鉴定为具有伤残等级、是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种 必须同时必填！");
								}
							}

						} else if (saveEmp.getFileStatus() == CommonConstants.ONE_INT) {
							errorCur = errorCurInfoStatus;
						}
					} else {
						errorCur = errorCurInfo;
					}

					if (Common.isNotNull(errorCur)) {
						detail.setErrorInfo(errorCur);
						//empMap.put(detail.getEmpIdcard(), CommonConstants.ZERO_STRING)
					} else {
						StringBuilder errorInfo = new StringBuilder();
						if (errorCheck.length() > 0) {
							errorInfo.append("校验不通过：").append(errorCheck);
						}
						if (errorMust.length() > 0) {
							errorInfo.append("必填项未填写：").append(errorMust);
						}
						if (errorFormat.length() > 0) {
							errorInfo.append("格式不正确：").append(errorFormat);
						}
						detail.setErrorInfo(errorInfo.toString());
						//empMap.put(detail.getEmpIdcard(), CommonConstants.ZERO_STRING)
					}
				} else {
					detail.setErrorInfo("身份证号不存在！");
				}
				// 身份证起止有效期 都有值 且 截止日期正常
				if (Common.isNotNull(detail.getValidityStart())
						&& Common.isNotNull(detail.getValidityEnd())
						&& !"长期".equals(detail.getValidityEnd())
						&& DateUtil.checkStringToDate(detail.getValidityEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT)
						&& !DateUtil.stringToDate(detail.getValidityEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT)
						.after(DateUtil.stringToDate(detail.getValidityStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT))){
					detail.setErrorInfo(EmployeeConstants.EMP_VALIDITY_END_START_DATE);
				}

				excelList.add(detail);
			}

			// 先校验手机号是否已存在系统里
			Map<String, TEmployeeInfo> existPhoneMap = new HashMap<>();
			if (!phoneList.isEmpty()) {
				List<TEmployeeInfo> phones = baseMapper.getListByPhone(phoneList);
				for (TEmployeeInfo employeeInfo : phones) {
					existPhoneMap.put(employeeInfo.getEmpPhone(), employeeInfo);
				}
			}
			// 批量校验 卡号与手机号
			Map<String, Boolean> bankNoMap = new HashMap<>();
			Map<String, Boolean> phoneMap = new HashMap<>();
			if (!bankList.isEmpty()) {
				R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
						, "/tcheckbankno/inner/checkBankNoBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					bankNoMap = checkListR.getData().getCheckMap();
				}
			}
			if (!mobileList.isEmpty()) {
				R<CheckBatchVo> phoneR = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
						, "/tcheckmobile/inner/checkMobileBatch", mobileList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (phoneR != null && phoneR.getData() != null) {
					phoneMap = phoneR.getData().getCheckMap();
				}
			}
			Boolean resultB;
			// 要保存的list
			List<PreUploadEmpImportTwoVo> saveExcelList = new ArrayList<>();

			List<TEmployeeInfo> saveList = new ArrayList<>();

			// 返回的错误excel
			List<PreUploadEmpImportTwoVo> errorList = new ArrayList<>();
			// 用于查询预入职相关信息
			List<String> idCardList = new ArrayList<>();
			// 是否全部正确
			boolean allTrue = true;
			for (PreUploadEmpImportTwoVo info : excelList) {
				errorCheck = new StringBuilder();
				errorCur = info.getErrorInfo();
				if (Common.isEmpty(errorCur) || !(errorCur.contains(errorCurInfo) || errorCur.contains(errorCurInfoStatus))) {
					if (Common.isNotNull(info.getEmpName())) {
						if (Common.isNotNull(info.getBankNo())) {
							resultB = bankNoMap.get(info.getBankNo());
							if (resultB != null) {
								if (Boolean.FALSE.equals(resultB)) {
									errorCheck.append("姓名&银行卡号不一致;");
								}
							} else {
								errorCheck.append("姓名&银行卡号未校验;");
							}
						}
					}
					// 手机号码
					if (Common.isNotNull(info.getEmpPhone())) {
						checkPhoneInfo(errorCheck, existPhoneMap, phoneMap, info, info.getEmpPhone(), "手机号码");
					}
					// 手机号码（紧急联系人）
					if (Common.isNotNull(info.getTel())) {
						resultB = phoneMap.get(info.getTel());
						if (resultB != null) {
							if (Boolean.FALSE.equals(resultB)) {
								errorCheck.append("手机号码（紧急联系人）").append("校验不通过;");
							}
						} else {
							errorCheck.append("手机号码（紧急联系人）").append("未校验;");
						}
					}
					// 1.9.7： 手机号码（家庭成员）校验
					if (Common.isNotNull(info.getContractTel())) {
						resultB = phoneMap.get(info.getContractTel());
						if (resultB != null) {
							if (Boolean.FALSE.equals(resultB)) {
								errorCheck.append("手机号码（家庭成员）").append("校验不通过;");
							}
						} else {
							errorCheck.append("手机号码（家庭成员）").append("未校验;");
						}
					}
					if (errorCheck.length() > 0) {
						info.setErrorInfo(info.getErrorInfo() + "校验未通过：" + errorCheck);
						allTrue = false;
					} else if (Common.isEmpty(info.getErrorInfo())) {
						// 全部验证成功
						saveExcelList.add(info);
						idCardList.add(info.getEmpIdcard());
					} else {
						allTrue = false;
					}
				} else {
					allTrue = false;
				}
				errorList.add(info);
			}
			// 验证通过的，开始保存
			if (!saveExcelList.isEmpty()) {

				// 组装1 预入职 档案
				String empId;
				String empIdCard;
				Date endDate = DateUtil.stringToDate("2999-12-31", DateUtil.ISO_EXPANDED_DATE_FORMAT);

				// 原先的档案信息
				TEmployeeInfo oldEmp;
				// 新老档案vo
				EmployeeNewOldVO newOld;
				// 新老档案List
				List<EmployeeNewOldVO> updateList = new ArrayList<>();

				// 紧急联系人新增或更新
				List<TEmpContactInfo> saveContact = new ArrayList<>();
				TEmpContactInfo contact;
				// 1.9.6 加不良记录
				TEmpBadRecord badRecord;
				List<TEmpBadRecord> empBadRecordList = new ArrayList<>();
				// 1.9.7 加员工工作履历信息
				TEmpWorkRecording workRecord;
				List<TEmpWorkRecording> workRecordList = new ArrayList<>();
				// 1.9.7 加员工家庭信息
				TEmpFamily familyRecord;
				List<TEmpFamily> familyRecordList = new ArrayList<>();
				// 1.9.7 加职业资格信息信息
				TEmpProfessionalQualification qualificationRecord;
				List<TEmpProfessionalQualification> qualificationRecordList = new ArrayList<>();
				// 1.9.7 加职业资格信息信息
				TEmpDisabilityInfo disabilityRecord;
				List<TEmpDisabilityInfo> disabilityRecordList = new ArrayList<>();

				for (PreUploadEmpImportTwoVo excel : saveExcelList) {
					saveEmp = existEmpMap.get(excel.getEmpIdcard());
					if (saveEmp != null) {
						empId = saveEmp.getId();
						empIdCard = saveEmp.getEmpIdcard();

						// 可以更新
						oldEmp = new TEmployeeInfo();
						BeanUtil.copyProperties(saveEmp, oldEmp);

						if (Common.isNotNull(excel.getEmpPhone())) {
							saveEmp.setEmpPhone(excel.getEmpPhone());
						}
						if (Common.isNotNull(excel.getEmpMarriStatusValue())) {
							saveEmp.setEmpMarriStatus(excel.getEmpMarriStatusValue());
						}
						// 校验字典数据是否正确-民族
						if (Common.isNotNull(excel.getEmpNationalValue())) {
							saveEmp.setEmpNational(excel.getEmpNationalValue());
						}
						// 校验字典数据是否正确-政治面貌
						if (Common.isNotNull(excel.getPoliticalStatusValue())) {
							saveEmp.setPoliticalStatus(excel.getPoliticalStatusValue());
						}
						// 校验字典数据是否正确-户口性质
						if (Common.isNotNull(excel.getEmpRegisTypeValue())) {
							saveEmp.setEmpRegisType(excel.getEmpRegisTypeValue());
						}
						// 校验字典数据是否正确-最高学历
						if (Common.isNotNull(excel.getEducationNameValue())) {
							saveEmp.setHignEducation(excel.getEducationNameValue());
						}
						// 校验字典数据是否正确-员工类型
						if (Common.isNotNull(excel.getEmpNatrueValue())) {
							saveEmp.setEmpNatrue(excel.getEmpNatrueValue());
						}
						// 户籍所在地
						if (Common.isNotNull(excel.getIdProvinceValue())) {
							saveEmp.setIdProvince(Integer.parseInt(excel.getIdProvinceValue()));
						}
						if (Common.isNotNull(excel.getIdCityValue())) {
							saveEmp.setIdCity(Integer.parseInt(excel.getIdCityValue()));
						} else {
							saveEmp.setIdCity(null);
						}
						if (Common.isNotNull(excel.getIdTownValue())) {
							saveEmp.setIdTown(Integer.parseInt(excel.getIdTownValue()));
						} else {
							saveEmp.setIdTown(null);
						}
						if (Common.isNotNull(excel.getIsCollegeValue())) {
							saveEmp.setIsCollege(Integer.parseInt(excel.getIsCollegeValue()));
						}
						if (Common.isNotNull(excel.getValidityStartValue())) {
							saveEmp.setValidityStart(excel.getValidityStartValue());
						}
						if (Common.isNotNull(excel.getValidityEnd())) {
							if ("长期".equals(excel.getValidityEnd())) {
								saveEmp.setValidityEnd(endDate);
							} else {
								saveEmp.setValidityEnd(excel.getValidityEndValue());
							}
						}
						// 档案所在地
						if (Common.isNotNull(excel.getFileProvinceValue())) {
							saveEmp.setFileProvince(Integer.parseInt(excel.getFileProvinceValue()));
						}
						if (Common.isNotNull(excel.getFileCityValue())) {
							saveEmp.setFileCity(Integer.parseInt(excel.getFileCityValue()));
						}
						if (Common.isNotNull(excel.getFileTownValue())) {
							saveEmp.setFileTown(Integer.parseInt(excel.getFileTownValue()));
						}else {
							saveEmp.setFileTown(null);
						}
						// 邮箱
						if (Common.isNotNull(excel.getEmpEmail())) {
							saveEmp.setEmpEmail(excel.getEmpEmail());
						}
						if (Common.isNotNull(excel.getSchool())) {
							saveEmp.setSchool(excel.getSchool());
						}
						if (Common.isNotNull(excel.getMajor())) {
							saveEmp.setMajor(excel.getMajor());
						}
						// 通信地址所在地
						if (Common.isNotNull(excel.getContactProvinceValue())) {
							saveEmp.setContactProvince(excel.getContactProvinceValue());
						}
						if (Common.isNotNull(excel.getContactCityValue())) {
							saveEmp.setContactCity(excel.getContactCityValue());
						}
						if (Common.isNotNull(excel.getContactTownValue())) {
							saveEmp.setContactTown(excel.getContactTownValue());
						}
						if (Common.isNotNull(excel.getContactAddress())) {
							saveEmp.setContactAddress(excel.getContactAddress());
						}
						if (Common.isNotNull(excel.getRemark())) {
							saveEmp.setRemark(excel.getRemark());
						}
						if (Common.isNotNull(excel.getEntryDateValue())) {
							saveEmp.setAdmissionDate(excel.getEntryDateValue());
						}
						if (Common.isNotNull(excel.getGradutionDateValue())) {
							saveEmp.setGradutionDate(excel.getGradutionDateValue());
						}
						if (Common.isNotNull(excel.getBankNo())) {
							saveEmp.setBankNo(excel.getBankNo());
						}
						if (Common.isNotNull(excel.getBankName())) {
							saveEmp.setBankName(excel.getBankName());
						}
						if (Common.isNotNull(excel.getBankSubName())) {
							saveEmp.setBankSubName(excel.getBankSubName());
						}
						if (Common.isNotNull(excel.getBankProvinceValue())) {
							saveEmp.setBankProvince(excel.getBankProvinceValue());
						}
						if (Common.isNotNull(excel.getBankCityValue())) {
							saveEmp.setBankCity(excel.getBankCityValue());
						}
						if (Common.isNotNull(excel.getTaxMonthValue())) {
							saveEmp.setTaxMonth(excel.getTaxMonthValue());
						}
						// 1.9.6: 是否有职业资格证书
						if (Common.isNotNull(excel.getHaveQualification())) {
							String flag = CommonConstants.ZERO_STRING;
							if("否".equals(excel.getHaveQualification())){
								flag = CommonConstants.ONE_STRING;
							}
							saveEmp.setHaveQualification(flag);
						}
						// 1.9.7: 是否为首份工作
						if (Common.isNotNull(excel.getIsFirstWork())) {
							String workFlag = CommonConstants.ZERO_STRING;
							if("否".equals(excel.getIsFirstWork())){
								workFlag = CommonConstants.ONE_STRING;
							}
							saveEmp.setFirstWorkFlag(workFlag);
						}

						// 更新时，不需要更新其余信息
						newOld = new EmployeeNewOldVO();
						newOld.setNewEmployee(saveEmp);
						newOld.setOldEmployee(oldEmp);
						updateList.add(newOld);
						saveEmp.setUpdateBy(user.getId());
						saveEmp.setUpdateTime(LocalDateTime.now());
						saveList.add(saveEmp);

						if (Common.isNotNull(excel.getRelationProvinceValue())
								|| Common.isNotNull(excel.getAddress())
								|| Common.isNotNull(excel.getTel())
								|| Common.isNotNull(excel.getRelationType())
								|| Common.isNotNull(excel.getContactEmpName())) {
							contact = existContactMap.get(excel.getEmpIdcard());
							if (contact == null) {
								contact = new TEmpContactInfo();
							}
							contact.setEmpId(empId);
							contact.setEmpIdcard(empIdCard);
							if (Common.isNotNull(excel.getRelationProvinceValue())) {
								contact.setRelationProvince(excel.getRelationProvinceValue());
							}
							if (Common.isNotNull(excel.getRelationCityValue())) {
								contact.setRelationCity(excel.getRelationCityValue());
							}
							if (Common.isNotNull(excel.getRelationTownValue())) {
								contact.setRelationTown(excel.getRelationTownValue());
							}
							if (Common.isNotNull(excel.getAddress())) {
								contact.setAddress(excel.getAddress());
							}
							if (Common.isNotNull(excel.getTel())) {
								contact.setTel(excel.getTel());
							}
							if (Common.isNotNull(excel.getRelationType())) {
								contact.setRelationType(excel.getRelationType());
							}
							if (Common.isNotNull(excel.getContactEmpName())) {
								contact.setEmpName(excel.getContactEmpName());
							}
							saveContact.add(contact);
						}
						// 1.9.6 存不良记录
						if (Common.isNotNull(excel.getBadRecordFlag())
								&& ("是".equals(excel.getBadRecordFlag()) || "否".equals(excel.getBadRecordFlag()))
						) {
							String badFlag = CommonConstants.ZERO_STRING;
							if("否".equals(excel.getBadRecordFlag())){
								badFlag = CommonConstants.ONE_STRING;
							}
							badRecord = new TEmpBadRecord();
							badRecord.setBadRecordFlag(badFlag);
							badRecord.setEmpName(saveEmp.getEmpName());
							badRecord.setEmpId(saveEmp.getId());
							badRecord.setEmpIdcard(saveEmp.getEmpIdcard());
							badRecord.setCreateBy(user.getId());
							badRecord.setCreateName(user.getNickname());
							badRecord.setCreateTime(LocalDateTime.now());
							if("否".equals(excel.getBadRecordFlag())){
								badRecord.setRemark("未曾经或正在追究与承担过刑事责任");
							} else {
								badRecord.setRemark("曾经或正在追究与承担过刑事责任");
								badRecord.setProject(dept.getDepartName());
								badRecord.setProjectCode(dept.getDepartNo());
							}
							empBadRecordList.add(badRecord);
						}

						// 1.9.7 存主要工作经历
						if ("否".equals(excel.getIsFirstWork())) {
							workRecord = new TEmpWorkRecording();
							workRecord.setEmpName(saveEmp.getEmpName());
							workRecord.setEmpId(saveEmp.getId());
							workRecord.setEmpCode(saveEmp.getEmpCode());
							workRecord.setEmpIdcard(saveEmp.getEmpIdcard());
							workRecord.setWorkUnit(excel.getWorkUnit());
							workRecord.setWorkJob(excel.getWorkJob());
							// 存时间
							workRecord.setStartDate(excel.getStartDateValue());
							workRecord.setEndDate(excel.getEndDateValue());
							workRecord.setCreateBy(user.getId());
							workRecord.setCreateName(user.getNickname());
							workRecord.setCreateTime(LocalDateTime.now());
							workRecord.setWorkingStatus(CommonConstants.ONE_STRING);
							workRecord.setDeleteFlag(CommonConstants.NOT_DELETE_FLAG);

							workRecordList.add(workRecord);
						}
						// 1.9.7 存家庭成员
						if(Common.isNotNull(excel.getFamilyName())){
							familyRecord = new TEmpFamily();
							familyRecord.setEmpName(saveEmp.getEmpName());
							familyRecord.setEmpId(saveEmp.getId());
							familyRecord.setEmpCode(saveEmp.getEmpCode());
							familyRecord.setEmpIdcard(saveEmp.getEmpIdcard());
							familyRecord.setFamilyName(excel.getFamilyName());
							familyRecord.setRelationshipSelf(excel.getRelationshipSelfValue());
							familyRecord.setContractTel(excel.getContractTel());
							familyRecord.setCreateBy(user.getId());
							familyRecord.setCreateName(user.getNickname());
							familyRecord.setCreateTime(LocalDateTime.now());

							familyRecordList.add(familyRecord);
						}
						// 1.9.7 加职业资格信息信息
						if ("是".equals(excel.getHaveQualification())) {
							qualificationRecord = new TEmpProfessionalQualification();
							String qualificationFlag = CommonConstants.ZERO_STRING;
							qualificationRecord.setHaveQualification(qualificationFlag);
							qualificationRecord.setEmpName(saveEmp.getEmpName());
							qualificationRecord.setEmpId(saveEmp.getId());
							qualificationRecord.setEmpCode(saveEmp.getEmpCode());
							qualificationRecord.setEmpIdcard(saveEmp.getEmpIdcard());
							qualificationRecord.setDeclareYear(excel.getDeclareYear());
							qualificationRecord.setQualificationType(excel.getQualificationTypeValue());
							qualificationRecord.setDeleteFlag(CommonConstants.NOT_DELETE_FLAG);
							qualificationRecord.setCreateBy(user.getId());
							qualificationRecord.setCreateName(user.getNickname());
							qualificationRecord.setCreateTime(LocalDateTime.now());

							qualificationRecordList.add(qualificationRecord);
						}
						// 1.9.7 加伤残信息
						if (Common.isNotNull(excel.getInjuryIdentification()) && Common.isNotNull(excel.getOccupationalDiseaseFlag()) &&
								Common.isNotNull(excel.getInfectiousDiseaseFlag()) && Common.isNotNull(excel.getDisabilityFlag()) &&
								Common.isNotNull(excel.getOtherFlag())
						) {
							disabilityRecord = new TEmpDisabilityInfo();

							disabilityRecord.setInjuryIdentification(excel.getInjuryIdentificationValue());
							disabilityRecord.setOccupationalDiseaseFlag(excel.getOccupationalDiseaseFlagValue());
							if ("是".equals(excel.getOccupationalDiseaseFlag())) {
								disabilityRecord.setOccupationalDisease(excel.getOccupationalDisease());
							}
							disabilityRecord.setInfectiousDiseaseFlag(excel.getInfectiousDiseaseFlagValue());
							if ("是".equals(excel.getInfectiousDiseaseFlag())) {
								disabilityRecord.setInfectiousName(excel.getInfectiousName());
							}
							disabilityRecord.setDisabilityFlag(excel.getDisabilityFlagValue());
							if ("是".equals(excel.getDisabilityFlag())) {
								disabilityRecord.setDisabilityLevel(excel.getDisabilityLevelValue());
								disabilityRecord.setDisabilityName(excel.getDisabilityName());
							}
							disabilityRecord.setOtherFlag(excel.getOtherFlagValue());

							disabilityRecord.setEmpName(saveEmp.getEmpName());
							disabilityRecord.setEmpId(saveEmp.getId());
							disabilityRecord.setEmpCode(saveEmp.getEmpCode());
							disabilityRecord.setEmpIdcard(saveEmp.getEmpIdcard());
							disabilityRecord.setCreateBy(user.getId());
							disabilityRecord.setCreateName(user.getNickname());
							disabilityRecord.setCreateTime(LocalDateTime.now());
							disabilityRecord.setDeleteFlag(CommonConstants.NOT_DELETE_FLAG);

							disabilityRecordList.add(disabilityRecord);
						}
					}
				}

				// 紧急联系人信息
				if (!saveContact.isEmpty()) {
					tEmpContactInfoService.saveOrUpdateBatch(saveContact);
				}
				// 更新
				this.updateBatchById(saveList);

				// 更新学历-房
				this.saveOrUpdateEducation(saveList);

				// 1.9.6 加不良记录
				this.saveBadRecord(empBadRecordList);
				// 1.9.7 加主要工作经历
				this.saveWorkRecord(workRecordList);
				// 1.9.7 加家庭成员
				this.saveFamilyRecord(familyRecordList);
				// 1.9.7 加职业资格
				this.saveQualificationRecord(qualificationRecordList);
				// 1.9.7 加伤残信息
				this.saveDisabilityRecord(disabilityRecordList);

				// 记录变更日志
				for (EmployeeNewOldVO newOldInfo : updateList) {
					tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0]
							, newOldInfo.getOldEmployee().getId(), ""
							, newOldInfo.getOldEmployee(), newOldInfo.getNewEmployee());
				}
			}
			if (allTrue) {
				//数据保存
				return R.ok();
			} else {
				return new R<>(CommonConstants.TWO_INT, null, errorList);
			}
		} else {
			return R.failed("识别到表头下存在空白行，若非空白表，请删除空白行再导入！");
		}
	}

	private void checkPhoneInfo(StringBuilder errorCheck, Map<String, TEmployeeInfo> existPhoneMap
			, Map<String, Boolean> phoneMap, PreUploadEmpImportTwoVo info, String phone, String phoneName) {
		Boolean resultB;
		TEmployeeInfo existEmp = existPhoneMap.get(phone);
		// 手机号已存在
		if (existEmp != null) {
			// 非自己使用的
			if (!existEmp.getEmpIdcard().equals(info.getEmpIdcard())) {
				errorCheck.append(phoneName).append("已被其他身份证使用;");
			}
		} else {
			resultB = phoneMap.get(phone);
			if (resultB != null) {
				if (Boolean.FALSE.equals(resultB)) {
					errorCheck.append(phoneName).append("校验不通过;");
				}
			} else {
				errorCheck.append(phoneName).append("未校验;");
			}
		}
	}

	/**
	 * @param deptId 项目Id
	 * @Description: 更具项目找人
	 * @Author: hgw
	 * @Date: 2024/10/17 16:33
	 * @return: java.util.Map<java.lang.String, com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo>
	 **/
	private Map<String, TEmployeeInfo> getMapByDeptId(String deptId) {
		Map<String, TEmployeeInfo> preMap = new HashMap<>();
		if (Common.isNotNull(deptId)) {
			List<TEmployeeInfo> preList = baseMapper.getListByDeptId(deptId);
			if (preList != null && !preList.isEmpty()) {
				for (TEmployeeInfo pre : preList) {
					preMap.put(pre.getEmpIdcard(), pre);
				}
			}
		}
		return preMap;
	}

	@Override
	public List<TEmployeeInfo> getListByDeptIdByLimit(String deptId, Integer limit1, Integer limit2) {
		List<TEmployeeInfo> preList = baseMapper.getListByDeptIdByLimit(deptId, limit1,limit2);
		return preList;
	}

	private Map<String, TEmpContactInfo> getTEmpContactInfoMapByDeptId(String deptId) {
		Map<String, TEmpContactInfo> contactMap = new HashMap<>();
		if (Common.isNotNull(deptId)) {
			List<TEmpContactInfo> contactList = tEmpContactInfoService.getContactByDeptId(deptId);
			if (contactList != null && !contactList.isEmpty()) {
				for (TEmpContactInfo contact : contactList) {
					contactMap.put(contact.getEmpIdcard(), contact);
				}
			}
		}
		return contactMap;
	}

	// 1.9.6：加不良记录
	private void saveBadRecord(List<TEmpBadRecord> empBadRecordList) {
		if (empBadRecordList.size()>0) {
			tEmpBadRecordService.saveBatch(empBadRecordList);
		}
	}

	// 1.9.7：加工作经历
	private void saveWorkRecord(List<TEmpWorkRecording> workRecordList) {
		if (workRecordList.size()>0) {
			tEmpWorkRecordingService.saveBatch(workRecordList);
		}
	}
	// 1.9.7：加家庭成员
	private void saveFamilyRecord(List<TEmpFamily> familyRecordList) {
		if (familyRecordList.size()>0) {
			tEmpFamilyService.saveBatch(familyRecordList);
		}
	}
	// 1.9.7：加职业资格
	private void saveQualificationRecord(List<TEmpProfessionalQualification> qualificationRecordList) {
		if (qualificationRecordList.size()>0) {
			tEmpProfessionalQualificationService.saveBatch(qualificationRecordList);
		}
	}
	// 1.9.7：加伤残信息
	private void saveDisabilityRecord(List<TEmpDisabilityInfo> disabilityRecordList) {
		if (disabilityRecordList.size()>0) {
			tEmpDisabilityInfoService.saveBatch(disabilityRecordList);
		}
	}

	/**
	 * @param empPhoneOld 手机号-原先
	 * @param empPhoneNew 手机号-新
	 * @Description: 更新档案手机号-包括离职库
	 * @Author: hgw
	 * @Date: 2025-4-23 15:34:26
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> updateEmpPhone(String id, String empPhoneOld, String empPhoneNew) {
		if (empPhoneOld.equals(empPhoneNew)) {
			return R.failed("手机号未发生变化");
		}
		// 1：判断姓名、身份证是否存在
		// 2：如果不存在，返回提示语：无该员工信息
		// 3：如果存在，判断手机号old对不对，不对则返回提示语：旧手机号错误
		// 4：如果手机号old对，判断手机号new对不对，不对则返回提示语：新手机号校验不通过
		// 5：如果手机号new校验通过，判断手机号new是否已存在，存在则返回提示语：手机号已被其他身份证使用
		// 6：如果手机号new未被使用，则更新手机号，并返回提示语：更新成功
		TEmployeeInfo emp = this.getById(id);
		if (emp != null) {
			if (!emp.getEmpPhone().equals(empPhoneOld)) {
				return R.failed("旧手机号发生变化，请重新获取档案信息！");
			}
			TEmployeeInfo empExist = baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
					.eq(TEmployeeInfo::getEmpPhone, empPhoneNew).last(CommonConstants.LAST_ONE_SQL));
			if (empExist != null) {
				return R.failed("手机号已被使用");
			}
			TCheckMobile checkMobile = new TCheckMobile();
			checkMobile.setMobile(empPhoneNew);
			R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
					, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
			if (a != null && a.getData() != null) {
				checkMobile = a.getData();
				if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
					// 校验服务判断了1、4、5都返回为1，因此仅判断1即可
					if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
						return R.failed("手机号校验失败：" + checkMobile.getMessage());
					}
				} else {
					return R.failed(EmployeeConstants.CHECK_ERROR);
				}
			} else {
				return R.failed(EmployeeConstants.CHECK_ERROR);
			}
			// 可以更新：
			emp.setEmpPhone(empPhoneNew);
			baseMapper.updateById(emp);
			return R.ok("更新成功！");
		} else {
			return R.failed("无该人员信息，不可修改手机号！");
		}
	}

	@Override
	public R<TEmployeeInfo> getByEmpNameAndCard(String empName, String empIdCard) {
		TEmployeeInfo emp = baseMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, empIdCard).last(CommonConstants.LAST_ONE_SQL));
		if (emp != null) {
			if (empName.equals(emp.getEmpName())) {
				return new R<>(emp);
			} else {
				return R.failed("姓名与身份证不匹配！");
			}
		} else {
			return R.failed("无该人员信息，不可修改手机号");
		}
	}
	/**
	 * 远程接口获取非在职档案（无档案或已离职）
	 */
	@Override
	public Set<String> getEmpOnlineMap(List<String> empIdCardList) {
		if (empIdCardList == null || empIdCardList.isEmpty()) {
			return null; // 返回空
		}
		return baseMapper.getEmpOnlineMap(empIdCardList);
	}

}
