/*
 *    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.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.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.TEmpEducation;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
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.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi;
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;

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

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

	@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 {
				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薪酬)");
		}
		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())) {
			// 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<>();
		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)
					.eq(TSettleDomain::getStopFlag, 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 {
				// 档案不存在
				// 校验身份证实名
				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("area_" + 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("area_" + excel.getIdCity() + 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("area_" + excel.getIdTown() + 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("area_" + 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("area_" + excel.getFileCity() + 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("area_" + excel.getFileTown() + 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
	 **/
	private synchronized 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("area_" + 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("area_" + excel.getIdCity() + 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("area_" + excel.getIdTown() + 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("area_" + 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("area_" + excel.getFileCity() + 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("area_" + excel.getFileTown() + 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()))) {
			// 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(TEmployeeInfo employeeInfo, HttpServletResponse response) {
		if (employeeInfo != null && employeeInfo.getExportFields() != null && !employeeInfo.getExportFields().isEmpty()) {
			String fileName = "人员档案批量导出" + DateUtil.getThisTime() + ".xlsx";
			//获取要导出的列表
			employeeInfo.setFileStatus(CommonConstants.ZERO_INT);
			List<EmployeeExportVO> list = baseMapper.getTEmployeeExportList(employeeInfo);
			ServletOutputStream out = null;
			if (list == null || list.isEmpty()) {
				list = new ArrayList<>();
			}
			try {
				ExcelUtil<EmployeeExportVO> util = new ExcelUtil<>(EmployeeExportVO.class);
				for (EmployeeExportVO vo : list) {
					util.convertEntity(vo, null, null, null);
				}
				out = response.getOutputStream();
				response.setContentType("multipart/form-data");
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, CommonConstants.UTF8));
				// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
				EasyExcel.write(out, EmployeeExportVO.class).includeColumnFiledNames(employeeInfo.getExportFields())
						.sheet("人员档案").doWrite(list);
				out.flush();
			} catch (Exception e) {
				log.error(EmployeeConstants.FILE_EXPORT_EXCEPTION, e);
			} finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					log.error(EmployeeConstants.FILE_EXPORT_EXCEPTION, e);
				}
			}
		}
	}

	/**
	 * 获取导出的离职档案列表
	 */
	@Override
	public void exportLeaveEmployee(TEmployeeInfo employeeInfo, HttpServletResponse response) {
		if (employeeInfo != null && employeeInfo.getExportFields() != null && !employeeInfo.getExportFields().isEmpty()) {
			String fileName = "离职档案批量导出" + DateUtil.getThisTime() + ".xlsx";
			//获取要导出的列表
			employeeInfo.setFileStatus(CommonConstants.ONE_INT);
			List<EmployeeExportVO> list = baseMapper.getTEmployeeLeaveExportList(employeeInfo);
			ServletOutputStream out = null;
			if (list == null || list.isEmpty()) {
				list = new ArrayList<>();
			}
			try {
				ExcelUtil<EmployeeExportVO> util = new ExcelUtil<>(EmployeeExportVO.class);
				for (EmployeeExportVO vo : list) {
					util.convertEntity(vo, null, null, null);
				}
				out = response.getOutputStream();
				response.setContentType("multipart/form-data");
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
				EasyExcel.write(out, EmployeeExportVO.class).includeColumnFiledNames(employeeInfo.getExportFields())
						.sheet("离职档案").doWrite(list);
				out.flush();
			} catch (Exception e) {
				log.error(EmployeeConstants.FILE_EXPORT_EXCEPTION, e);
			} finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					log.error(EmployeeConstants.FILE_EXPORT_EXCEPTION, e);
				}
			}
		}
	}

}
