/*
 *    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.TCheckIdCard;
import com.yifu.cloud.plus.v1.check.entity.TCheckMobile;
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.TEmployeeContractAuditMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
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.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
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 lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

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

	// 缓存信息
	private final CacheManager cacheManager;
	private final TEmployeeProjectService tEmployeeProjectService;
	private final DaprCheckProperties daprCheckProperties;
	private final DaprUpmsProperties daprUpmsProperties;
	private final TEmployeeLogService tEmployeeLogService;
	private final TEmpEducationService tEmpEducationService;
	private final TSettleDomainService tSettleDomainService;

	private final TEmployeeContractAuditMapper contractAuditMapper;

	private final TEmployeeContractInfoService contractServicer;



	@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());
		}

		// 校验手机号：
		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);

		// 记录变更日志
		tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], old.getId(), "", old, employeeInfo);
		return R.ok(this.updateById(employeeInfo));
	}

	@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);
								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) {

			// 出生日期
			String idCardDate = idCard.substring(6, 14);
			Date empBirthday = DateUtil.stringToDateByPatten(idCardDate, "yyyyMMdd");
			employeeInfo.setEmpBirthday(empBirthday);

			// 性别
			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, EmployeeVO 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.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.getEmpRegisType())) {
				errorMsg.add(EmployeeConstants.EMP_REGIS_TYPE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.EMP_REGIS_TYPE));
			}
			if (Common.isEmpty(employeeInfo.getFileProvince())) {
				errorMsg.add(EmployeeConstants.FILE_PROVINCE);
				errorMsgMap.put(lineNum, new ErrorMessage(EmployeeConstants.FILE_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("就职岗位必填！"));
		}
	}

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

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

				@Override
				public void invoke(EmployeeVO 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<EmployeeVO> 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("第" + (i + 2) + "行身份证号与第" + idCardMap.get(idCard) + "行重复！");
					errorMsgMap.put((i + 2L), 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((i + 2L), 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);
			}
		}

		EmployeeVO 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());
						}
					}
					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())) {
					areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileProvince().trim());
					if (Common.isEmpty(areaStr)) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setFileProvince(Integer.parseInt(areaStr));
					}
				}
				if (Common.isNotNull(excel.getFileCity())) {
					areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileCity().trim() + CommonConstants.DOWN_LINE_STRING + excel.getFileProvince().trim());
					if (Common.isEmpty(areaStr)) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setFileCity(Integer.parseInt(areaStr));
					}
				}
				if (Common.isNotNull(excel.getFileTown())) {
					areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileTown().trim() + CommonConstants.DOWN_LINE_STRING + excel.getFileCity().trim());
					if (Common.isEmpty(areaStr)) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
					} else {
						saveEmp.setFileTown(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);
					}
				}
				saveEmp.setValidityStart(excel.getValidityStart());
				saveEmp.setValidityEnd(excel.getValidityEnd());
				// 邮箱
				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.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
	 **/
	private 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)
	private 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) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeVO> util1 = new ExcelUtil<>(EmployeeVO.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

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

				@Override
				public void invoke(EmployeeVO 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);
					}
					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<EmployeeVO> excelVOList, List<ErrorMessage> errorMessageList) {
		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);
		}
		// 通用校验获取失败的数据
		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);
			}
		}

		// 个性化校验逻辑
		EmployeeVO 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++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get((i + 2L)))) {
				continue;
			}
			errorMsg = new HashSet<>();
			excel = excelVOList.get(i);
			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.getFileProvince())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileProvince().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setFileProvince(Integer.parseInt(areaStr));
						}
					}
					if (Common.isNotNull(excel.getFileCity())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileCity().trim() + CommonConstants.DOWN_LINE_STRING + excel.getFileProvince().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setFileCity(Integer.parseInt(areaStr));
						}
					}
					if (Common.isNotNull(excel.getFileTown())) {
						areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getFileTown().trim() + CommonConstants.DOWN_LINE_STRING + excel.getFileCity().trim());
						if (Common.isEmpty(areaStr)) {
							errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR, excel.getEmpIdcard()));
						} else {
							saveEmp.setFileTown(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())) {
						saveEmp.setValidityEnd(excel.getValidityEnd());
					}
					// 邮箱
					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.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.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((i + 2L), 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.getEmpRegisType())) {
				errorMsg.add(EmployeeConstants.EMP_REGIS_TYPE);
			}
			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();
		// 新增档案
		saveEmp(empAddsMap);
		// 新增项目档案不需要返回ID
		saveProject(empAddsMap, projectsMap);
		// 新增合同
		saveContract(projectsMap, contractsMap,empAddsMap);
		addVo.setProjectsMap(projectsMap);
		addVo.setEmpAddsMap(empAddsMap);
		addVo.setContractsMap(contractsMap);
		return addVo;
	}

	/**
	 * @Author fxj
	 * @Description  派单审核通过 同步人员档案 项目档案 合同状态信息
	 * @Date 19:30 2022/8/1
	 * @Param
	 * @return
	**/
	@Override
	public Boolean updateEmpInfo(UpdateEmpVo vo) {
		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())
							.eq(TEmployeeInfo::getStatus,CommonConstants.ZERO_INT)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(employeeInfo)){
						employeeInfo.setStatus(CommonConstants.ONE_INT);
						baseMapper.updateById(employeeInfo);
					}

					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);
							tEmployeeProjectService.updateById(p);
						}
					}
				}
				if (Common.isNotNull(vo.getContractId())){
					TEmployeeContractInfo c = contractServicer.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_INT)
							.eq(TEmployeeContractInfo::getId,vo.getContractId())
							.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(c.getCreateBy());
						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());
							tEmployeeProjectService.updateContractStatus(c.getEmpId(),CommonConstants.ONE_INT);
							baseMapper.updateContractStatus(c.getEmpId(),CommonConstants.ONE_INT);
							//审核不同
						}else if (CommonConstants.ONE_STRING.equals(vo.getType())){
							c.setAuditStatus(CommonConstants.THREE_INT);
							c.setInUse(CommonConstants.ONE_STRING);
							contractAudit.setAuditStatus("审核不通过");
							contractAudit.setRemark(vo.getRemarkTemp());
							contractAudit.setRootName("合同审核");
						}
						contractAuditMapper.insert(contractAudit);
						contractServicer.updateById(c);
					}

				}
			}
		}
		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));
	}

	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);
						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;
			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.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();
				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);
						projectAdd.setId(project.getId());
						projectAdd.setEmpNo(project.getEmpNo());
						projectsMap.put(project.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + project.getDeptNo(), projectAdd);
					}
				} catch (Exception e) {
					log.error(projectAdd.getEmpIdcard() + CommonConstants.COLON_STRING + "派单新增项目档案失败",e);
				}
			}
		}
	}

	/**
	 * @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);
	}
}
