/*
 *    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.util.ArrayUtil;
import com.alibaba.excel.EasyExcelFactory;
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.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.yifu.cloud.plus.v1.check.entity.TCheckBankNo;
import com.yifu.cloud.plus.v1.check.entity.TCheckIdCard;
import com.yifu.cloud.plus.v1.check.vo.CheckBatchVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AreaMap;
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.TArchivesExportLimitMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TArchivesLimitMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TPreEmpMainMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.utils.ExcelStyle;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.AliSmsResult;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.SmsUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.ExcelColumnVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.ExcelSheetVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSalaryProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryEmployee;
import com.yifu.cloud.plus.v1.yifu.salary.vo.ExportErrorVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.ListStringVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TBankNameMapVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryEmpMapVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.Lists;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 预入职-主表
 *
 * @author hgw
 * @date 2024-06-17 11:31:08
 */
@Log4j2
@AllArgsConstructor
@Service
@EnableConfigurationProperties({DaprSalaryProperties.class, DaprCheckProperties.class, DaprUpmsProperties.class})
public class TPreEmpMainServiceImpl extends ServiceImpl<TPreEmpMainMapper, TPreEmpMain> implements TPreEmpMainService {
	// 预入职-员工不良记录表
	private final TPreEmpBadRecordService tPreEmpBadRecordService;
	// 预入职-员工工作履历信息表
	private final TPreEmpWorkRecordingService tPreEmpWorkRecordingService;
	// 预入职-紧急联络人
	private final TPreEmpContactInfoService tPreEmpContactInfoService;
	// 预入职-员工声明
	private final TPreEmpDeclarationService tPreEmpDeclarationService;
	// 预入职-员工伤残信息表
	private final TPreEmpDisabilityInfoService tPreEmpDisabilityInfoService;
	// 预入职-员工学历信息表
	private final TPreEmpEducationService tPreEmpEducationService;
	// 预入职-员工家庭信息表
	private final TPreEmpFamilyService tPreEmpFamilyService;
	// 预入职-人员档案表
	private final TPreEmployeeInfoService tPreEmployeeInfoService;
	// 预入职-项目档案表
	private final TPreEmployeeProjectService tPreEmployeeProjectService;
	// 预入职-员工职业资格信息表
	private final TPreEmpProfessionalQualificationService tPreEmpProfessionalService;
	// 预入职-其他附件
	private final TPreEmpOtherFileService tPreEmpOtherFileService;

	// 附件21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)
	private final TAttaInfoService tAttaInfoService;

	// 档案相关服务：
	// 预入职-员工不良记录表
	private final TEmpBadRecordService tEmpBadRecordService;
	// 预入职-员工工作履历信息表
	private final TEmpWorkRecordingService tEmpWorkRecordingService;
	// 预入职-紧急联络人
	private final TEmpContactInfoService tEmpContactInfoService;
	// 预入职-员工伤残信息表
	private final TEmpDisabilityInfoService tEmpDisabilityInfoService;
	// 预入职-员工学历信息表
	private final TEmpEducationService tEmpEducationService;
	// 预入职-员工家庭信息表
	private final TEmpFamilyService tEmpFamilyService;
	// 预入职-人员档案表
	private final TEmployeeInfoService tEmployeeInfoService;
	// 预入职-项目档案表
	private final TEmployeeProjectService tEmployeeProjectService;
	// 预入职-员工职业资格信息表
	private final TEmpProfessionalQualificationService tEmpProfessionalService;
	// 项目
	private final TSettleDomainService tSettleDomainService;
	// 审核日志
	private final TPreEmpMainLogService tPreEmpMainLogService;
	// 其他附件
	private final TEmpOtherFileService tEmpOtherFileService;

	// 薪资服务，获取计税月份
	private final DaprSalaryProperties salaryProperties;
	// 导入批量校验身份证、卡号、手机号
	private final DaprCheckProperties checkProperties;
	private final DaprUpmsProperties daprUpmsProperties;

	private final TArchivesExportLimitMapper tArchivesExportLimitMapper;

	private final TArchivesLimitMapper tArchivesLimitMapper;

	private final EmployeeRegistrationPreService registrationPreService;

	private final OSSUtil ossUtil;

	private static final String ID = "id";

	public static final String TAX_MONTH_REGEX = "^2\\d{5}";

	private final RedisUtil redisUtil;

	private final AtomicInteger preImportAtomicInteger = new AtomicInteger(0);
	private final AtomicInteger preExportAtomicInteger = new AtomicInteger(0);

	private final AtomicInteger zipAtomicInteger = new AtomicInteger(0);

	/**
	 * 预入职-主表简单分页查询
	 *
	 * @param tPreEmpMain 预入职-主表
	 * @return
	 */
	@Override
	public IPage<TPreEmpMain> getTPreEmpMainPage(Page<TPreEmpMain> page, TPreEmpMainSearchVo tPreEmpMain) {
		return baseMapper.getTPreEmpMainPage(page, tPreEmpMain);
	}

	/**
	 * @Description: 详情
	 * @Author: hgw
	 * @Date: 2024/6/17 17:19
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.vo.PreEmpMainDetailVo>
	 **/
	@Override
	public R<PreEmpMainDetailVo> getByCardAndDeptId(String empIdCard, String deptId) {
		TSettleDomain dept = tSettleDomainService.getById(deptId);
		if (dept == null) {
			return R.failed("未找到项目信息！");
		}
		TSalaryEmployee tSalaryEmployee = null;
		R<TSalaryEmployee> sdr = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl(), salaryProperties.getAppId()
				, "/tsalaryemployee/inner/getSalaryEmployee", empIdCard, TSalaryEmployee.class, SecurityConstants.FROM_IN);
		if (sdr != null && sdr.getData() != null) {
			tSalaryEmployee = sdr.getData();
		}
		TPreEmpMain main = baseMapper.getTPreEmpMainByCardAndDept(empIdCard, deptId);
		// 类型1详档2简档
		String isSimple = registrationPreService.judgeIsSimple(empIdCard, deptId);
		TPreEmpDeclaration declaration;
		// 是否为详档，true 是，否则不创建多余的附属信息
		boolean isDetailBoo = true;
		// 详变简，再清空预入职信息
		boolean isDetailToSimple = false;
		if (CommonConstants.TWO_STRING.equals(isSimple)) {
			isDetailBoo = false;
			if (main == null || Common.isEmpty(main.getIsSimple()) || CommonConstants.ONE_STRING.equals(main.getIsSimple())) {
				isDetailToSimple = true;
			}
			declaration = tPreEmpDeclarationService.getById(CommonConstants.TWO_STRING);
		} else {
			declaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
		}
		if (declaration == null) {
			return R.failed("请联系管理员添加员工声明信息！");
		}

		TEmployeeInfo employee = tEmployeeInfoService.getInfoByIdcard(empIdCard);
		String empId = null;
		TEmployeeProject project = tEmployeeProjectService.getByEmpIdCardAndDeptId(empIdCard, deptId);
		PreEmpMainDetailVo vo = new PreEmpMainDetailVo();
		YifuUser user = getNewYifuUser();
		if (main != null) {
			// 清空信息
			if (CommonConstants.FIVE_STRING.equals(main.getStatus())) {
				if (Common.isNotNull(main.getId())) {
					baseMapper.deleteBadByMainId(main.getId());
					baseMapper.deleteContactByMainId(main.getId());
					baseMapper.deleteDisabilityByMainId(main.getId());
					baseMapper.deleteEducationByMainId(main.getId());
					baseMapper.deleteFamilyByMainId(main.getId());
					baseMapper.deleteEmployeeByMainId(main.getId());
					baseMapper.deleteProjectByMainId(main.getId());
					tPreEmpWorkRecordingService.deleteByMainId(main.getId());
					tPreEmpProfessionalService.deleteProfessionalByMainId(main.getId());
					tPreEmpOtherFileService.deleteOtherFileByMainId(main.getId());
					tAttaInfoService.deleteByDomainId(main.getId());
				}
				baseMapper.deleteById(main);
				main = null;
			}
			// 1.7.8 2025-3-21 16:58:56 详档变简档，清空部分信息
			if (main != null && isDetailToSimple) {
				TPreEmployeeInfo emp = tPreEmployeeInfoService.getTPreEmployeeInfoList(main.getId());
				// 先删除档案，然后保留部分信息（项目档案不用，因为都是项目信息等）
				baseMapper.deleteEmployeeByMainId(main.getId());
				TPreEmployeeInfo newEmp = new TPreEmployeeInfo();
				newEmp.setOldId(emp.getOldId());
				newEmp.setPreMainId(main.getId());
				newEmp.setEmpName(emp.getEmpName());
				newEmp.setEmpIdcard(emp.getEmpIdcard());
				newEmp.setEmpPhone(emp.getEmpPhone());
				newEmp.setContactAddress(emp.getContactAddress());
				newEmp.setContactProvince(emp.getContactProvince());
				newEmp.setContactCity(emp.getContactCity());
				newEmp.setContactTown(emp.getContactTown());
				this.setBaseSexInfo(newEmp);
				newEmp.setBankProvince(emp.getBankProvince());
				newEmp.setBankCity(emp.getBankCity());
				newEmp.setBankName(emp.getBankName());
				newEmp.setBankSubName(emp.getBankSubName());
				newEmp.setBankNo(emp.getBankNo());
				newEmp.setCreateBy(user.getId());
				newEmp.setCreateName(user.getNickname());
				newEmp.setCreateTime(LocalDateTime.now());
				tPreEmployeeInfoService.save(newEmp);
				vo.setTpreEmployeeInfo(newEmp);
				// 全部保留
				// baseMapper.deleteContactByMainId(main.getId())
				// tPreEmpOtherFileService.deleteOtherFileByMainId(main.getId())
				// 删除
				baseMapper.deleteBadByMainId(main.getId());
				baseMapper.deleteDisabilityByMainId(main.getId());
				baseMapper.deleteEducationByMainId(main.getId());
				baseMapper.deleteFamilyByMainId(main.getId());
				tPreEmpWorkRecordingService.deleteByMainId(main.getId());
				tPreEmpProfessionalService.deleteProfessionalByMainId(main.getId());
				// 删除附件，保留身份证、其他附件、签名
				tAttaInfoService.deleteByDomainIdExceptionCard(main.getId());
			}
		}
		// 审核通过并且有在项，取在项
		boolean empFirst = false;
		if ((main == null || (main != null && CommonConstants.FOUR_STRING.equals(main.getStatus()))) && employee != null && project != null) {
			empFirst = true;
		}
		if (main != null) {
			vo.setTpreEmpDeclaration(declaration);
			main.setDeclarationId(declaration.getId());
			main.setIsSimple(isSimple);
			this.updateById(main);
			// 2024-7-3 17:23:50 倩倩要求放开状态拦截，前端加按钮禁用即可
			/* (CommonConstants.ONE_STRING.equals(main.getStatus())
					|| CommonConstants.TWO_STRING.equals(main.getStatus()))
				retur R.failed("信息审核中，请耐心等待！")

			 (CommonConstants.FOUR_STRING.equals(main.getStatus()))
				retur R.failed("信息已填写，请勿重复操作！")
			*/
			TPreEmployeeInfo tPreEmployeeInfo = tPreEmployeeInfoService.getTPreEmployeeInfoList(main.getId());
			if (tPreEmployeeInfo != null && Common.isNotNull(tPreEmployeeInfo.getId())) {
				empId = tPreEmployeeInfo.getId();

				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					empId = employee.getId();
					tPreEmployeeInfo = new TPreEmployeeInfo();
					BeanUtil.copyProperties(employee, tPreEmployeeInfo, ID);
					// MVP1.9.1新逻辑：在项信息存在，则去薪资人员里的银行等信息
					setNewSalaryEmpBankInfo(tSalaryEmployee, tPreEmployeeInfo);
					tPreEmployeeInfo.setOldId(employee.getId());
				}
				if (employee == null) {
					tPreEmployeeInfo.setOldId(null);
				}
				vo.setTpreEmployeeInfo(tPreEmployeeInfo);
			} else {
				tPreEmployeeInfo = new TPreEmployeeInfo();
				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					empId = employee.getId();
					BeanUtil.copyProperties(employee, tPreEmployeeInfo, ID);
					// MVP1.9.1新逻辑：在项信息存在，则去薪资人员里的银行等信息
					setNewSalaryEmpBankInfo(tSalaryEmployee, tPreEmployeeInfo);
					tPreEmployeeInfo.setOldId(employee.getId());
				}
				tPreEmployeeInfo.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeInfo.setEmpName(main.getEmpName());
				tPreEmployeeInfo.setPreMainId(main.getId());
				tPreEmployeeInfo.setCreateBy(user.getId());
				tPreEmployeeInfo.setCreateName(user.getNickname());
				tPreEmployeeInfo.setCreateTime(LocalDateTime.now());
				tPreEmployeeInfoService.save(tPreEmployeeInfo);
				vo.setTpreEmployeeInfo(tPreEmployeeInfo);
			}
			TPreEmployeeProject tPreEmployeeProject = tPreEmployeeProjectService.getTPreEmployeeProjectList(main.getId());
			// 预入职-项目档案表
			if (tPreEmployeeProject != null) {
				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					tPreEmployeeProject = new TPreEmployeeProject();
					BeanUtil.copyProperties(project, tPreEmployeeProject, ID);
					tPreEmployeeProject.setOldId(project.getId());
				}
				if (project == null) {
					tPreEmployeeProject.setOldId(null);
				}
				vo.setTpreEmployeeProject(tPreEmployeeProject);
			} else {
				tPreEmployeeProject = new TPreEmployeeProject();
				tPreEmployeeProject.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeProject.setEmpName(main.getEmpName());
				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					BeanUtil.copyProperties(project, tPreEmployeeProject, ID);
					tPreEmployeeProject.setOldId(project.getId());
				}
				tPreEmployeeProject.setUnitId(dept.getCustomerId());
				tPreEmployeeProject.setUnitName(dept.getCustomerName());
				tPreEmployeeProject.setUnitNo(dept.getCustomerNo());
				tPreEmployeeProject.setBusinessPrimaryType(dept.getBusinessPrimaryType());
				tPreEmployeeProject.setBusinessSecondType(dept.getBusinessSecondType());
				tPreEmployeeProject.setBusinessThirdType(dept.getBusinessThirdType());
				tPreEmployeeProject.setDeptId(main.getDeptId());
				tPreEmployeeProject.setDeptName(main.getDeptName());
				tPreEmployeeProject.setDeptNo(main.getDeptNo());
				tPreEmployeeProject.setPreMainId(main.getId());
				tPreEmployeeProject.setCreateBy(user.getId());
				tPreEmployeeProject.setCreateName(user.getNickname());
				tPreEmployeeProject.setCreateTime(LocalDateTime.now());
				tPreEmployeeProjectService.save(tPreEmployeeProject);
				vo.setTpreEmployeeProject(tPreEmployeeProject);
			}
		} else {
			main = new TPreEmpMain();
			main.setEmpIdcard(empIdCard);
			main.setDeptId(dept.getId());
			main.setDeptName(dept.getDepartName());
			main.setDeptNo(dept.getDepartNo());
			main.setUnitId(dept.getCustomerId());
			main.setUnitName(dept.getCustomerName());
			main.setUnitNo(dept.getCustomerNo());
			main.setBusinessPrimaryType(dept.getBusinessPrimaryType());
			main.setBusinessSecondType(dept.getBusinessSecondType());
			main.setBusinessThirdType(dept.getBusinessThirdType());
			main.setStatus(CommonConstants.FIVE_STRING);
			// 预入职-员工声明
			vo.setTpreEmpDeclaration(declaration);
			main.setDeclarationId(declaration.getId());
			main.setIsSimple(isSimple);
			this.save(main);

			TPreEmployeeInfo tPreEmployeeInfo;
			TPreEmployeeProject tPreEmployeeProject;
			if (employee != null) {
				empId = employee.getId();
				tPreEmployeeInfo = new TPreEmployeeInfo();
				BeanUtil.copyProperties(employee, tPreEmployeeInfo, ID);
				tPreEmployeeInfo.setOldId(employee.getId());
				tPreEmployeeInfo.setPreMainId(main.getId());
				tPreEmployeeInfo.setCreateBy(user.getId());
				tPreEmployeeInfo.setCreateName(user.getNickname());
				tPreEmployeeInfo.setCreateTime(LocalDateTime.now());
				tPreEmployeeInfoService.saveOrUpdate(tPreEmployeeInfo);
				vo.setTpreEmployeeInfo(tPreEmployeeInfo);

				if (project != null) {
					tPreEmployeeProject = new TPreEmployeeProject();
					BeanUtil.copyProperties(project, tPreEmployeeProject, ID);
					tPreEmployeeProject.setOldId(project.getId());
					tPreEmployeeProject.setPreMainId(main.getId());
					tPreEmployeeProject.setCreateBy(user.getId());
					tPreEmployeeProject.setCreateName(user.getNickname());
					tPreEmployeeProject.setCreateTime(LocalDateTime.now());
					tPreEmployeeProjectService.saveOrUpdate(tPreEmployeeProject);
					vo.setTpreEmployeeProject(tPreEmployeeProject);

					// MVP1.9.1新逻辑：在项信息存在，则去薪资人员里的银行等信息
					setNewSalaryEmpBankInfo(tSalaryEmployee, tPreEmployeeInfo);
					tPreEmployeeInfoService.updateById(tPreEmployeeInfo);
				}
			} else {
				tPreEmployeeInfo = new TPreEmployeeInfo();
				tPreEmployeeInfo.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeInfo.setPreMainId(main.getId());
				tPreEmployeeInfo.setCreateBy(user.getId());
				tPreEmployeeInfo.setCreateName(user.getNickname());
				tPreEmployeeInfo.setCreateTime(LocalDateTime.now());
				tPreEmployeeInfoService.save(tPreEmployeeInfo);
				vo.setTpreEmployeeInfo(tPreEmployeeInfo);
				tPreEmployeeProject = new TPreEmployeeProject();
				tPreEmployeeProject.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeProject.setUnitId(dept.getCustomerId());
				tPreEmployeeProject.setUnitName(dept.getCustomerName());
				tPreEmployeeProject.setUnitNo(dept.getCustomerNo());
				tPreEmployeeProject.setBusinessPrimaryType(dept.getBusinessPrimaryType());
				tPreEmployeeProject.setBusinessSecondType(dept.getBusinessSecondType());
				tPreEmployeeProject.setBusinessThirdType(dept.getBusinessThirdType());
				tPreEmployeeProject.setDeptId(main.getDeptId());
				tPreEmployeeProject.setDeptName(main.getDeptName());
				tPreEmployeeProject.setDeptNo(main.getDeptNo());
				tPreEmployeeProject.setPreMainId(main.getId());
				tPreEmployeeProject.setCreateBy(user.getId());
				tPreEmployeeProject.setCreateName(user.getNickname());
				tPreEmployeeProject.setCreateTime(LocalDateTime.now());
				tPreEmployeeProjectService.save(tPreEmployeeProject);
				vo.setTpreEmployeeProject(tPreEmployeeProject);
			}
		}
		String id = main.getId();
		vo.setMain(main);
		if (vo.getTpreEmpDeclaration() == null) {
			vo.setTpreEmpDeclaration(declaration);
		}

		// 预入职-紧急联络人
		TPreEmpContactInfo tPreEmpContactInfo = tPreEmpContactInfoService.getTPreEmpContactInfoList(id);
		if (tPreEmpContactInfo == null || empFirst) {
			String preId = null;
			if (tPreEmpContactInfo != null) {
				preId = tPreEmpContactInfo.getId();
			}
			tPreEmpContactInfo = new TPreEmpContactInfo();
			tPreEmpContactInfo.setId(preId);
			if (Common.isNotNull(empId)) {
				TEmpContactInfo info = tEmpContactInfoService.getByEmpId(empId);
				if (info != null) {
					BeanUtil.copyProperties(info, tPreEmpContactInfo, ID);
					if (Common.isEmpty(preId) && !empFirst) {
						tPreEmpContactInfo.setId(info.getId());
					}
					tPreEmpContactInfo.setEmpId(empId);
					tPreEmpContactInfo.setOldId(info.getId());
				}
			}
			tPreEmpContactInfo.setPreMainId(id);
			tPreEmpContactInfo.setCreateBy(user.getId());
			tPreEmpContactInfo.setCreateName(user.getNickname());
			tPreEmpContactInfo.setCreateTime(LocalDateTime.now());
			if (Common.isEmpty(tPreEmpContactInfo.getId())) {
				tPreEmpContactInfoService.save(tPreEmpContactInfo);
			}
		}
		vo.setTpreEmpContactInfo(tPreEmpContactInfo);

		// 预入职-人员档案表
		TPreEmployeeInfo tPreEmployeeInfo;
		if (vo.getTpreEmployeeInfo() == null) {
			tPreEmployeeInfo = tPreEmployeeInfoService.getTPreEmployeeInfoList(id);
			if (tPreEmployeeInfo == null) {
				tPreEmployeeInfo = new TPreEmployeeInfo();
				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					BeanUtil.copyProperties(employee, tPreEmployeeInfo, ID);
					tPreEmployeeInfo.setOldId(project.getId());
				}
				tPreEmployeeInfo.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeInfo.setPreMainId(main.getId());
				tPreEmployeeInfo.setCreateBy(user.getId());
				tPreEmployeeInfo.setCreateName(user.getNickname());
				tPreEmployeeInfo.setCreateTime(LocalDateTime.now());
				tPreEmployeeInfoService.save(tPreEmployeeInfo);
			}
			vo.setTpreEmployeeInfo(tPreEmployeeInfo);
		}
		tPreEmployeeInfo = vo.getTpreEmployeeInfo();
		// 去薪资服务获取卡号
		if (tPreEmployeeInfo != null && Common.isEmpty(tPreEmployeeInfo.getBankNo())
				&& tSalaryEmployee != null && Common.isNotNull(tSalaryEmployee.getBankNo())) {
			tPreEmployeeInfo.setBankNo(tSalaryEmployee.getBankNo());
			tPreEmployeeInfo.setBankName(tSalaryEmployee.getBankName());
			tPreEmployeeInfo.setBankSubName(tSalaryEmployee.getBankSubName());
			tPreEmployeeInfo.setBankProvince(tSalaryEmployee.getBankProvince());
			tPreEmployeeInfo.setBankCity(tSalaryEmployee.getBankCity());
		}
		// 预入职-项目档案表
		if (vo.getTpreEmployeeProject() == null) {
			TPreEmployeeProject tPreEmployeeProject = tPreEmployeeProjectService.getTPreEmployeeProjectList(id);
			if (tPreEmployeeProject == null) {
				tPreEmployeeProject = new TPreEmployeeProject();
				// 预入职已审核+在项，取在项信息
				if (empFirst) {
					BeanUtil.copyProperties(project, tPreEmployeeProject, ID);
					tPreEmployeeProject.setOldId(project.getId());
				}
				tPreEmployeeProject.setEmpIdcard(main.getEmpIdcard());
				tPreEmployeeProject.setUnitId(dept.getCustomerId());
				tPreEmployeeProject.setUnitName(dept.getCustomerName());
				tPreEmployeeProject.setUnitNo(dept.getCustomerNo());
				tPreEmployeeProject.setBusinessPrimaryType(dept.getBusinessPrimaryType());
				tPreEmployeeProject.setBusinessSecondType(dept.getBusinessSecondType());
				tPreEmployeeProject.setBusinessThirdType(dept.getBusinessThirdType());
				tPreEmployeeProject.setDeptId(main.getDeptId());
				tPreEmployeeProject.setDeptName(main.getDeptName());
				tPreEmployeeProject.setDeptNo(main.getDeptNo());
				tPreEmployeeProject.setPreMainId(main.getId());
				tPreEmployeeProject.setCreateBy(user.getId());
				tPreEmployeeProject.setCreateName(user.getNickname());
				tPreEmployeeProject.setCreateTime(LocalDateTime.now());
				tPreEmployeeProjectService.save(tPreEmployeeProject);
			}
			vo.setTpreEmployeeProject(tPreEmployeeProject);
		}

		// 预入职-其他附件
		List<TPreEmpOtherFile> tPreEmpOtherFileList = tPreEmpOtherFileService.getTPreEmpOtherFileList(id);
		if (tPreEmpOtherFileList == null || tPreEmpOtherFileList.isEmpty()) {
			tPreEmpOtherFileList = new ArrayList<>();
			if (Common.isNotNull(empId)) {
				List<TEmpOtherFile> infoList = tEmpOtherFileService.getListByEmpId(empId);
				TPreEmpOtherFile record;
				if (infoList != null && !infoList.isEmpty()) {
					for (TEmpOtherFile info : infoList) {
						record = new TPreEmpOtherFile();
						BeanUtil.copyProperties(info, record, ID);
						record.setEmpId(empId);
						record.setOldId(info.getId());
						// 附件
						List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
						if (attaInfoList != null) {
							URL url;
							for (TAttaInfo atta : attaInfoList) {
								url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
								atta.setAttaUrl(String.valueOf(url));
							}
						}
						record.setAttaList(attaInfoList);
						record.setPreMainId(id);
						if (Common.isEmpty(record.getCreateTime())) {
							record.setCreateTime(LocalDateTime.now());
						}
						tPreEmpOtherFileList.add(record);
					}
					tPreEmpOtherFileService.saveBatch(tPreEmpOtherFileList);
				}
			}
			if (tPreEmpOtherFileList.isEmpty()) {
				TPreEmpOtherFile record = new TPreEmpOtherFile();
				if (employee != null) {
					record.setEmpId(employee.getId());
				}
				record.setCreateTime(LocalDateTime.now());
				record.setPreMainId(id);
				record.setAttaList(new ArrayList<>());
				tPreEmpOtherFileService.save(record);
				tPreEmpOtherFileList.add(record);
			}
		} else if (empFirst) {
			tPreEmpOtherFileList = new ArrayList<>();
			if (Common.isNotNull(empId)) {
				List<TEmpOtherFile> infoList = tEmpOtherFileService.getListByEmpId(empId);
				TPreEmpOtherFile record;
				if (infoList != null && !infoList.isEmpty()) {
					for (TEmpOtherFile info : infoList) {
						record = new TPreEmpOtherFile();
						BeanUtil.copyProperties(info, record);
						record.setEmpId(empId);
						record.setOldId(info.getId());
						// 附件
						List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
						if (attaInfoList != null) {
							URL url;
							for (TAttaInfo atta : attaInfoList) {
								url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
								atta.setAttaUrl(String.valueOf(url));
							}
						}
						record.setAttaList(attaInfoList);
						record.setPreMainId(id);
						if (Common.isEmpty(record.getCreateTime())) {
							record.setCreateTime(LocalDateTime.now());
						}
						tPreEmpOtherFileList.add(record);
					}
				}
			}
			if (tPreEmpOtherFileList.isEmpty()) {
				TPreEmpOtherFile record = new TPreEmpOtherFile();
				if (employee != null) {
					record.setEmpId(employee.getId());
				}
				record.setCreateTime(LocalDateTime.now());
				record.setPreMainId(id);
				record.setAttaList(new ArrayList<>());
				tPreEmpOtherFileList.add(record);
			}
		} else {
			for (TPreEmpOtherFile info : tPreEmpOtherFileList) {
				// 附件
				List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
				if (attaInfoList != null) {
					URL url;
					for (TAttaInfo atta : attaInfoList) {
						url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
						atta.setAttaUrl(String.valueOf(url));
					}
				}
				info.setAttaList(attaInfoList);
			}
		}
		vo.setTpreEmpOtherFileList(tPreEmpOtherFileList);

		// 预入职-附件 9身份证 10 户口本；21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)
		List<TAttaInfo> allAttaList = tAttaInfoService.getTAttaInfoListByDoMainId(id);
		if ((allAttaList == null || allAttaList.isEmpty() || empFirst) && Common.isNotNull(empId)) {
			allAttaList = tAttaInfoService.getTAttaInfoListByDoMainId(empId);
		}
		if (allAttaList != null && !allAttaList.isEmpty()) {
			URL url;
			for (TAttaInfo atta : allAttaList) {
				url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
				atta.setAttaUrl(String.valueOf(url));
			}
		}
		vo.setAttaInfoList(allAttaList);

		// 以下为详档所有，简档不具有：
		if (isDetailBoo) {
			// 预入职-员工不良记录表
			TPreEmpBadRecord tPreEmpBadRecord = tPreEmpBadRecordService.getTPreEmpBadRecordList(id);
			if (tPreEmpBadRecord == null || empFirst) {
				String preId = null;
				if (tPreEmpBadRecord != null) {
					preId = tPreEmpBadRecord.getId();
				}
				tPreEmpBadRecord = new TPreEmpBadRecord();
				tPreEmpBadRecord.setId(preId);
				if (Common.isNotNull(empId)) {
					TEmpBadRecord info = tEmpBadRecordService.getByEmpId(empId);
					if (info != null) {
						BeanUtil.copyProperties(info, tPreEmpBadRecord, ID);
						if (Common.isEmpty(preId) && empFirst) {
							tPreEmpBadRecord.setId(info.getId());
						}
						tPreEmpBadRecord.setEmpId(empId);
						tPreEmpBadRecord.setOldId(info.getId());
					}
				}
				tPreEmpBadRecord.setPreMainId(id);
				tPreEmpBadRecord.setSettleDomain(deptId);
				tPreEmpBadRecord.setProject(dept.getDepartName());
				tPreEmpBadRecord.setProjectCode(dept.getDepartNo());
				tPreEmpBadRecord.setEmpIdcard(empIdCard);
				tPreEmpBadRecord.setCreateBy(user.getId());
				tPreEmpBadRecord.setCreateName(user.getNickname());
				tPreEmpBadRecord.setCreateTime(LocalDateTime.now());
				if (Common.isEmpty(tPreEmpBadRecord.getId())) {
					tPreEmpBadRecordService.save(tPreEmpBadRecord);
				}
			}
			vo.setTpreEmpBadRecord(tPreEmpBadRecord);

			// 预入职-员工伤残信息表
			TPreEmpDisabilityInfo tPreEmpDisabilityInfo = tPreEmpDisabilityInfoService.getTPreEmpDisabilityInfoList(id);
			if (tPreEmpDisabilityInfo == null || empFirst) {
				String preId = null;
				if (tPreEmpDisabilityInfo != null) {
					preId = tPreEmpDisabilityInfo.getId();
				}
				tPreEmpDisabilityInfo = new TPreEmpDisabilityInfo();
				tPreEmpDisabilityInfo.setId(preId);
				if (Common.isNotNull(empId)) {
					TEmpDisabilityInfo info = tEmpDisabilityInfoService.getByEmpId(empId);
					if (info != null) {
						BeanUtil.copyProperties(info, tPreEmpDisabilityInfo, ID);
						if (Common.isEmpty(preId) && !empFirst) {
							tPreEmpDisabilityInfo.setId(info.getId());
						}
						tPreEmpDisabilityInfo.setEmpId(empId);
						tPreEmpDisabilityInfo.setOldId(info.getId());
					}
				}
				tPreEmpDisabilityInfo.setPreMainId(id);
				tPreEmpDisabilityInfo.setSettleDomain(deptId);
				if (employee != null) {
					tPreEmpDisabilityInfo.setEmpId(employee.getId());
					tPreEmpDisabilityInfo.setEmpName(employee.getEmpName());
					tPreEmpDisabilityInfo.setEmpCode(employee.getEmpCode());
				}
				tPreEmpDisabilityInfo.setEmpIdcard(empIdCard);
				tPreEmpDisabilityInfo.setCreateBy(user.getId());
				tPreEmpDisabilityInfo.setCreateName(user.getNickname());
				tPreEmpDisabilityInfo.setCreateTime(LocalDateTime.now());
				if (Common.isEmpty(tPreEmpDisabilityInfo.getId())) {
					tPreEmpDisabilityInfoService.save(tPreEmpDisabilityInfo);
				}
			}
			vo.setTpreEmpDisabilityInfo(tPreEmpDisabilityInfo);
			// 预入职-员工学历信息表
			TPreEmpEducation tPreEmpEducation = tPreEmpEducationService.getTPreEmpEducationList(id);
			if (tPreEmpEducation == null || empFirst) {
				String preId = null;
				if (tPreEmpEducation != null) {
					preId = tPreEmpEducation.getId();
				}
				tPreEmpEducation = new TPreEmpEducation();
				tPreEmpEducation.setId(preId);
				if (Common.isNotNull(empId)) {
					TEmpEducation info = tEmpEducationService.getByEmpId(empId);
					if (info != null) {
						BeanUtil.copyProperties(info, tPreEmpEducation, ID);
						if (Common.isEmpty(preId) && !empFirst) {
							tPreEmpEducation.setId(info.getId());
						}
						tPreEmpEducation.setEmpId(empId);
						tPreEmpEducation.setOldId(info.getId());

						// 附件
						List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
						if (attaInfoList != null) {
							URL url;
							for (TAttaInfo atta : attaInfoList) {
								url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
								atta.setAttaUrl(String.valueOf(url));
							}
						}
						tPreEmpEducation.setAttaList(attaInfoList);
					}
				}
				tPreEmpEducation.setPreMainId(id);
				tPreEmpEducation.setSettleDomain(deptId);
				if (employee != null) {
					tPreEmpEducation.setEmpId(employee.getId());
					tPreEmpEducation.setEmpName(employee.getEmpName());
					tPreEmpEducation.setEmpCode(employee.getEmpCode());
				}
				tPreEmpEducation.setEmpIdcard(empIdCard);
				tPreEmpEducation.setCreateBy(user.getId());
				tPreEmpEducation.setCreateName(user.getNickname());
				tPreEmpEducation.setCreateTime(LocalDateTime.now());
				if (Common.isEmpty(tPreEmpEducation.getId())) {
					tPreEmpEducationService.save(tPreEmpEducation);
				}
			} else {
				// 附件
				List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(tPreEmpEducation.getId());
				if (attaInfoList != null) {
					URL url;
					for (TAttaInfo atta : attaInfoList) {
						url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
						atta.setAttaUrl(String.valueOf(url));
					}
				}
				tPreEmpEducation.setAttaList(attaInfoList);
			}
			vo.setTpreEmpEducation(tPreEmpEducation);
			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamilyList = tPreEmpFamilyService.getTPreEmpFamilyList(id);
			if (tPreEmpFamilyList == null || tPreEmpFamilyList.isEmpty()) {
				tPreEmpFamilyList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpFamily> infoList = tEmpFamilyService.getListByEmpId(empId);
					if (infoList != null && !infoList.isEmpty()) {
						TPreEmpFamily record;
						for (TEmpFamily info : infoList) {
							record = new TPreEmpFamily();
							BeanUtil.copyProperties(info, record, ID);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}
							record.setEmpIdcard(empIdCard);
							record.setPreMainId(id);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpFamilyList.add(record);
						}
						tPreEmpFamilyService.saveBatch(tPreEmpFamilyList);
					}
				}
				if (tPreEmpFamilyList.isEmpty()) {
					TPreEmpFamily record = new TPreEmpFamily();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpFamilyService.save(record);
					tPreEmpFamilyList.add(record);
				}
			} else if (empFirst) {
				tPreEmpFamilyList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpFamily> infoList = tEmpFamilyService.getListByEmpId(empId);
					if (infoList != null && !infoList.isEmpty()) {
						TPreEmpFamily record;
						for (TEmpFamily info : infoList) {
							record = new TPreEmpFamily();
							BeanUtil.copyProperties(info, record);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}
							record.setEmpIdcard(empIdCard);
							record.setPreMainId(id);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpFamilyList.add(record);
						}
					}
				}
				if (tPreEmpFamilyList.isEmpty()) {
					TPreEmpFamily record = new TPreEmpFamily();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpFamilyList.add(record);
				}
			}
			vo.setTpreEmpFamilyList(tPreEmpFamilyList);


			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualificationList = tPreEmpProfessionalService.getTPreEmpProfessionalQualificationList(id);
			if (tPreEmpProfessionalQualificationList == null || tPreEmpProfessionalQualificationList.isEmpty()) {
				tPreEmpProfessionalQualificationList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpProfessionalQualification> infoList = tEmpProfessionalService.getListByEmpId(empId);
					TPreEmpProfessionalQualification record;
					if (infoList != null && !infoList.isEmpty()) {
						for (TEmpProfessionalQualification info : infoList) {
							record = new TPreEmpProfessionalQualification();
							BeanUtil.copyProperties(info, record, ID);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}

							// 附件
							List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
							if (attaInfoList != null) {
								URL url;
								for (TAttaInfo atta : attaInfoList) {
									url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
									atta.setAttaUrl(String.valueOf(url));
								}
							}
							record.setAttaList(attaInfoList);
							record.setPreMainId(id);
							record.setEmpIdcard(empIdCard);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpProfessionalQualificationList.add(record);
						}
						tPreEmpProfessionalService.saveBatch(tPreEmpProfessionalQualificationList);
					}
				}
				if (tPreEmpProfessionalQualificationList.isEmpty()) {
					TPreEmpProfessionalQualification record = new TPreEmpProfessionalQualification();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setAttaList(new ArrayList<>());
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpProfessionalService.save(record);
					tPreEmpProfessionalQualificationList.add(record);
				}
			} else if (empFirst) {
				tPreEmpProfessionalQualificationList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpProfessionalQualification> infoList = tEmpProfessionalService.getListByEmpId(empId);
					TPreEmpProfessionalQualification record;
					if (infoList != null && !infoList.isEmpty()) {
						for (TEmpProfessionalQualification info : infoList) {
							record = new TPreEmpProfessionalQualification();
							BeanUtil.copyProperties(info, record);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}

							// 附件
							List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
							if (attaInfoList != null) {
								URL url;
								for (TAttaInfo atta : attaInfoList) {
									url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
									atta.setAttaUrl(String.valueOf(url));
								}
							}
							record.setAttaList(attaInfoList);
							record.setPreMainId(id);
							record.setEmpIdcard(empIdCard);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpProfessionalQualificationList.add(record);
						}
					}
				}
				if (tPreEmpProfessionalQualificationList.isEmpty()) {
					TPreEmpProfessionalQualification record = new TPreEmpProfessionalQualification();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setAttaList(new ArrayList<>());
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpProfessionalQualificationList.add(record);
				}

			} else {
				for (TPreEmpProfessionalQualification info : tPreEmpProfessionalQualificationList) {
					// 附件
					List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
					if (attaInfoList != null) {
						URL url;
						for (TAttaInfo atta : attaInfoList) {
							url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
							atta.setAttaUrl(String.valueOf(url));
						}
					}
					info.setAttaList(attaInfoList);
				}
			}
			vo.setTpreEmpProfessionalQualificationList(tPreEmpProfessionalQualificationList);


			// 预入职-员工工作履历信息表
			List<TPreEmpWorkRecording> tPreEmpWorkRecordingList = tPreEmpWorkRecordingService.getTPreEmpWorkRecordingList(id);
			if (tPreEmpWorkRecordingList == null || tPreEmpWorkRecordingList.isEmpty()) {
				tPreEmpWorkRecordingList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpWorkRecording> infoList = tEmpWorkRecordingService.getListByEmpId(empId);
					TPreEmpWorkRecording record;
					if (infoList != null && !infoList.isEmpty()) {
						for (TEmpWorkRecording info : infoList) {
							record = new TPreEmpWorkRecording();
							BeanUtil.copyProperties(info, record, ID);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}
							record.setEmpIdcard(empIdCard);
							record.setPreMainId(id);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpWorkRecordingList.add(record);
						}
						tPreEmpWorkRecordingService.saveBatch(tPreEmpWorkRecordingList);
					}
				}
				if (tPreEmpWorkRecordingList.isEmpty()) {
					TPreEmpWorkRecording record = new TPreEmpWorkRecording();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpWorkRecordingService.save(record);
					tPreEmpWorkRecordingList.add(record);
				}
			} else if (empFirst) {
				tPreEmpWorkRecordingList = new ArrayList<>();
				if (Common.isNotNull(empId)) {
					List<TEmpWorkRecording> infoList = tEmpWorkRecordingService.getListByEmpId(empId);
					TPreEmpWorkRecording record;
					if (infoList != null && !infoList.isEmpty()) {
						for (TEmpWorkRecording info : infoList) {
							record = new TPreEmpWorkRecording();
							BeanUtil.copyProperties(info, record);
							record.setEmpId(empId);
							record.setOldId(info.getId());
							record.setSettleDomain(deptId);
							if (employee != null) {
								record.setEmpId(employee.getId());
								record.setEmpName(employee.getEmpName());
								record.setEmpCode(employee.getEmpCode());
							}
							record.setEmpIdcard(empIdCard);
							record.setPreMainId(id);
							if (Common.isEmpty(record.getCreateBy())) {
								record.setCreateBy(user.getId());
								record.setCreateName(user.getNickname());
								record.setCreateTime(LocalDateTime.now());
							}
							tPreEmpWorkRecordingList.add(record);
						}
					}
				}
				if (tPreEmpWorkRecordingList.isEmpty()) {
					TPreEmpWorkRecording record = new TPreEmpWorkRecording();
					record.setSettleDomain(deptId);
					if (employee != null) {
						record.setEmpId(employee.getId());
						record.setEmpName(employee.getEmpName());
						record.setEmpCode(employee.getEmpCode());
					}
					record.setEmpIdcard(empIdCard);
					record.setPreMainId(id);
					record.setCreateBy(user.getId());
					record.setCreateName(user.getNickname());
					record.setCreateTime(LocalDateTime.now());
					tPreEmpWorkRecordingList.add(record);
				}
			}
			vo.setTpreEmpWorkRecordingList(tPreEmpWorkRecordingList);

		}

		return R.ok(vo);

	}

	/**
	 * @param tSalaryEmployee
	 * @param tPreEmployeeInfo
	 * @Description: 用薪资的人员信息
	 * @Author: hgw
	 * @Date: 2024/11/12 14:28
	 * @return: void
	 **/
	private void setNewSalaryEmpBankInfo(TSalaryEmployee tSalaryEmployee, TPreEmployeeInfo tPreEmployeeInfo) {
		if (tSalaryEmployee != null) {
			tPreEmployeeInfo.setBankNo(tSalaryEmployee.getBankNo());
			if (Common.isEmpty(tSalaryEmployee.getBankNo())) {
				tPreEmployeeInfo.setBankName(null);
				tPreEmployeeInfo.setBankSubName(null);
				tPreEmployeeInfo.setBankProvince(null);
				tPreEmployeeInfo.setBankCity(null);
				tPreEmployeeInfo.setTaxMonth(null);
			} else {
				tPreEmployeeInfo.setBankName(tSalaryEmployee.getBankName());
				tPreEmployeeInfo.setBankSubName(tSalaryEmployee.getBankSubName());
				tPreEmployeeInfo.setBankProvince(tSalaryEmployee.getBankProvince());
				tPreEmployeeInfo.setBankCity(tSalaryEmployee.getBankCity());
				tPreEmployeeInfo.setTaxMonth(tSalaryEmployee.getTaxMonth());
			}
		} else {
			tPreEmployeeInfo.setBankNo(null);
			tPreEmployeeInfo.setBankName(null);
			tPreEmployeeInfo.setBankSubName(null);
			tPreEmployeeInfo.setBankProvince(null);
			tPreEmployeeInfo.setBankCity(null);
			tPreEmployeeInfo.setTaxMonth(null);
		}
	}

	/**
	 * @Description: 详情
	 * @Author: hgw
	 * @Date: 2024/6/17 17:19
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.vo.PreEmpMainDetailVo>
	 **/
	@Override
	public R<PreEmpMainDetailVo> getInfoById(String id) {
		TPreEmpMain main = this.getById(id);
		PreEmpMainDetailVo vo = new PreEmpMainDetailVo();
		if (main != null && main.getId() != null) {
			vo.setMain(main);
			// 预入职-员工不良记录表
			TPreEmpBadRecord tPreEmpBadRecord = tPreEmpBadRecordService.getTPreEmpBadRecordList(id);
			vo.setTpreEmpBadRecord(tPreEmpBadRecord);
			// 预入职-紧急联络人
			TPreEmpContactInfo tPreEmpContactInfo = tPreEmpContactInfoService.getTPreEmpContactInfoList(id);
			vo.setTpreEmpContactInfo(tPreEmpContactInfo);
			// 预入职-员工声明
			TPreEmpDeclaration tPreEmpDeclaration;
			if (Common.isNotNull(main.getDeclarationId())) {
				tPreEmpDeclaration = tPreEmpDeclarationService.getById(main.getDeclarationId());
			} else {
				// 类型1详档2简档
				if (Common.isNotNull(main.getEmpIdcard()) && Common.isNotNull(main.getDeptId())) {
					String isSimple = registrationPreService.judgeIsSimple(main.getEmpIdcard(), main.getDeptId());
					if (CommonConstants.TWO_STRING.equals(isSimple)) {
						tPreEmpDeclaration = tPreEmpDeclarationService.getById(CommonConstants.TWO_STRING);
					} else {
						tPreEmpDeclaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
					}
				} else {
					tPreEmpDeclaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
				}
			}
			if (tPreEmpDeclaration == null) {
				return R.failed("请联系管理员添加员工声明信息！");
			}
			vo.setTpreEmpDeclaration(tPreEmpDeclaration);
			// 预入职-员工伤残信息表
			TPreEmpDisabilityInfo tPreEmpDisabilityInfo = tPreEmpDisabilityInfoService.getTPreEmpDisabilityInfoList(id);
			vo.setTpreEmpDisabilityInfo(tPreEmpDisabilityInfo);
			// 预入职-员工学历信息表
			TPreEmpEducation tPreEmpEducation = tPreEmpEducationService.getTPreEmpEducationList(id);
			if (tPreEmpEducation != null) {
				List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(tPreEmpEducation.getId());
				if (attaInfoList != null) {
					URL url;
					for (TAttaInfo atta : attaInfoList) {
						url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
						atta.setAttaUrl(String.valueOf(url));
					}
				}
				tPreEmpEducation.setAttaList(attaInfoList);
			}
			vo.setTpreEmpEducation(tPreEmpEducation);
			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamily = tPreEmpFamilyService.getTPreEmpFamilyList(id);
			vo.setTpreEmpFamilyList(tPreEmpFamily);
			// 预入职-人员档案表
			TPreEmployeeInfo tPreEmployeeInfo = tPreEmployeeInfoService.getTPreEmployeeInfoList(id);
			vo.setTpreEmployeeInfo(tPreEmployeeInfo);
			// 预入职-项目档案表
			TPreEmployeeProject tPreEmployeeProject = tPreEmployeeProjectService.getTPreEmployeeProjectList(id);
			vo.setTpreEmployeeProject(tPreEmployeeProject);
			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualificationList = tPreEmpProfessionalService.getTPreEmpProfessionalQualificationList(id);

			if (tPreEmpProfessionalQualificationList != null) {
				List<TAttaInfo> attaInfoList;
				for (TPreEmpProfessionalQualification info : tPreEmpProfessionalQualificationList) {
					attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
					if (attaInfoList != null) {
						URL url;
						for (TAttaInfo atta : attaInfoList) {
							url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
							atta.setAttaUrl(String.valueOf(url));
						}
						info.setAttaList(attaInfoList);
					}
				}
			}

			vo.setTpreEmpProfessionalQualificationList(tPreEmpProfessionalQualificationList);

			// 预入职-其他附件
			List<TPreEmpOtherFile> tPreEmpOtherFileList = tPreEmpOtherFileService.getTPreEmpOtherFileList(id);
			if (tPreEmpOtherFileList != null && !tPreEmpOtherFileList.isEmpty()) {
				List<TAttaInfo> attaInfoList;
				URL url;
				for (TPreEmpOtherFile info : tPreEmpOtherFileList) {
					// 附件
					attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(info.getId());
					if (attaInfoList != null) {
						for (TAttaInfo atta : attaInfoList) {
							url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
							atta.setAttaUrl(String.valueOf(url));
						}
					}
					info.setAttaList(attaInfoList);
				}
			}
			vo.setTpreEmpOtherFileList(tPreEmpOtherFileList);

			// 预入职-员工工作履历信息表
			List<TPreEmpWorkRecording> tPreEmpWorkRecording = tPreEmpWorkRecordingService.getTPreEmpWorkRecordingList(id);
			vo.setTpreEmpWorkRecordingList(tPreEmpWorkRecording);

			// 预入职-附件 9身份证 10 户口本；21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)
			List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(id);
			if (attaInfoList != null) {
				URL url;
				for (TAttaInfo atta : attaInfoList) {
					url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
					atta.setAttaUrl(String.valueOf(url));
				}
			}
			vo.setAttaInfoList(attaInfoList);
			return R.ok(vo);
		} else {
			return R.failed("根据ID，未找到预入职主表！");
		}
	}

	/**
	 * @Description: 单个完善信息
	 * @Author: hgw
	 * @Date: 2024/6/17 17:42
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Override
	public R<String> doImproveInformation(PreEmpMainDetailVo vo) {
		TPreEmpMain preMain = vo.getMain();
		TPreEmployeeInfo tPreEmployee = vo.getTpreEmployeeInfo();
		TPreEmployeeInfo oldPreEmployee = tPreEmployeeInfoService.getTPreEmployeeInfoList(preMain.getId());
		TPreEmployeeProject project = vo.getTpreEmployeeProject();
		if (tPreEmployee == null || project == null || oldPreEmployee == null ||
				Common.isEmpty(preMain.getId()) || Common.isEmpty(tPreEmployee.getId()) || Common.isEmpty(project.getId())) {
			return R.failed("请传主表ID与人员ID与项目ID");
		}
		TPreEmpMain main = this.getById(preMain.getId());
		if (!CommonConstants.ONE_STRING.equals(main.getStatus())) {
			return R.failed("状态不为待完善，不可编辑！");
		}
		String errorInfo = null;
		if (Common.isNotNull(preMain.getStatus()) && !CommonConstants.ONE_STRING.equals(preMain.getStatus())) {
			if (Common.isEmpty(tPreEmployee.getEmpNatrue())) {
				errorInfo = "【员工类型】";
			}
			if (Common.isEmpty(tPreEmployee.getFileProvince())) {
				errorInfo += "【档案地省】";
			}
			if (Common.isNotNull(errorInfo)) {
				return R.failed(errorInfo + "不可为空！");
			}
			// 计税月份
			if (Common.isNotNull(tPreEmployee.getBankNo()) && Common.isEmpty(tPreEmployee.getTaxMonth())) {
				return R.failed("有银行卡号，计税月份必填！");
			}
		}
		if (Common.isNotNull(tPreEmployee.getTaxMonth())) {
			String taxMonth = tPreEmployee.getTaxMonth().trim();
			if (!taxMonth.matches(TAX_MONTH_REGEX)) {
				return R.failed("计税月份为6位年月，例如：202407！");
			}
			if (Common.isNotNull(main.getSourType()) && CommonConstants.ONE_STRING.equals(main.getSourType())) {
				// 校验：
				R<String> sdr = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl(), salaryProperties.getAppId()
						, "/tsalaryemployee/inner/getEmpTaxMonth", oldPreEmployee.getEmpIdcard(), String.class, SecurityConstants.FROM_IN);
				if (sdr != null && sdr.getData() != null && !CommonConstants.ZERO_STRING.equals(sdr.getData())) {
					taxMonth = sdr.getData();
					if (!CommonConstants.ZERO_STRING.equals(taxMonth)
							&& !taxMonth.equals(tPreEmployee.getTaxMonth())) {
						return R.failed("计税月份和薪酬查询处的计税月份不一致！请填写：" + taxMonth);
					}
				}
			} else if (Common.isNotNull(tPreEmployee.getTaxMonthFlag()) && CommonConstants.ZERO_STRING.equals(tPreEmployee.getTaxMonthFlag())
					&& !oldPreEmployee.getTaxMonth().equals(tPreEmployee.getTaxMonth()) ) {
				return R.failed("本年度有发薪纪录，计税月份不可编辑！");
			}
		}

		tPreEmployee.setMajor(oldPreEmployee.getMajor());
		tPreEmployee.setSchool(oldPreEmployee.getSchool());
		tPreEmployee.setAdmissionDate(oldPreEmployee.getAdmissionDate());
		tPreEmployee.setGradutionDate(oldPreEmployee.getGradutionDate());

		tPreEmployeeInfoService.updateById(tPreEmployee);
		project.setEmpNatrue(tPreEmployee.getEmpNatrue());
		tPreEmployeeProjectService.updateById(project);

		main.setEmpNatrue(tPreEmployee.getEmpNatrue());
		main.setStatus(CommonConstants.TWO_STRING);
		if (CommonConstants.ONE_STRING.equals(main.getSourType())) {
			// 更新其他附件信息  fxj 2024-09-09
			updateOtherAtta(preMain);
			// 更新附件信息  hgw 2024-10-15
			updateAtta(preMain);
		}
		// 可以变更状态：
		if (Common.isNotNull(preMain.getStatus())) {
			if (CommonConstants.ONE_STRING.equals(preMain.getStatus())) {
				main.setStatus(CommonConstants.ONE_STRING);
			} else if (CommonConstants.TWO_STRING.equals(preMain.getStatus())) {
				main.setStatus(CommonConstants.TWO_STRING);
			}
			if (CommonConstants.FOUR_STRING.equals(preMain.getStatus())) {
				// 先变成待审核
				main.setStatus(CommonConstants.TWO_STRING);
				this.updateById(main);
				// 再调用审核通过的逻辑：
				this.doAudit(main.getId(), CommonConstants.FOUR_STRING, null);
			} else {
				this.updateById(main);
			}
		} else {
			this.updateById(main);
		}
		return R.ok("已完善！");
	}

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

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

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

	/**
	 * @param vo
	 * @Description: 草稿
	 * @Author: hgw
	 * @Date: 2024/6/17 17:42
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Override
	@Transactional
	public R<String> saveDraftPreEmpMain(PreEmpMainDetailVo vo) {
		return saveBase(vo, CommonConstants.ZERO_STRING);
	}

	/**
	 * @param vo
	 * @Description: 保存
	 * @Author: hgw
	 * @Date: 2024/6/17 17:42
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Override
	@Transactional
	public R<String> savePreEmpMain(PreEmpMainDetailVo vo) {
		return saveBase(vo, CommonConstants.ONE_STRING);
	}


	/**
	 * @Description: 核心保存
	 * @Author: hgw
	 * @Date: 2024/6/17 17:44
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> saveBase(PreEmpMainDetailVo vo, String status) {
		TPreEmpMain main = vo.getMain();
		try {
			YifuUser user = getNewYifuUser();
			String idCard = main.getEmpIdcard();
			if (Common.isNotNull(idCard)) {
				if (Common.isEmpty(main.getDeptId())) {
					return R.failed("项目ID不可为空");
				}
				String isSimple = registrationPreService.judgeIsSimple(idCard, main.getDeptId());
				if (CommonConstants.ONE_STRING.equals(status) && CommonConstants.ONE_STRING.equals(isSimple) && !isSimple.equals(main.getIsSimple())) {
					return R.failed("员工类型或合同类型已变更，请刷新后重新提交！");
				}
				EmployeeRegistrationPre pre = registrationPreService.getPreInfo(idCard, main.getDeptId());
				TPreEmployeeProject tPreEmployeeProject = vo.getTpreEmployeeProject();
				TPreEmployeeInfo tPreEmployeeInfo = vo.getTpreEmployeeInfo();
				if (pre != null && Common.isNotNull(pre.getId())) {
					if (Common.isNotNull(pre.getEmpNature())) {
						if (tPreEmployeeProject != null) {
							tPreEmployeeProject.setEmpNatrue(pre.getEmpNature());
							if (Common.isNotNull(pre.getContractType())) {
								tPreEmployeeProject.setContractType(pre.getContractType());
							}
							if (Common.isNotNull(pre.getPosition())) {
								tPreEmployeeProject.setPost(pre.getPosition());
							}
							if (Common.isNotNull(pre.getJoinLeaveDate())) {
								tPreEmployeeProject.setEnjoinDate(pre.getJoinLeaveDate());
							}
						}
						main.setEmpNatrue(pre.getEmpNature());
					}
					if (tPreEmployeeInfo != null) {
						if (Common.isNotNull(pre.getEmpPhone())) {
							tPreEmployeeInfo.setEmpPhone(pre.getEmpPhone());
							main.setEmpPhone(pre.getEmpPhone());
						}
						if (Common.isNotNull(pre.getEmpNature())) {
							tPreEmployeeInfo.setEmpNatrue(pre.getEmpNature());
						}
						if (Common.isNotNull(pre.getProvinceCode())) {
							tPreEmployeeInfo.setFileProvince(Integer.parseInt(pre.getProvinceCode()));
						}
						if (Common.isNotNull(pre.getCityCode())) {
							tPreEmployeeInfo.setFileCity(Integer.parseInt(pre.getCityCode()));
						} else {
							tPreEmployeeInfo.setFileCity(null);
						}
						if (Common.isNotNull(pre.getTownCode())) {
							tPreEmployeeInfo.setFileTown(Integer.parseInt(pre.getTownCode()));
						} else {
							tPreEmployeeInfo.setFileTown(null);
						}
					}
				}
				// 如果是简档，将清空多余信息（在获取里清空过了）
				boolean isSimpleBoo = false;
				if (CommonConstants.TWO_STRING.equals(isSimple)) {
					isSimpleBoo = true;
				}

				if (tPreEmployeeProject != null && Common.isNotNull(tPreEmployeeProject.getOldId())) {
					// 预入职-人员档案表
					if (tPreEmployeeInfo != null && Common.isNotNull(tPreEmployeeInfo.getOldId())) {
						// 转到更新档案去
						return updateToEmployeeByPre(vo, isSimpleBoo);
					} else {
						return R.failed("档案原ID不可为空！");
					}
				} else {
					main.setStatus(status);
					// 有信息，就跳转到待审核
					if (pre != null && Common.isNotNull(pre.getId()) && CommonConstants.ONE_STRING.equals(status)) {
						main.setStatus(CommonConstants.TWO_STRING);
						registrationPreService.updatePreStatusToTwo(main.getDeptId(), idCard);
						if (isSimpleBoo) {
							main.setStatus(CommonConstants.FOUR_STRING);
							// 审核日志
							TPreEmpMainLog auditLog = new TPreEmpMainLog();
							auditLog.setAuditId(user.getId());
							auditLog.setAuditName("自动审核");
							auditLog.setAuditTime(new Date());
							auditLog.setAuditRemark("简档自动审核通过");
							auditLog.setMainId(main.getId());
							auditLog.setAuditResult(CommonConstants.FOUR_STRING);
							tPreEmpMainLogService.save(auditLog);

							main.setAuditId(user.getId());
							main.setAuditRemark("简档自动审核通过");
							main.setAuditName("自动审核");
							main.setAuditTime(new Date());
							updateToEmployeeByPre(vo, isSimpleBoo);
						}
					}
					main.setCreateBy(user.getId());
					main.setCreateName(user.getNickname());
					main.setCreateTime(LocalDateTime.now());
					main.setSourType(CommonConstants.ZERO_STRING);
					this.saveOrUpdate(main);
					String mainId = main.getId();

					// 预入职-员工不良记录表
					TPreEmpBadRecord tPreEmpBadRecord = vo.getTpreEmpBadRecord();
					if (tPreEmpBadRecord != null) {
						tPreEmpBadRecord.setPreMainId(mainId);
						tPreEmpBadRecord.setCreateBy(user.getId());
						tPreEmpBadRecord.setCreateName(user.getNickname());
						tPreEmpBadRecord.setCreateTime(LocalDateTime.now());
						// todo 1.9.6 -chenyuxi:先根据备注文字判断
						if(Common.isNotNull(tPreEmpBadRecord.getRemark())){
							if(tPreEmpBadRecord.getRemark().contains("未曾经")){
								tPreEmpBadRecord.setBadRecordFlag(CommonConstants.ONE_STRING);
							} else {
								tPreEmpBadRecord.setBadRecordFlag(CommonConstants.ZERO_STRING);
							}
						}
						// 1.9.6 -chenyuxi: 新增和编辑分开，允许存null值
						// 新增不良记录
						if(Common.isEmpty(tPreEmpBadRecord.getId())){
							tPreEmpBadRecordService.saveOrUpdate(tPreEmpBadRecord);
						} else {
							// 编辑不良记录
							LambdaUpdateWrapper<TPreEmpBadRecord> updateDiyInfoWrapper = new LambdaUpdateWrapper<>();
							updateDiyInfoWrapper.eq(TPreEmpBadRecord::getId, tPreEmpBadRecord.getId())
									.set(TPreEmpBadRecord::getBadRecordFlag, tPreEmpBadRecord.getBadRecordFlag())
									.set(TPreEmpBadRecord::getRemark, tPreEmpBadRecord.getRemark())
									.set(TPreEmpBadRecord::getHappenTime, null)
									.set(TPreEmpBadRecord::getLoseFee, null)
									.set(TPreEmpBadRecord::getLoseFeeOther, null)
									.set(TPreEmpBadRecord::getUpdateBy, user.getId())
									.set(TPreEmpBadRecord::getUpdateTime, LocalDateTime.now());
							tPreEmpBadRecordService.update(null, updateDiyInfoWrapper);
						}

					}
					// 预入职-紧急联络人
					TPreEmpContactInfo tPreEmpContactInfo = vo.getTpreEmpContactInfo();
					if (tPreEmpContactInfo != null) {
						tPreEmpContactInfo.setPreMainId(mainId);
						tPreEmpContactInfo.setCreateBy(user.getId());
						tPreEmpContactInfo.setCreateName(user.getNickname());
						tPreEmpContactInfo.setCreateTime(LocalDateTime.now());
						tPreEmpContactInfoService.saveOrUpdate(tPreEmpContactInfo);
					}
					// 预入职-员工伤残信息表
					TPreEmpDisabilityInfo tPreEmpDisabilityInfo = vo.getTpreEmpDisabilityInfo();
					if (tPreEmpDisabilityInfo != null) {
						tPreEmpDisabilityInfo.setPreMainId(mainId);
						tPreEmpDisabilityInfo.setCreateBy(user.getId());
						tPreEmpDisabilityInfo.setCreateName(user.getNickname());
						tPreEmpDisabilityInfo.setCreateTime(LocalDateTime.now());
						tPreEmpDisabilityInfoService.saveOrUpdate(tPreEmpDisabilityInfo);
					}
					// 预入职-员工学历信息表
					TPreEmpEducation tPreEmpEducation = vo.getTpreEmpEducation();
					if (tPreEmpEducation != null) {
						tPreEmpEducation.setPreMainId(mainId);
						tPreEmpEducation.setCreateBy(user.getId());
						tPreEmpEducation.setCreateName(user.getNickname());
						tPreEmpEducation.setCreateTime(LocalDateTime.now());
						tPreEmpEducationService.saveOrUpdate(tPreEmpEducation);
						// 附件
						tAttaInfoService.deleteByDomainIdAndType(tPreEmpEducation.getId(), 0);
						if (tPreEmpEducation.getAttaList() != null && !tPreEmpEducation.getAttaList().isEmpty()) {
							List<TAttaInfo> attaList = tPreEmpEducation.getAttaList();
							if (attaList != null) {
								for (TAttaInfo atta : attaList) {
									atta.setId(null);
									atta.setDomainId(tPreEmpEducation.getId());
									atta.setCreateBy(user.getId());
									atta.setCreateName(user.getNickname());
									atta.setCreateTime(LocalDateTime.now());
								}
								tAttaInfoService.saveBatch(attaList);
							}
						}
					}
					// 预入职-员工家庭信息表
					List<TPreEmpFamily> tPreEmpFamily = vo.getTpreEmpFamilyList();
					if (tPreEmpFamily != null) {
						tPreEmpFamilyService.deleteFamilyByMainId(mainId);
						for (TPreEmpFamily info : tPreEmpFamily) {
							info.setEmpIdcard(idCard);
							info.setPreMainId(mainId);
							info.setCreateBy(user.getId());
							info.setCreateName(user.getNickname());
							info.setCreateTime(LocalDateTime.now());
						}
						tPreEmpFamilyService.saveOrUpdateBatch(tPreEmpFamily);
					}
					// 预入职-人员档案表
					if (tPreEmployeeInfo != null) {
						if (tPreEmpEducation != null) {
							if (Common.isNotNull(tPreEmpEducation.getEducationName())) {
								// 5大专 6本科 7硕士 8博士
								if ("5".equals(tPreEmpEducation.getEducationName())
										|| "6".equals(tPreEmpEducation.getEducationName())
										|| "7".equals(tPreEmpEducation.getEducationName())
										|| "8".equals(tPreEmpEducation.getEducationName())) {
									tPreEmployeeInfo.setIsCollege(CommonConstants.ONE_INT);
								} else {
									tPreEmployeeInfo.setIsCollege(CommonConstants.ZERO_INT);
								}
								tPreEmployeeInfo.setHignEducation(tPreEmpEducation.getEducationName());
							}
							tPreEmployeeInfo.setSchool(tPreEmpEducation.getSchool());
							tPreEmployeeInfo.setMajor(tPreEmpEducation.getMajor());
							tPreEmployeeInfo.setAdmissionDate(tPreEmpEducation.getEntryDate());
							tPreEmployeeInfo.setGradutionDate(tPreEmpEducation.getGradutionDate());
						}
						// 生成性别年龄等：
						this.setBaseSexInfo(tPreEmployeeInfo);
						tPreEmployeeInfo.setPreMainId(mainId);
						tPreEmployeeInfo.setCreateBy(user.getId());
						tPreEmployeeInfo.setCreateName(user.getNickname());
						tPreEmployeeInfo.setCreateTime(LocalDateTime.now());

						// 塞计税月份标志
						this.setTaxMonthAndFlag(status, tPreEmployeeInfo);

						tPreEmployeeInfoService.saveOrUpdate(tPreEmployeeInfo);
					}
					// 预入职-项目档案表
					if (tPreEmployeeProject != null) {
						tPreEmployeeProject.setPreMainId(mainId);
						tPreEmployeeProject.setCreateBy(user.getId());
						tPreEmployeeProject.setCreateName(user.getNickname());
						tPreEmployeeProject.setCreateTime(LocalDateTime.now());
						tPreEmployeeProjectService.saveOrUpdate(tPreEmployeeProject);
					}
					// 预入职-员工职业资格信息表
					List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualification = vo.getTpreEmpProfessionalQualificationList();
					if (tPreEmpProfessionalQualification != null && tPreEmpProfessionalQualification.size()>0) {
						// 先删除后增加
						tPreEmpProfessionalService.deleteProfessionalByMainId(mainId);
						for (TPreEmpProfessionalQualification info : tPreEmpProfessionalQualification) {
							info.setEmpIdcard(idCard);
							info.setPreMainId(mainId);
							info.setCreateBy(user.getId());
							info.setCreateName(user.getNickname());
							info.setCreateTime(LocalDateTime.now());
							// 1.9.6 -chenyuxi:增加标识
							info.setHaveQualification(CommonConstants.ZERO_STRING);
							tPreEmpProfessionalService.saveOrUpdate(info);
							// 附件
							if (info.getAttaList() != null && !info.getAttaList().isEmpty()) {
								List<TAttaInfo> attaList = info.getAttaList();
								if (attaList != null) {
									tAttaInfoService.deleteByDomainIdAndType(info.getId(), 1);
									for (TAttaInfo atta : attaList) {
										atta.setId(null);
										atta.setDomainId(info.getId());
										atta.setCreateBy(user.getId());
										atta.setCreateName(user.getNickname());
										atta.setCreateTime(LocalDateTime.now());
									}
									tAttaInfoService.saveBatch(attaList);
								}
							}
						}
					}
					// 预入职-其他附件
					List<TPreEmpOtherFile> tPreOtherFileList = vo.getTpreEmpOtherFileList();
					if (tPreOtherFileList != null) {
						// 先删除后增加
						tPreEmpOtherFileService.deleteOtherFileByMainId(mainId);
						for (TPreEmpOtherFile info : tPreOtherFileList) {
							info.setPreMainId(mainId);
							info.setCreateTime(LocalDateTime.now());
							tPreEmpOtherFileService.saveOrUpdate(info);
							// 附件
							if (info.getAttaList() != null && !info.getAttaList().isEmpty()) {
								List<TAttaInfo> attaList = info.getAttaList();
								if (attaList != null) {
									tAttaInfoService.deleteByDomainIdAndType(info.getId(), 2);
									for (TAttaInfo atta : attaList) {
										atta.setId(null);
										atta.setDomainId(info.getId());
										atta.setCreateBy(user.getId());
										atta.setCreateName(user.getNickname());
										atta.setCreateTime(LocalDateTime.now());
									}
									tAttaInfoService.saveBatch(attaList);
								}
							}
						}
					}
					// 预入职-员工工作履历信息表
					List<TPreEmpWorkRecording> tPreEmpWorkRecording = vo.getTpreEmpWorkRecordingList();
					if (tPreEmpWorkRecording != null) {
						// 先删除后增加
						tPreEmpWorkRecordingService.deleteByMainId(mainId);
						for (TPreEmpWorkRecording info : tPreEmpWorkRecording) {
							info.setEmpIdcard(idCard);
							info.setPreMainId(mainId);
							info.setCreateBy(user.getId());
							info.setCreateName(user.getNickname());
							info.setCreateTime(LocalDateTime.now());
						}
						tPreEmpWorkRecordingService.saveOrUpdateBatch(tPreEmpWorkRecording);
					}
					// 预入职-附件
					List<TAttaInfo> attaInfoList = vo.getAttaInfoList();
					if (attaInfoList != null) {
						// 先删除后增加
						tAttaInfoService.deleteByDomainId(mainId);
						for (TAttaInfo info : attaInfoList) {
							info.setId(null);
							info.setDomainId(mainId);
							info.setCreateBy(user.getId());
							info.setCreateName(user.getNickname());
							info.setCreateTime(LocalDateTime.now());
						}
						tAttaInfoService.saveBatch(attaInfoList);
					}
				}
				return R.ok("成功");
			} else {
				return R.failed("身份证不可为空！");
			}
		} catch (Exception e) {
			log.error("档案预入职C端保存异常：", e);
			throw new RuntimeException("保存失败，请联系管理员！！预入职主键【" + main.getId() + "】身份证=" + main.getEmpIdcard());
		}
	}

	/**
	 * @param status 1：保存
	 * @Description: 获取计税月份和是否可编辑的标志
	 * @Author: hgw
	 * @Date: 2024/7/16 16:15
	 * @return: java.lang.String
	 **/
	private void setTaxMonthAndFlag(String status, TPreEmployeeInfo employeeInfo) {
		String taxMonth = DateUtil.getThisMonth();
		employeeInfo.setTaxMonthFlag(CommonConstants.ONE_STRING);
		if (CommonConstants.ONE_STRING.equals(status)) {
			// 去薪资服务获取
			R<String> sdr = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl(), salaryProperties.getAppId()
					, "/tsalaryemployee/inner/getEmpTaxMonth", employeeInfo.getEmpIdcard(), String.class, SecurityConstants.FROM_IN);
			if (sdr != null && sdr.getData() != null && !CommonConstants.ZERO_STRING.equals(sdr.getData())) {
				taxMonth = sdr.getData();
				employeeInfo.setTaxMonthFlag(CommonConstants.ZERO_STRING);
			}
		}
		employeeInfo.setTaxMonth(taxMonth);
	}

	private YifuUser getNewYifuUser() {
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new YifuUser("2", 1L, "", "预入职扫码",
				"预入职扫码", "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null,null);
	}

	/**
	 * @param isSimpleBoo true 简档，仅更新部分信息
	 * @Description: 执行复制到档案的操作
	 * @Author: hgw
	 * @Date: 2024/6/18 19:35
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> updateToEmployeeByPre(PreEmpMainDetailVo vo, boolean isSimpleBoo) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null) {
			user = getNewYifuUser();
		}
		// 预入职-人员档案表
		TPreEmployeeInfo tPreEmployeeInfo = vo.getTpreEmployeeInfo();
		// 简档，初始化开关，后期如果优化简档详情页面，这里可不初始化
		if (tPreEmployeeInfo != null && isSimpleBoo) {
			tPreEmployeeInfo.setFirstWorkFlag(CommonConstants.ZERO_STRING);
			tPreEmployeeInfo.setHaveQualification(CommonConstants.ONE_STRING);
		}
		// 预入职-项目档案表
		TPreEmployeeProject tPreEmployeeProject = vo.getTpreEmployeeProject();
		// 预入职-员工学历信息表
		TPreEmpEducation tPreEmpEducation = vo.getTpreEmpEducation();
		// 如果档案项目id都没有，则新增。newFlag是true：
		String empId = null;
		String empIdCard = null;
		// 1人员档案
		TEmployeeInfo emp = null;
		// 2项目档案
		TEmployeeProject project = null;
		TSettleDomain dept = null;
		if (tPreEmployeeProject != null && Common.isNotNull(tPreEmployeeProject.getDeptId())) {
			dept = tSettleDomainService.getById(tPreEmployeeProject.getDeptId());
		}
		if (dept == null) {
			return R.failed("根据项目id，未找到项目！");
		}
		if (tPreEmployeeInfo != null && tPreEmpEducation != null) {
			if (Common.isNotNull(tPreEmpEducation.getEducationName())) {
				if ("5".equals(tPreEmpEducation.getEducationName())
						|| "6".equals(tPreEmpEducation.getEducationName())
						|| "7".equals(tPreEmpEducation.getEducationName())
						|| "8".equals(tPreEmpEducation.getEducationName())) {
					tPreEmployeeInfo.setIsCollege(CommonConstants.ONE_INT);
				} else {
					tPreEmployeeInfo.setIsCollege(CommonConstants.ZERO_INT);
				}
				tPreEmployeeInfo.setHignEducation(tPreEmpEducation.getEducationName());
			}
			tPreEmployeeInfo.setSchool(tPreEmpEducation.getSchool());
			tPreEmployeeInfo.setMajor(tPreEmpEducation.getMajor());
			tPreEmployeeInfo.setAdmissionDate(tPreEmpEducation.getEntryDate());
			tPreEmployeeInfo.setGradutionDate(tPreEmpEducation.getGradutionDate());
		}
		// 有在项，则更新薪资人员
		boolean isMustUpdateSalary = false;
		if (tPreEmployeeInfo != null && Common.isEmpty(tPreEmployeeInfo.getBankNo())) {
			tPreEmployeeInfo.setBankName(null);
			tPreEmployeeInfo.setBankSubName(null);
			tPreEmployeeInfo.setBankProvince(null);
			tPreEmployeeInfo.setBankCity(null);
			tPreEmployeeInfo.setTaxMonth(null);
		}
		if (tPreEmployeeInfo != null && Common.isNotNull(tPreEmployeeInfo.getOldId())
				&& Common.isNotNull(tPreEmployeeProject.getOldId())) {
			empId = tPreEmployeeInfo.getOldId();
			emp = tEmployeeInfoService.getById(empId);
			if (emp != null) {
				// 检查人员档案的合同社保公积金状态，如果不是初始状态则不更新
				Integer oldContractStatus = emp.getContractStatus();
				Integer oldSocialStatus = emp.getSocialStatus();
				Integer oldFundStatus = emp.getFundStatus();
				Integer oldInsuranceStatus = emp.getInsuranceStatus();

				// 生成性别年龄等：
				this.setBaseSexInfo(tPreEmployeeInfo);
				if (isSimpleBoo) {
					// 简档，仅重置部分信息：
					if (Common.isNotNull(tPreEmployeeInfo.getEmpPhone())) {
						emp.setEmpPhone(tPreEmployeeInfo.getEmpPhone());
					}
					if (Common.isNotNull(tPreEmployeeInfo.getEmpNatrue())) {
						emp.setEmpNatrue(tPreEmployeeInfo.getEmpNatrue());
					}
					emp.setEmpName(tPreEmployeeInfo.getEmpName());
					emp.setEmpIdcard(tPreEmployeeInfo.getEmpIdcard());
					emp.setEmpPhone(tPreEmployeeInfo.getEmpPhone());
					emp.setContactAddress(tPreEmployeeInfo.getContactAddress());
					emp.setContactProvince(tPreEmployeeInfo.getContactProvince());
					emp.setContactCity(tPreEmployeeInfo.getContactCity());
					emp.setContactTown(tPreEmployeeInfo.getContactTown());
					emp.setEmpBirthday(tPreEmployeeInfo.getEmpBirthday());
					emp.setEmpSex(tPreEmployeeInfo.getEmpSex());
					emp.setEmpAge(tPreEmployeeInfo.getEmpAge());
					emp.setBankProvince(tPreEmployeeInfo.getBankProvince());
					emp.setBankCity(tPreEmployeeInfo.getBankCity());
					emp.setBankName(tPreEmployeeInfo.getBankName());
					emp.setBankSubName(tPreEmployeeInfo.getBankSubName());
					emp.setBankNo(tPreEmployeeInfo.getBankNo());
					emp.setCreateBy(user.getId());
					emp.setCreateName(user.getNickname());
					emp.setCreateTime(LocalDateTime.now());

					emp.setFileProvince(tPreEmployeeInfo.getFileProvince());
					emp.setFileCity(tPreEmployeeInfo.getFileCity());
					emp.setFileTown(tPreEmployeeInfo.getFileTown());
					// 更新，不初始化
					// emp.setFirstWorkFlag(tPreEmployeeInfo.getFirstWorkFlag())
					// emp.setHaveQualification(tPreEmployeeInfo.getHaveQualification())

				} else {
					BeanUtil.copyProperties(tPreEmployeeInfo, emp, ID);
				}
				if (CommonConstants.ONE_INT == emp.getFileStatus()) {
					emp.setCreateTime(LocalDateTime.now());
					emp.setFileStatus(CommonConstants.ZERO_INT);
				}
				if (Common.isNotNull(oldContractStatus) && oldContractStatus != 0) {
					emp.setContractStatus(oldContractStatus);
				}
				if (Common.isNotNull(oldSocialStatus) && oldSocialStatus != 0) {
					emp.setSocialStatus(oldSocialStatus);
				}
				if (Common.isNotNull(oldFundStatus) && oldFundStatus != 0) {
					emp.setFundStatus(oldFundStatus);
				}
				if (Common.isNotNull(oldInsuranceStatus) && oldInsuranceStatus != 0) {
					emp.setInsuranceStatus(oldInsuranceStatus);
				}
				tEmployeeInfoService.updateById(emp);
			} else {
				emp = this.saveTEmployeeInfo(user, tPreEmployeeInfo);
				empId = emp.getId();
			}
			empIdCard = emp.getEmpIdcard();
			project = tEmployeeProjectService.getById(tPreEmployeeProject.getOldId());
			if (project != null) {

				// 检查人员档案的合同社保公积金状态，如果不是初始状态则不更新
				Integer oldDeptContractStatus = project.getContractStatus();
				Integer oldDeptSocialStatus = project.getSocialStatus();
				Integer oldDeptFundStatus = project.getFundStatus();
				Integer oldDeptInsuranceStatus = project.getInsuranceStatus();
				Integer oldDeptSocialProvince = project.getSocialProvince();
				Integer oldDeptSocialCity = project.getSocialCity();
				Integer oldDeptSocialTown = project.getSocialTown();

				if (Common.isEmpty(tPreEmployeeProject.getWorkingHours())) {
					tPreEmployeeProject.setWorkingHours("");
				}
				if (Common.isEmpty(tPreEmployeeProject.getPost())) {
					tPreEmployeeProject.setPost("");
				}
				if (Common.isEmpty(tPreEmployeeProject.getTryPeriod())) {
					tPreEmployeeProject.setTryPeriod("");
				}
				// 2024-7-23 11:52:33 金龙弟预张倩倩认为不同步项目的合同信息
				// String[ ignoreProperties  new Strin{"id", "contractType", "workingHours", "post", "enjoinDate", "tryPeriod"
				// 2025-3-27 15:13:30 张倩倩认为要同步项目的合同信息
				String[] ignoreProperties = new String[]{"id", "workingHours", "tryPeriod"};
				BeanUtil.copyProperties(tPreEmployeeProject, project, ignoreProperties);
				if (CommonConstants.ONE_INT == project.getProjectStatus()) {
					project.setCreateTime(LocalDateTime.now());
					project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
					project.setProjectStatus(CommonConstants.ZERO_INT);
				} else if (CommonConstants.ZERO_INT == project.getProjectStatus()) {
					isMustUpdateSalary = true;
				}
				if (Common.isNotNull(oldDeptContractStatus) && oldDeptContractStatus != 0) {
					project.setContractStatus(oldDeptContractStatus);
				}
				if (Common.isNotNull(oldDeptSocialStatus) && oldDeptSocialStatus != 0) {
					project.setSocialStatus(oldDeptSocialStatus);
				}
				if (Common.isNotNull(oldDeptFundStatus) && oldDeptFundStatus != 0) {
					project.setFundStatus(oldDeptFundStatus);
				}
				if (Common.isNotNull(oldDeptInsuranceStatus) && oldDeptInsuranceStatus != 0) {
					project.setInsuranceStatus(oldDeptInsuranceStatus);
				}
				// 2026-03-24 段说要不更新社保省市县
				if (Common.isNotNull(oldDeptSocialProvince)) {
					project.setSocialProvince(oldDeptSocialProvince);
					project.setSocialCity(oldDeptSocialCity);
					project.setSocialTown(oldDeptSocialTown);
				}
				tEmployeeProjectService.updateById(project);

			} else {
				project = this.saveTEmployeeProject(project, user, tPreEmployeeProject, emp, dept);
			}
		} else {
			// 新建档案、项目档案，将档案id赋值，给其他附属信息
			if (tPreEmployeeInfo != null) {
				// 生成性别年龄等：
				this.setBaseSexInfo(tPreEmployeeInfo);

				// 1人员档案
				emp = this.saveTEmployeeInfo(user, tPreEmployeeInfo);
				empId = emp.getId();
				empIdCard = emp.getEmpIdcard();
				// 2项目档案
				project = this.saveTEmployeeProject(project, user, tPreEmployeeProject, emp, dept);
			}
		}
		if (emp == null) {
			return R.failed("新建员工失败！");
		}

		if (project != null) {
			// 增加，同步CSP
			tEmployeeProjectService.doSaveBelongDept(project, CommonConstants.ONE_STRING);
			// 更新入职待建档状态为已完成
			registrationPreService.updatePreStatusToEnd(project.getDeptNo(),project.getEmpIdcard());
		}
		// 更新或新增薪资人员
		// 2024-11-6 16:56:46 新逻辑：在项人员，要更新薪资人员，及时卡号为空也要更新
		if (Common.isNotNull(tPreEmployeeInfo.getBankNo()) || isMustUpdateSalary) {

			TSalaryEmployee newEmp = new TSalaryEmployee();
			newEmp.setFileStatus(CommonConstants.ZERO_STRING);
			newEmp.setDeptId(dept.getId());
			newEmp.setDeptName(dept.getDepartName());
			newEmp.setDeptNo(dept.getDepartNo());
			newEmp.setUnitId(dept.getCustomerId());
			newEmp.setUnitName(dept.getCustomerName());
			newEmp.setUnitNo(dept.getCustomerNo());
			newEmp.setCreateBy(String.valueOf(user.getId()));
			newEmp.setCreateName(user.getNickname());
			newEmp.setCreateTime(LocalDateTime.now());
			newEmp.setUpdateBy(String.valueOf(user.getId()));
			newEmp.setUpdateTime(LocalDateTime.now());
			newEmp.setInvoiceTitle(dept.getInvoiceTitleSalary());
			newEmp.setEmpName(tPreEmployeeInfo.getEmpName());
			newEmp.setEmpIdcard(tPreEmployeeInfo.getEmpIdcard());
			newEmp.setBankProvince(tPreEmployeeInfo.getBankProvince());
			newEmp.setBankCity(tPreEmployeeInfo.getBankCity());
			newEmp.setBankNo(tPreEmployeeInfo.getBankNo());
			String taxMonth = tPreEmployeeInfo.getTaxMonth();
			// 2024-11-6 18:23:36 产品倩倩说，有在项，带出来的时候是空，就不用变为当前月
			if (Common.isEmpty(tPreEmployeeInfo.getTaxMonth()) && !isMustUpdateSalary) {
				taxMonth = DateUtil.getThisMonth();
			}
			if (Common.isEmpty(tPreEmployeeInfo.getBankNo())) {
				taxMonth = null;
			}
			newEmp.setTaxMonth(taxMonth);
			newEmp.setBankName(tPreEmployeeInfo.getBankName());
			newEmp.setBankSubName(tPreEmployeeInfo.getBankSubName());
			newEmp.setEmpPhone(tPreEmployeeInfo.getEmpPhone());
			// 保存薪资人员（含判断是否有发薪）
			R<String> sdr = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl(), salaryProperties.getAppId()
					, "/tsalaryemployee/inner/savePreNewEmpInfo", newEmp, String.class, SecurityConstants.FROM_IN);
			if (sdr == null || Common.isEmpty(sdr.getData())) {
				return R.failed("同步薪资人员失败！");
			}
		}

		// 3:其他附属信息

		// 预入职-员工不良记录表
		// 预入职-员工工作履历信息表
		// 预入职-紧急联络人
		// 预入职-员工伤残信息表
		// 预入职-员工学历信息表
		// 预入职-员工家庭信息表
		// 预入职-人员档案表
		// 预入职-项目档案表
		// 预入职-员工职业资格信息表

		// 最高学历
		if (!isSimpleBoo) {
			if (tPreEmpEducation != null) {
				TEmpEducation tEmpEducation = null;
				if (Common.isNotNull(tPreEmpEducation.getOldId())) {
					tEmpEducation = tEmpEducationService.getById(tPreEmpEducation.getOldId());
				} else {
					// 测试金龙弟建议查询信息后更新，不新增额外的一条 2024-10-24 16:23:47 hgw修改
					tEmpEducation = tEmpEducationService.getByEmpId(empId);
				}
				if (tEmpEducation == null) {
					tEmpEducation = new TEmpEducation();
				} else {
					// 已存在的学历信息（如果不一致，要更新档案的最高学历）
					if (Common.isEmpty(tEmpEducation.getEducationName())
							|| !tEmpEducation.getEducationName().equals(tPreEmpEducation.getEducationName())) {
						emp.setHignEducation(tPreEmpEducation.getEducationName());
						tEmployeeInfoService.updateById(emp);
					}
				}
				BeanUtil.copyProperties(tPreEmpEducation, tEmpEducation, ID);
				if (Common.isEmpty(tEmpEducation.getEmpCode())) {
					tEmpEducation.setEmpCode(emp.getEmpCode());
				}
				if (Common.isEmpty(tEmpEducation.getEmpName())) {
					tEmpEducation.setEmpName(emp.getEmpName());
				}
				if (Common.isEmpty(tEmpEducation.getCreateTime())) {
					tEmpEducation.setCreateTime(LocalDateTime.now());
				}
				tEmpEducation.setDeleteFlag(CommonConstants.STATUS_NORMAL);
				tEmpEducation.setEmpId(empId);
				if (Common.isNotNull(empIdCard)) {
					tEmpEducationService.updateEducationToNoByIdCard(empIdCard);
				}
				if (Common.isEmpty(tEmpEducation.getCreateBy())) {
					tEmpEducation.setCreateBy(user.getId());
					tEmpEducation.setCreateName(user.getNickname());
					tEmpEducation.setCreateTime(LocalDateTime.now());
				}
				tEmpEducationService.saveOrUpdate(tEmpEducation);
				String attaId = tPreEmpEducation.getOldId();
				tAttaInfoService.deleteByDomainIdAndType(attaId, 0);
				if (tPreEmpEducation.getAttaList() != null && !tPreEmpEducation.getAttaList().isEmpty()) {
					List<TAttaInfo> attaList = tPreEmpEducation.getAttaList();
					if (attaList != null) {
						TAttaInfo newEmpAtta;
						for (TAttaInfo atta : attaList) {
							newEmpAtta = new TAttaInfo();
							BeanUtil.copyProperties(atta, newEmpAtta, ID);
							newEmpAtta.setDomainId(tEmpEducation.getId());

							if (Common.isEmpty(tEmpEducation.getCreateBy())) {
								tEmpEducation.setCreateBy(user.getId());
								tEmpEducation.setCreateName(user.getNickname());
								tEmpEducation.setCreateTime(LocalDateTime.now());
							}
							tAttaInfoService.saveOrUpdate(newEmpAtta);
						}
					}
				}
			}
			// 预入职-员工不良记录表
			TPreEmpBadRecord tPreEmpBadRecord = vo.getTpreEmpBadRecord();
			if (tPreEmpBadRecord != null) {
				TEmpBadRecord tEmpBadRecord = null;
				if (Common.isNotNull(tPreEmpBadRecord.getOldId())) {
					tEmpBadRecord = tEmpBadRecordService.getById(tPreEmpBadRecord.getOldId());
				} else {
					// 测试金龙弟建议查询信息后更新，不新增额外的一条 2024-10-24 16:23:47 hgw修改
					tEmpBadRecord = tEmpBadRecordService.getByEmpId(empId);
				}
				if (tEmpBadRecord == null) {
					tEmpBadRecord = new TEmpBadRecord();
				}
				BeanUtil.copyProperties(tPreEmpBadRecord, tEmpBadRecord, ID);
				tEmpBadRecord.setEmpId(empId);

				if (Common.isEmpty(tEmpBadRecord.getCreateBy())) {
					tEmpBadRecord.setCreateBy(user.getId());
					tEmpBadRecord.setCreateName(user.getNickname());
					tEmpBadRecord.setCreateTime(LocalDateTime.now());
				}
				tEmpBadRecordService.saveOrUpdate(tEmpBadRecord);
			}
		}
		// 预入职-紧急联络人
		TPreEmpContactInfo tPreEmpContactInfo = vo.getTpreEmpContactInfo();
		if (tPreEmpContactInfo != null) {
			TEmpContactInfo tEmpContactInfo = null;
			if (Common.isNotNull(tPreEmpContactInfo.getOldId())) {
				tEmpContactInfo = tEmpContactInfoService.getById(tPreEmpContactInfo.getOldId());
			} else {
				// 测试金龙弟建议查询信息后更新，不新增额外的一条 2024-10-24 16:23:47 hgw修改
				tEmpContactInfo = tEmpContactInfoService.getByEmpId(empId);
			}
			if (tEmpContactInfo == null) {
				tEmpContactInfo = new TEmpContactInfo();
			}
			BeanUtil.copyProperties(tPreEmpContactInfo, tEmpContactInfo, ID);
			tEmpContactInfo.setEmpId(empId);

			if (Common.isEmpty(tEmpContactInfo.getCreateBy())) {
				tEmpContactInfo.setCreateBy(user.getId());
				tEmpContactInfo.setCreateName(user.getNickname());
				tEmpContactInfo.setCreateTime(LocalDateTime.now());
			}
			if (Common.isEmpty(tEmpContactInfo.getEmpIdcard()) && Common.isNotNull(emp)) {
				tEmpContactInfo.setEmpIdcard(emp.getEmpIdcard());
			}
			tEmpContactInfoService.saveOrUpdate(tEmpContactInfo);
		}
		// 预入职-员工伤残信息表
		TPreEmpDisabilityInfo tPreEmpDisabilityInfo = vo.getTpreEmpDisabilityInfo();
		if (!isSimpleBoo) {
			if (tPreEmpDisabilityInfo != null) {
				TEmpDisabilityInfo tEmpDisabilityInfo = null;
				if (Common.isNotNull(tPreEmpDisabilityInfo.getOldId())) {
					tEmpDisabilityInfo = tEmpDisabilityInfoService.getById(tPreEmpDisabilityInfo.getOldId());
				} else {
					// 测试金龙弟建议查询信息后更新，不新增额外的一条 2024-10-24 16:23:47 hgw修改
					tEmpDisabilityInfo = tEmpDisabilityInfoService.getByEmpId(empId);
				}
				if (tEmpDisabilityInfo == null) {
					tEmpDisabilityInfo = new TEmpDisabilityInfo();
				}
				BeanUtil.copyProperties(tPreEmpDisabilityInfo, tEmpDisabilityInfo, ID);
				tEmpDisabilityInfo.setDeleteFlag(CommonConstants.STATUS_NORMAL);
				tEmpDisabilityInfo.setEmpId(empId);
				if (Common.isEmpty(tEmpDisabilityInfo.getEmpCode())) {
					tEmpDisabilityInfo.setEmpCode(emp.getEmpCode());
				}
				if (Common.isEmpty(tEmpDisabilityInfo.getEmpName())) {
					tEmpDisabilityInfo.setEmpName(emp.getEmpName());
				}

				if (Common.isEmpty(tEmpDisabilityInfo.getCreateBy())) {
					tEmpDisabilityInfo.setCreateBy(user.getId());
					tEmpDisabilityInfo.setCreateName(user.getNickname());
					tEmpDisabilityInfo.setCreateTime(LocalDateTime.now());
				}
				tEmpDisabilityInfoService.saveOrUpdate(tEmpDisabilityInfo);
			}

			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamilyList = vo.getTpreEmpFamilyList();
			if (tPreEmpFamilyList != null) {
				// 先删除其他信息
				tEmpFamilyService.deleteByEmpId(empId);
				TEmpFamily tEmpFamily;
				for (TPreEmpFamily tPreEmpFamily : tPreEmpFamilyList) {
					tEmpFamily = new TEmpFamily();
					BeanUtil.copyProperties(tPreEmpFamily, tEmpFamily, ID);
					tEmpFamily.setEmpId(empId);
					tEmpFamily.setDeleteFlag(CommonConstants.STATUS_NORMAL);
					tEmpFamily.setEmpCode(emp.getEmpCode());
					tEmpFamily.setEmpName(emp.getEmpName());
					tEmpFamily.setEmpIdcard(emp.getEmpIdcard());
					if (Common.isNotNull(tPreEmpFamily.getOldId())) {
						tEmpFamily.setId(tPreEmpFamily.getOldId());
					}

					if (Common.isEmpty(tEmpFamily.getCreateBy())) {
						tEmpFamily.setCreateBy(user.getId());
						tEmpFamily.setCreateName(user.getNickname());
						tEmpFamily.setCreateTime(LocalDateTime.now());
					}
					tEmpFamilyService.save(tEmpFamily);
				}
			}
			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualificationList = vo.getTpreEmpProfessionalQualificationList();
			// 先删除其他信息
			tEmpProfessionalService.deleteProfessionalByEmpId(empId);
			if (tPreEmpProfessionalQualificationList != null
					&& (Common.isEmpty(emp.getHaveQualification()) || CommonConstants.ZERO_STRING.equals(emp.getHaveQualification()))) {
				TEmpProfessionalQualification info;
				for (TPreEmpProfessionalQualification preInfo : tPreEmpProfessionalQualificationList) {
					info = new TEmpProfessionalQualification();
					BeanUtil.copyProperties(preInfo, info, ID);
					info.setDeleteFlag(CommonConstants.STATUS_NORMAL);
					info.setEmpId(empId);
					info.setEmpCode(emp.getEmpCode());
					info.setEmpName(emp.getEmpName());
					info.setEmpIdcard(emp.getEmpIdcard());
					if (Common.isNotNull(preInfo.getOldId())) {
						info.setId(preInfo.getOldId());
					}

					if (Common.isEmpty(info.getCreateBy())) {
						info.setCreateBy(user.getId());
						info.setCreateName(user.getNickname());
						info.setCreateTime(LocalDateTime.now());
					}
					tEmpProfessionalService.save(info);
					if (preInfo.getAttaList() != null && !preInfo.getAttaList().isEmpty()) {
						List<TAttaInfo> attaList = preInfo.getAttaList();
						if (attaList != null) {
							String attaId = preInfo.getOldId();
							tAttaInfoService.deleteByDomainIdAndType(attaId, 1);
							TAttaInfo newEmpAtta;
							for (TAttaInfo atta : attaList) {
								newEmpAtta = new TAttaInfo();
								BeanUtil.copyProperties(atta, newEmpAtta, ID);
								newEmpAtta.setDomainId(info.getId());

								if (Common.isEmpty(atta.getCreateBy())) {
									atta.setCreateBy(user.getId());
									atta.setCreateName(user.getNickname());
									atta.setCreateTime(LocalDateTime.now());
								}
								tAttaInfoService.saveOrUpdate(newEmpAtta);
							}
						}
					}
				}
			}

		}
		// 预入职-其他附件
		List<TPreEmpOtherFile> preEmpOtherFileList = vo.getTpreEmpOtherFileList();
		// 先删除其他信息
		tEmpOtherFileService.deleteOtherFileByEmpId(empId);
		if (preEmpOtherFileList != null && !preEmpOtherFileList.isEmpty()) {
			TEmpOtherFile info;
			for (TPreEmpOtherFile preInfo : preEmpOtherFileList) {
				info = new TEmpOtherFile();
				BeanUtil.copyProperties(preInfo, info, ID);
				info.setEmpId(empId);
				if (Common.isNotNull(preInfo.getOldId())) {
					info.setId(preInfo.getOldId());
				}
				tEmpOtherFileService.save(info);
				if (preInfo.getAttaList() != null && !preInfo.getAttaList().isEmpty()) {
					List<TAttaInfo> attaList = preInfo.getAttaList();
					if (attaList != null) {
						String attaId = preInfo.getOldId();
						tAttaInfoService.deleteByDomainIdAndType(attaId, 2);
						TAttaInfo newEmpAtta;
						for (TAttaInfo atta : attaList) {
							newEmpAtta = new TAttaInfo();
							BeanUtil.copyProperties(atta, newEmpAtta, ID);
							newEmpAtta.setDomainId(info.getId());
							if (Common.isEmpty(atta.getCreateBy())) {
								atta.setCreateBy(user.getId());
								atta.setCreateName(user.getNickname());
								atta.setCreateTime(LocalDateTime.now());
							}
							if (Common.isEmpty(atta.getAttaName())) {
								atta.setAttaName(preInfo.getAttaName());
							}
							tAttaInfoService.saveOrUpdate(newEmpAtta);
						}
					}
				}
			}
		}
		// 预入职-员工工作履历信息表
		if (!isSimpleBoo) {
			List<TPreEmpWorkRecording> tPreEmpWorkRecordingList = vo.getTpreEmpWorkRecordingList();
			// 先删除其他信息
			tEmpWorkRecordingService.deleteWorkRecordByEmpId(empId);
			if (tPreEmpWorkRecordingList != null && (Common.isEmpty(emp.getFirstWorkFlag()) || CommonConstants.ONE_STRING.equals(emp.getFirstWorkFlag()))) {
				TEmpWorkRecording info;
				for (TPreEmpWorkRecording preInfo : tPreEmpWorkRecordingList) {
					info = new TEmpWorkRecording();
					BeanUtil.copyProperties(preInfo, info, ID);
					info.setDeleteFlag(CommonConstants.STATUS_NORMAL);
					info.setEmpId(empId);
					info.setEmpCode(emp.getEmpCode());
					info.setEmpName(emp.getEmpName());
					info.setEmpIdcard(emp.getEmpIdcard());

					if (Common.isEmpty(info.getCreateBy())) {
						info.setCreateBy(user.getId());
						info.setCreateName(user.getNickname());
						info.setCreateTime(LocalDateTime.now());
					}
					if (Common.isNotNull(preInfo.getOldId())) {
						info.setId(preInfo.getOldId());
					}
					tEmpWorkRecordingService.save(info);
				}
			}
		}
		// 预入职-附件
		List<TAttaInfo> attaList = vo.getAttaInfoList();
		if (attaList != null) {
			// 先删除其他信息
			if (!isSimpleBoo) {
				tAttaInfoService.deleteByDomainIdAndOther(empId);
			} else {
				// 简档，仅删除身份证附件和(21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文)
				tAttaInfoService.deleteByDomainIdCard(empId);
			}
			TAttaInfo attaEmp;
			List<TAttaInfo> attaEmpList = new ArrayList<>();
			for (TAttaInfo atta : attaList) {
				attaEmp = new TAttaInfo();
				BeanUtil.copyProperties(atta, attaEmp, ID);
				attaEmp.setDomainId(empId);
				attaEmp.setCreateBy(user.getId());
				attaEmp.setCreateName(user.getNickname());
				attaEmp.setCreateTime(LocalDateTime.now());
				attaEmpList.add(attaEmp);
			}
			tAttaInfoService.saveBatch(attaEmpList);
		}
		return R.ok("成功！");
	}

	// 2新增或更新项目
	private TEmployeeProject saveTEmployeeProject(TEmployeeProject project, YifuUser user, TPreEmployeeProject tPreEmployeeProject, TEmployeeInfo emp, TSettleDomain dept) {
		boolean isNew;
		if (Common.isNotNull(tPreEmployeeProject.getEmpIdcard()) && Common.isNotNull(tPreEmployeeProject.getDeptId())) {
			project = tEmployeeProjectService.getByEmpIdCardAndDeptId(tPreEmployeeProject.getEmpIdcard(), tPreEmployeeProject.getDeptId());
			if (project == null) {
				project = tEmployeeProjectService.getByEmpIdCardAndDeptIdAndDelete(tPreEmployeeProject.getEmpIdcard(), tPreEmployeeProject.getDeptId());
				if (project != null) {
					project.setCreateTime(LocalDateTime.now());
					project.setProjectStatus(CommonConstants.ZERO_INT);
					project.setProjectSource(CommonConstants.EIGHT_STRING);
					project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
				}
			} else if (CommonConstants.ONE_INT == project.getProjectStatus()) {
				project.setCreateTime(LocalDateTime.now());
				project.setProjectStatus(CommonConstants.ZERO_INT);
			}
			isNew = false;
			if (project == null) {
				isNew = true;
				project = new TEmployeeProject();
			}
			if (Common.isEmpty(tPreEmployeeProject.getWorkingHours())) {
				tPreEmployeeProject.setWorkingHours("");
			}
			if (Common.isEmpty(tPreEmployeeProject.getPost())) {
				tPreEmployeeProject.setPost("");
			}
			if (Common.isEmpty(tPreEmployeeProject.getTryPeriod())) {
				tPreEmployeeProject.setTryPeriod("");
			}
			// 2024-7-23 11:52:33 金龙弟预张倩倩认为不同步项目的合同信息
			//String] ignoreProperties = new String]"id", "contractType", "workingHours", "post", "enjoinDate", "tryPeriod"
			// 2025-3-27 15:13:30 张倩倩认为要同步项目的合同信息
			String[] ignoreProperties = new String[]{"id", "workingHours", "tryPeriod"};

			Integer oldDeptContractStatus = project.getContractStatus();
			Integer oldDeptSocialStatus = project.getSocialStatus();
			Integer oldDeptFundStatus = project.getFundStatus();
			Integer oldDeptInsuranceStatus = project.getInsuranceStatus();
			Integer oldDeptSocialProvince = project.getSocialProvince();
			Integer oldDeptSocialCity = project.getSocialCity();
			Integer oldDeptSocialTown = project.getSocialTown();

			BeanUtil.copyProperties(tPreEmployeeProject, project, ignoreProperties);
			if (Common.isEmpty(project.getStatus())) {
				project.setStatus(CommonConstants.ZERO_INT);
			}
			if (Common.isEmpty(project.getEmpId()) && emp != null) {
				project.setEmpId(emp.getId());
			}
			if (isNew) {
				// 新项目档案塞基本属性
				this.setNewEmpProjectBaseData(project, emp, dept, user);
			}
			if (Common.isNotNull(oldDeptContractStatus) && oldDeptContractStatus != 0) {
				project.setContractStatus(oldDeptContractStatus);
			}
			if (Common.isNotNull(oldDeptSocialStatus) && oldDeptSocialStatus != 0) {
				project.setSocialStatus(oldDeptSocialStatus);
			}
			if (Common.isNotNull(oldDeptFundStatus) && oldDeptFundStatus != 0) {
				project.setFundStatus(oldDeptFundStatus);
			}
			if (Common.isNotNull(oldDeptInsuranceStatus) && oldDeptInsuranceStatus != 0) {
				project.setInsuranceStatus(oldDeptInsuranceStatus);
			}
			// 2026-03-24 段说要不更新社保省市县
			if (Common.isNotNull(oldDeptSocialProvince)) {
				project.setSocialProvince(oldDeptSocialProvince);
				project.setSocialCity(oldDeptSocialCity);
				project.setSocialTown(oldDeptSocialTown);
			}
			tEmployeeProjectService.saveOrUpdate(project);
		}
		return project;
	}

	// 1新增档案
	private TEmployeeInfo saveTEmployeeInfo(YifuUser user, TPreEmployeeInfo tPreEmployeeInfo) {
		TEmployeeInfo emp = tEmployeeInfoService.getInfoByIdcard(tPreEmployeeInfo.getEmpIdcard());
		if (emp == null) {
			emp = tEmployeeInfoService.getInfoByDelete(tPreEmployeeInfo.getEmpIdcard());
			if (emp != null) {
				emp.setCreateTime(LocalDateTime.now());
				emp.setFileStatus(CommonConstants.ZERO_INT);
				emp.setDeleteFlag(CommonConstants.STATUS_NORMAL);
			}
		} else if (CommonConstants.ONE_INT == emp.getFileStatus()) {
			emp.setCreateTime(LocalDateTime.now());
			emp.setFileStatus(CommonConstants.ZERO_INT);
		}
		boolean isNew = false;
		if (emp == null) {
			isNew = true;
			emp = new TEmployeeInfo();
		}
		String empCode = emp.getEmpCode();
		// 检查人员档案的合同社保公积金状态，如果不是初始状态则不更新
		Integer oldContractStatus = emp.getContractStatus();
		Integer oldSocialStatus = emp.getSocialStatus();
		Integer oldFundStatus = emp.getFundStatus();
		Integer oldInsuranceStatus = emp.getInsuranceStatus();
		BeanUtil.copyProperties(tPreEmployeeInfo, emp, ID);
		if (Common.isEmpty(emp.getEmpCode()) && Common.isNotNull(empCode)) {
			emp.setEmpCode(empCode);
		}
		if (Common.isEmpty(emp.getEmpCode())) {
			emp.setEmpCode(tEmployeeInfoService.getCode());
		}
		emp.setFileStatus(CommonConstants.ZERO_INT);
		emp.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		if (isNew) {
			// 新员工塞基本属性
			this.setNewEmpBaseData(emp, user);
		}
		emp.setFileStatus(CommonConstants.ZERO_INT);

		if (Common.isNotNull(oldContractStatus) && oldContractStatus != 0) {
			emp.setContractStatus(oldContractStatus);
		}
		if (Common.isNotNull(oldSocialStatus) && oldSocialStatus != 0) {
			emp.setSocialStatus(oldSocialStatus);
		}
		if (Common.isNotNull(oldFundStatus) && oldFundStatus != 0) {
			emp.setFundStatus(oldFundStatus);
		}
		if (Common.isNotNull(oldInsuranceStatus) && oldInsuranceStatus != 0) {
			emp.setInsuranceStatus(oldInsuranceStatus);
		}
		tEmployeeInfoService.saveOrUpdate(emp);
		return emp;
	}

	/**
	 * @Description: 新员工塞基本信息
	 * @Author: hgw
	 * @Date: 2024/6/19 14:26
	 * @return: void
	 **/
	private void setNewEmpBaseData(TEmployeeInfo employeeInfo, YifuUser user) {
		// 新增档案
		employeeInfo.setEmpCode(tEmployeeInfoService.getCode());
		employeeInfo.setCreateBy(user.getId());
		employeeInfo.setCreateName(user.getNickname());
		employeeInfo.setCreateTime(LocalDateTime.now());

		employeeInfo.setFileSource(CommonConstants.SEVEN_STRING);
		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);
	}

	/**
	 * @Description: 新员工塞基本项目档案信息
	 * @Author: hgw
	 * @Date: 2024/6/19 14:26
	 * @return: void
	 **/
	private void setNewEmpProjectBaseData(TEmployeeProject insTEmployeePro, TEmployeeInfo tEmployeeInfo, TSettleDomain tSettleDomain, YifuUser user) {
		// 新增档案
		insTEmployeePro.setId(String.valueOf(UUID.randomUUID()).replace("-", ""));
		insTEmployeePro.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		insTEmployeePro.setStatus(CommonConstants.ZERO_INT);

		//获取项目和单位信息
		if (Common.isNotNull(tSettleDomain)) {
			insTEmployeePro.setDeptId(tSettleDomain.getId());
			insTEmployeePro.setDeptName(tSettleDomain.getDepartName());
			insTEmployeePro.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
			insTEmployeePro.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
			insTEmployeePro.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
			insTEmployeePro.setUnitId(tSettleDomain.getCustomerId());
			insTEmployeePro.setUnitNo(tSettleDomain.getCustomerNo());
			insTEmployeePro.setUnitName(tSettleDomain.getCustomerName());
			String empNO = tEmployeeProjectService.getEmpNo(insTEmployeePro.getDeptNo());
			insTEmployeePro.setEmpNo(empNO);
		}
		//员工编码生成规则
		if (tEmployeeInfo != null) {
			insTEmployeePro.setEmpId(tEmployeeInfo.getId());
			insTEmployeePro.setEmpName(tEmployeeInfo.getEmpName());
			insTEmployeePro.setEmpCode(tEmployeeInfo.getEmpCode());
		}
		insTEmployeePro.setCreateBy(user.getId());
		insTEmployeePro.setCreateTime(LocalDateTime.now());
		insTEmployeePro.setCreateName(user.getNickname());
		insTEmployeePro.setProjectSource(CommonConstants.EIGHT_STRING);

	}


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

			// 出生日期
			java.sql.Date empBirthday = com.yifu.cloud.plus.v1.yifu.archives.util.IdCardUtil.getBirthdate(idCard);
			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));
		}
	}

	/**
	 * 预入职-主表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TPreEmpMainSearchVo searchVo) {
		String fileName = "预入职导出主表" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TPreEmpMain> list = new ArrayList<>();
		long count = baseMapper.getTPreEmpMainCount(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, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcelFactory.write(out, TPreEmpMain.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.getTPreEmpMainList(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TPreEmpMain> util = new ExcelUtil<>(TPreEmpMain.class);
						for (TPreEmpMain vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet("预入职-主表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.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);
			}
		}
	}

	@Override
	public List<TPreEmpMain> noPageDiy(TPreEmpMainSearchVo searchVo) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TPreEmpMain::getId, idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	private LambdaQueryWrapper<TPreEmpMain> buildQueryWrapper(TPreEmpMainSearchVo entity) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimeStart())) {
			wrapper.ge(TPreEmpMain::getCreateTime, entity.getCreateTimeStart());
		}
		if (ArrayUtil.isNotEmpty(entity.getCreateTimeEnd())) {
			wrapper.le(TPreEmpMain::getCreateTime, entity.getCreateTimeEnd());
		}
		if (Common.isNotNull(entity.getStatusArray())) {
			wrapper.in(TPreEmpMain::getStatus, entity.getStatusArray());
		}
		if (Common.isNotNull(entity.getEmpNatureArray())) {
			wrapper.in(TPreEmpMain::getEmpNatrue, entity.getEmpNatureArray());
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TPreEmpMain::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

	/**
	 * @Description: 批量完善信息
	 * @Author: hgw
	 * @Date: 2024/6/21 15:26
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage>>
	 **/
	@Override
	public R<List<ErrorMessage<String>>> importDiy(InputStream inputStream) {
		List<ErrorMessage<String>> errorMessageList = new ArrayList<>();
		ExcelUtil<TPreEmpMainVo> util1 = new ExcelUtil<>(TPreEmpMainVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcelFactory.read(inputStream, TPreEmpMainVo.class, new ReadListener<TPreEmpMainVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TPreEmpMainVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TPreEmpMainVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage<String> errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessageList.add(errorMessage);
					} 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());
					importTPreEmpMain(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 void importTPreEmpMain(List<TPreEmpMainVo> excelVOList, List<ErrorMessage<String>> errorMessageList) {
		TPreEmpMain main;
		TPreEmployeeInfo employee;
		TPreEmployeeProject project;
		// 执行数据插入操作 组装
		for (TPreEmpMainVo excel : excelVOList) {
			if (Common.isEmpty(excel.getDeptNo()) || Common.isEmpty(excel.getEmpIdcard()) || Common.isEmpty(excel.getEmpNatrue()) || Common.isEmpty(excel.getFileProvince())) {
				errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "完善信息不可为空！"));
			} else {
				// 插入
				main = baseMapper.getTPreEmpMainByCardAndDeptNo(excel.getEmpIdcard(), excel.getDeptNo());
				if (main == null || Common.isEmpty(main.getId()) || Common.isEmpty(main.getStatus())) {
					errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "未找到预入职主表！"));
				} else {
					if (!CommonConstants.ONE_STRING.equals(main.getStatus())) {
						errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "状态不为待完善，不可编辑！"));
					} else {
						employee = tPreEmployeeInfoService.getTPreEmployeeInfoList(main.getId());
						if (employee == null || Common.isEmpty(employee.getId())) {
							errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "未找到预入职人员表！"));
						} else {
							project = tPreEmployeeProjectService.getTPreEmployeeProjectList(main.getId());
							if (project == null || Common.isEmpty(project.getId())) {
								errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "未找到预入职项目档案表！"));
							} else {
								if (Common.isNotNull(employee.getBankNo()) && Common.isEmpty(excel.getTaxMonth())) {
									errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "有银行卡号，计税月份必填！"));
									continue;
								}
								if (Common.isNotNull(excel.getTaxMonth())) {
									String taxMonth = excel.getTaxMonth().trim();
									if (!taxMonth.matches(TAX_MONTH_REGEX)) {
										errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "计税月份为6位年月，例如：202407！"));
										continue;
									}
									if (Common.isEmpty(employee.getTaxMonthFlag()) || CommonConstants.ONE_STRING.equals(employee.getTaxMonthFlag())) {
										employee.setTaxMonth(excel.getTaxMonth());
									}
								}
								employee.setEmpNatrue(excel.getEmpNatrue());
								project.setEmpNatrue(excel.getEmpNatrue());
								employee.setFileProvince(Integer.parseInt(excel.getFileProvince()));
								if (Common.isEmpty(excel.getFileCity())) {
									employee.setFileCity(CommonConstants.ZERO_INT);
								} else {
									try {
										employee.setFileCity(Integer.parseInt(excel.getFileCity()));
									} catch (Exception e) {
										errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "未找到市！"));
										continue;
									}
								}
								if (Common.isEmpty(excel.getFileTown())) {
									employee.setFileTown(CommonConstants.ZERO_INT);
								} else {
									try {
										employee.setFileTown(Integer.parseInt(excel.getFileTown()));
									} catch (Exception e) {
										//errorMessageList.add(new ErrorMessage<>(excel.getRowIndex(), "未找到县！")); 2024-09-26 mvp1.6.11 预入职档案地区县选填
										throw new RuntimeException("档案地址-区/县转换异常");
									}
								}
								tPreEmployeeInfoService.updateById(employee);
								tPreEmployeeProjectService.updateById(project);
								main.setEmpNatrue(excel.getEmpNatrue());
								// PC导入的，不更新为待审核
								if (Common.isEmpty(main.getSourType()) || CommonConstants.ZERO_STRING.equals(main.getSourType())) {
									main.setStatus(CommonConstants.TWO_STRING);
								}
								this.updateById(main);
							}
						}
					}
				}
			}
		}
	}

	@Override
	@Transactional
	public R<String> doAudit(String id, String status, String auditRemark) {
		if (Common.isEmpty(id) && Common.isEmpty(status)) {
			return R.failed("id、status不可为空！");
		}
		TPreEmpMain preEmpMain = this.getById(id);
		if (preEmpMain == null || Common.isEmpty(preEmpMain.getStatus()) || !CommonConstants.TWO_STRING.equals(preEmpMain.getStatus())) {
			return R.failed("请确认预入职状态！");
		}
		try {
			if (!CommonConstants.THREE_STRING.equals(status) && !CommonConstants.FOUR_STRING.equals(status)) {
				return R.failed("审核状态不对！");
			}
			if (CommonConstants.THREE_STRING.equals(status) && Common.isEmpty(auditRemark)) {
				return R.failed("审核不通过，原因必填！");
			}
			YifuUser user = SecurityUtils.getUser();
			if (user == null || Common.isEmpty(user.getId())) {
				return R.failed("未找到登录信息！");
			}
			preEmpMain.setStatus(status);
			preEmpMain.setAuditId(user.getId());
			preEmpMain.setAuditRemark(auditRemark);
			preEmpMain.setAuditName(user.getNickname());
			// 2024-9-6 17:32:00 倩倩与 王成沟通，变更为审核时间，且审核通过与不通过的时候显示
			preEmpMain.setAuditTime(new Date());

			// 审核日志
			TPreEmpMainLog auditLog = new TPreEmpMainLog();
			auditLog.setAuditId(user.getId());
			auditLog.setAuditName(user.getNickname());
			auditLog.setAuditTime(new Date());
			auditLog.setAuditRemark(auditRemark);
			auditLog.setMainId(preEmpMain.getId());
			auditLog.setAuditResult(status);

			R<PreEmpMainDetailVo> voR = this.getInfoById(id);
			if (voR != null && voR.getCode() == CommonConstants.SUCCESS) {
				// 转到更新档案去
				PreEmpMainDetailVo vo = voR.getData();
				tPreEmpMainLogService.save(auditLog);
				this.updateById(preEmpMain);
				if (CommonConstants.THREE_STRING.equals(status)) {
					// 更新入职待建档状态为信息待填写
					registrationPreService.updatePreStatusToOne(preEmpMain.getDeptNo(),preEmpMain.getEmpIdcard());
				}
				if (CommonConstants.FOUR_STRING.equals(status)) {
					// true 简档
					boolean isSimpleBoo = false;
					if (Common.isNotNull(preEmpMain.getIsSimple()) && CommonConstants.TWO_STRING.equals(preEmpMain.getIsSimple())) {
						isSimpleBoo = true;
					}
					return updateToEmployeeByPre(vo, isSimpleBoo);
				} else {
					return R.ok("已审核");
				}
			} else {
				return R.failed("未找到信息，未审核！");
			}
		} catch (Exception e) {
			log.error("档案预入职审核异常：", e);
			throw new RuntimeException("保存失败，请联系管理员！！预入职主键【" + preEmpMain.getId() + "】");
		}

	}

	@Override
	public R<List<ErrorVO>> doBatchAudit(List<String> ids, String status, String auditRemark) {
		if (Common.isEmpty(ids) && Common.isEmpty(status)) {
			return R.failed("id、status不可为空！");
		}
		if (!CommonConstants.THREE_STRING.equals(status) && !CommonConstants.FOUR_STRING.equals(status)) {
			return R.failed("审核状态不对！");
		}
		if (CommonConstants.THREE_STRING.equals(status) && Common.isEmpty(auditRemark)) {
			return R.failed("审核不通过，原因必填！");
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed("未找到登录信息！");
		}
		List<ErrorVO> returnList = new ArrayList<>();
		TPreEmpMain preEmpMain;
		ErrorVO errorVo;
		int i = 1;
		boolean isTrue = true;
		for (String id : ids) {
			errorVo = new ErrorVO();
			errorVo.setResult(CommonConstants.ZERO_INT);
			errorVo.setLineNum(i++);
			preEmpMain = this.getById(id);
			if (preEmpMain == null || Common.isEmpty(preEmpMain.getStatus()) || !CommonConstants.TWO_STRING.equals(preEmpMain.getStatus())) {
				errorVo.setErrorInfo("请确认预入职状态！");
				returnList.add(errorVo);
				isTrue = false;
			} else {
				errorVo.setResult(CommonConstants.ONE_INT);
				errorVo.setMainName(preEmpMain.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + preEmpMain.getDeptNo());
				returnList.add(errorVo);
				preEmpMain.setStatus(status);
				preEmpMain.setAuditId(user.getId());
				preEmpMain.setAuditRemark(auditRemark);
				preEmpMain.setAuditName(user.getNickname());
				if (CommonConstants.FOUR_STRING.equals(status)) {
					preEmpMain.setAuditTime(new Date());
				}

				// 审核日志
				TPreEmpMainLog auditLog = new TPreEmpMainLog();
				auditLog.setAuditId(user.getId());
				auditLog.setAuditName(user.getNickname());
				auditLog.setAuditTime(new Date());
				auditLog.setAuditRemark(auditRemark);
				auditLog.setMainId(preEmpMain.getId());
				auditLog.setAuditResult(status);

				R<PreEmpMainDetailVo> voR = this.getInfoById(id);
				PreEmpMainDetailVo vo = null;
				if (voR != null && voR.getCode() == CommonConstants.SUCCESS) {
					// 转到更新档案去
					vo = voR.getData();
					this.updateById(preEmpMain);
					tPreEmpMainLogService.save(auditLog);
					if (CommonConstants.FOUR_STRING.equals(status)) {
						// true 简档
						boolean isSimpleBoo = false;
						if (Common.isNotNull(preEmpMain.getIsSimple()) && CommonConstants.TWO_STRING.equals(preEmpMain.getIsSimple())) {
							isSimpleBoo = true;
						}
						updateToEmployeeByPre(vo, isSimpleBoo);
					}
				}
			}
		}
		if (isTrue) {
			return R.ok(returnList);
		} else {
			return R.failed(returnList);
		}
	}

	private List<String> getNewArrayList(String[] strArr) {
		return Arrays.asList(strArr);
	}


	@Override
	public void exportAll(HttpServletResponse response, TPreEmpMainSearchVo searchVo) {
		TArchivesLimit archivesLimit = tArchivesLimitMapper.selectById(CommonConstants.THREE_INT);
		Integer preMaxLimit = 2;
		if (Common.isNotNull(archivesLimit) && Common.isNotNull(archivesLimit.getMaxNum())) {
			preMaxLimit = archivesLimit.getMaxNum();
		}
		if (preExportAtomicInteger.incrementAndGet() <= preMaxLimit) {
			try {
				exportAllCore(response, searchVo);
			} catch (Exception e) {
				log.error("导出异常：", e);
			} finally {
				preExportAtomicInteger.decrementAndGet();
			}
		} else {
			// 前面做了+1（atomicInteger.incrementAndGet()）这里也要-1
			preExportAtomicInteger.decrementAndGet();
			log.error("预入职导出超出阈值：" + ResultConstants.FILE_DOWN_LOAD_DATA);
			exportError(response, ResultConstants.FILE_DOWN_LOAD_DATA);
		}
	}

	private void exportError(HttpServletResponse response, String errorMessage) {
		String fileName = "导出异常" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<ExportErrorVo> list = new ArrayList<>();
		list.add(new ExportErrorVo(errorMessage));
		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 = EasyExcelFactory.write(out, ExportErrorVo.class).build();
			int index = 0;
			WriteSheet writeSheet = EasyExcelFactory.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);
			}
		}
	}

	/**
	 * 预入职导出全量
	 *
	 * @return
	 */
	private void exportAllCore(HttpServletResponse response, TPreEmpMainSearchVo searchVo) {

		YifuUser user = SecurityUtils.getUser();
		if (user != null) {
			TArchivesExportLimit exportLimit = new TArchivesExportLimit();
			exportLimit.setType(CommonConstants.ONE_INT);
			exportLimit.setCreateBy(user.getId());
			String name = "预入职导出全量";
			String fileName = name + DateUtil.getThisTime() + ".xlsx";
			//获取要导出的列表
			List<TPreMainExportAllVO> list = Lists.newArrayList();
			long count = baseMapper.getTPreEmpMainAllCount(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, CommonConstants.UTF8));
				ExcelWriter excelWriter = null;
				if (count > 200000) {
					exportError(response, "数据超过20万条，请联系管理员后端导出预入职");
				} else {
					exportLimit.setDeleteFlag(CommonConstants.ZERO_INT);
					exportLimit.setCreateName(user.getNickname());
					exportLimit.setCreateTime(LocalDateTime.now());
					tArchivesExportLimitMapper.insert(exportLimit);

					// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
					List<List<String>> headList = Lists.newArrayList();
					headList.add(this.getNewArrayList(new String[]{"提交时间", "提交时间"}));
					headList.add(this.getNewArrayList(new String[]{"状态", "状态"}));
					headList.add(this.getNewArrayList(new String[]{"审核人", "审核人"}));
					headList.add(this.getNewArrayList(new String[]{"审核时间", "审核时间"}));
					String oneTitle = "员工基本信息";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "员工主码"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "员工类型"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "员工姓名"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "身份证号"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "性别"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "身份证期限"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "身份证开始日期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "身份证截止日期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "出生日期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "年龄"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "婚姻状况"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "民族"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "政治面貌"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "手机号码"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "邮箱"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "户籍所在地-省"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "户籍所在地-市"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "户籍所在地-区/县"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "户口性质"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "档案所在地-省"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "档案所在地-市"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "档案所在地-区/县"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "档案状态"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "通信地址-省"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "通信地址-市"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "通信地址-区/县"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "通信地址-详细地址"}));
					oneTitle = "在项信息";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "客户名称"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "项目名称"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "业务类型"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "合同类型"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "工时制"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "就职岗位"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "入职日期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "试用期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "标签"}));
					oneTitle = "紧急联络人";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "姓名"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "与本人关系"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "联系地址"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "联系电话"}));
					oneTitle = "最高教育经历";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "学校"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "专业"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "学历"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否大专及以上"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "最高学历"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "入学时间"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "毕业时间"}));
					oneTitle = "主要工作经历";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否为首份工作"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "工作单位"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "工作岗位"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "开始工作日期"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "结束工作日期"}));
					oneTitle = "主要家庭成员信息";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "成员姓名"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "与本人关系"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "手机号码"}));
					oneTitle = "职业资格信息";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否有职业资格证书"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "申报年度"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "职业资格名称"}));
					oneTitle = "伤残信息";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否曾被认定为工伤"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否有职业病"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "职业病名称"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否有传染性疾病"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "传染病名称"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否持有残疾人证明"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "伤残病名称"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "伤残等级"}));
					headList.add(this.getNewArrayList(new String[]{oneTitle, "是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种"}));
					oneTitle = "不良记录";
					headList.add(this.getNewArrayList(new String[]{oneTitle, "不良记录描述"}));

					Set<String> titleContent = getExportFieldNameDetailByClass(TPreMainExportAllVO.class);
					// 获取所有字典type
					Map<String,String> nameAndDicTypeMap = getConverterDicTypeAndArea(TPreMainExportAllVO.class);
					// 获取所有字典对应的值
					Map<String,String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
					Map<String,String> idLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.AREA_VALUE_ALL);
					if (Common.isEmpty(idLabelMap) || idLabelMap.isEmpty()) {
						R<AreaMap> areaListR = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
								, "/area/inner/getAreaMapAll", "", AreaMap.class, SecurityConstants.FROM_IN);
						if (Common.isNotNull(areaListR)) {
							idLabelMap = areaListR.getData().getIdLabelMap();
						}
					}
					if (redisLabelMap != null && idLabelMap != null) {
						redisLabelMap.putAll(idLabelMap);
					}
					excelWriter = EasyExcelFactory.write(out).registerWriteHandler(ExcelStyle.getNormalStype())
							.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
							.includeColumnFieldNames(titleContent).head(headList).build();
					int index = 1;
					if (count > CommonConstants.ZERO_INT) {
						//int limitNum = CommonConstants.EXCEL_EXPORT_LIMIT
						int limitNum = 10000;
						ExcelWriterSheetBuilder writeSheet;
						List<TPreMainExportAllVO> listWork;
						Map<String, TPreMainExportAllVO> mapWork;
						List<TPreMainExportAllVO> listFamily;
						Map<String, TPreMainExportAllVO> mapFamily;
						List<TPreMainExportAllVO> listProfessional;
						Map<String, TPreMainExportAllVO> mapProfessional;
						TPreMainExportAllVO temp;
						List<String> preMainIdList;
						for (int i = 0; i <= count; i += limitNum) {
							exportLimit.setProgressBar("导出预入职进度："+i+"/"+count);
							tArchivesExportLimitMapper.updateById(exportLimit);
							preMainIdList = new ArrayList<>();
							// 获取实际记录
							searchVo.setLimitStart(i);
							searchVo.setLimitEnd(limitNum);
							list = baseMapper.getTPreEmpMainAllList(searchVo);
							if (list != null && !list.isEmpty()) {
								for (TPreMainExportAllVO vo : list) {
									preMainIdList.add(vo.getMainId());
								}
								listWork = baseMapper.getTPreEmpMainAllListByWork(preMainIdList);
								listFamily = baseMapper.getTPreEmpMainAllListByFamily(preMainIdList);
								listProfessional = baseMapper.getTPreEmpMainAllListByProfessional(preMainIdList);
								mapWork = new HashMap<>();
								mapFamily = new HashMap<>();
								mapProfessional = new HashMap<>();
								if (listWork != null && !listWork.isEmpty()) {
									for (TPreMainExportAllVO vo : listWork) {
										mapWork.putIfAbsent(vo.getMainId(), vo);
									}
								}
								if (listFamily != null && !listFamily.isEmpty()) {
									for (TPreMainExportAllVO vo : listFamily) {
										mapFamily.putIfAbsent(vo.getMainId(), vo);
									}
								}
								if (listProfessional != null && !listProfessional.isEmpty()) {
									for (TPreMainExportAllVO vo : listProfessional) {
										mapProfessional.putIfAbsent(vo.getMainId(), vo);
									}
								}

								for (TPreMainExportAllVO vo : list) {
									temp = mapWork.get(vo.getMainId());
									if (temp != null) {
										vo.setField44(temp.getField44());
										vo.setField45(temp.getField45());
										vo.setField46(temp.getField46());
										vo.setField47(temp.getField47());
									}
									temp = mapFamily.get(vo.getMainId());
									if (temp != null) {
										vo.setField48(temp.getField48());
										vo.setField49(temp.getField49());
										vo.setField50(temp.getField50());
									}
									temp = mapProfessional.get(vo.getMainId());
									if (temp != null) {
										vo.setField52(temp.getField52());
										vo.setField53(temp.getField53());
									}
								}
								writeSheet = EasyExcelFactory.writerSheet(name + index).includeColumnFieldNames(titleContent);
								excelWriter.write(list, writeSheet.build());
								index++;
							}
							if (Common.isNotNull(list)) {
								list.clear();
							}
						}

						// 1工作经历
						index = 1;
						count = baseMapper.getTEmpMainAllCountOneWork(searchVo);
						for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
							// 获取实际记录
							searchVo.setLimitStart(i);
							searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
							list = baseMapper.getTEmpMainAllListOneWork(searchVo);
							if (Common.isNotNull(list)) {
								writeSheet = EasyExcelFactory.writerSheet("工作经历" + index).includeColumnFieldNames(titleContent);
								excelWriter.write(list, writeSheet.build());
								index++;
							}
							if (Common.isNotNull(list)) {
								list.clear();
							}
						}
						// 2家庭成员
						index = 1;
						count = baseMapper.getTEmpMainAllCountTwoFamily(searchVo);
						for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
							// 获取实际记录
							searchVo.setLimitStart(i);
							searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
							list = baseMapper.getTEmpMainAllListTwoFamily(searchVo);
							if (Common.isNotNull(list)) {
								writeSheet = EasyExcelFactory.writerSheet("家庭成员" + index).includeColumnFieldNames(titleContent);
								excelWriter.write(list, writeSheet.build());
								index++;
							}
							if (Common.isNotNull(list)) {
								list.clear();
							}
						}
						// 3职业资格
						index = 1;
						count = baseMapper.getTEmpMainAllCountThreeProfessional(searchVo);
						for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
							// 获取实际记录
							searchVo.setLimitStart(i);
							searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
							list = baseMapper.getTEmpMainAllListThreeProfessional(searchVo);
							if (Common.isNotNull(list)) {
								writeSheet = EasyExcelFactory.writerSheet("职业资格" + index).includeColumnFieldNames(titleContent);
								excelWriter.write(list, writeSheet.build());
								index++;
							}
							if (Common.isNotNull(list)) {
								list.clear();
							}
						}

					} else {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet(name + index).build();
						excelWriter.write(list, writeSheet);
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
				out.flush();
				if (excelWriter != null) {
					excelWriter.finish();
				}
			} catch (Exception e) {
				log.error("执行异常", e);
			} finally {
				try {
					// 结束后将状态更新为已导出
					exportLimit.setDeleteFlag(CommonConstants.ONE_INT);
					exportLimit.setUpdateBy(user.getNickname());
					exportLimit.setUpdateTime(LocalDateTime.now());
					tArchivesExportLimitMapper.updateById(exportLimit);
					if (null != out) {
						out.close();
					}
				} catch (IOException e) {
					log.error("执行异常", e);
				}
			}
		}
	}

	private Set<String> getExportFieldNameDetailByClass(Class<?> clazz) {
		Set<String> exportfieldsName = new HashSet<>();
		Field[] fields = clazz.getDeclaredFields();
		ExcelAttribute annotation;
		for (Field field : fields) {
			annotation = field.getAnnotation(ExcelAttribute.class);
			if (annotation != null && Common.isNotNull(annotation.name()) && annotation.needExport()) {
				exportfieldsName.add(field.getName());
			}
		}
		return exportfieldsName;
	}

	private Map<String,String> getConverterDicTypeAndArea(Class<?> clazz) {
		// 得到所有定义字段
		Field[] allFields = clazz.getDeclaredFields();
		Map<String,String> nameDicMap = new HashMap<>();
		List<Field> fields = new ArrayList<>();
		// 将需要字典表头存起来备用，如果没传，则全部翻译
		for (Field field : allFields) {
			if (field.isAnnotationPresent(ExcelAttribute.class)) {
				fields.add(field);
			}
		}
		ExcelAttribute attr;
		Field field;
		for (int j = 0; j < fields.size(); j++) {
			field = fields.get(j);
			attr = field.getAnnotation(ExcelAttribute.class);
			if (Common.isNotNull(field) && Common.isNotNull(attr)){
				if (Common.isNotNull(attr.dataType())) {
					nameDicMap.put(field.getName(), attr.dataType());
				} else if (Common.isNotNull(attr.isArea()) && attr.isArea()) {
					nameDicMap.put(field.getName(), CacheConstants.AREA_VALUE_ALL);
				}
			}
		}
		return nameDicMap;
	}

	@Override
	public R<List<PreUploadEmpImportVo>> uploadPreEmp(MultipartFile file, PreUploadImportParamVo paramVo) throws Exception {
		TArchivesLimit archivesLimit = tArchivesLimitMapper.selectById(CommonConstants.ONE_INT);
		Integer preMaxLimit = 10;
		if (Common.isNotNull(archivesLimit) && Common.isNotNull(archivesLimit.getMaxNum())) {
			preMaxLimit = archivesLimit.getMaxNum();
		}
		if (preImportAtomicInteger.incrementAndGet() <= preMaxLimit) {
			try {
				return uploadPreEmpCore(file, paramVo);
			} catch (Exception e) {
				log.error("导入预入职异常：", e);
			} finally {
				preImportAtomicInteger.decrementAndGet();
			}
		} else {
			// 前面做了+1（atomicInteger.incrementAndGet()）这里也要-1
			preImportAtomicInteger.decrementAndGet();
			log.error("导入预入职超出阈值");
			return R.failed("导入预入职，" + ResultConstants.IMPORT_DOWN_LOAD_DATA);
		}
		return R.failed("导入预入职中，" + ResultConstants.IMPORT_DOWN_LOAD_DATA);
	}

	/**
	 * @param file 文件流
	 * @Description: 导入预入职
	 * @Author: hgw
	 * @Date: 2024/10/12 9:28
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.archives.vo.PreEmpMainDetailVo>>
	 **/
	private R<List<PreUploadEmpImportVo>> uploadPreEmpCore(MultipartFile file, PreUploadImportParamVo paramVo) throws Exception {
		// 自定义解析Excel，判断表头、必填、格式；
		// 按项目查项目人员、档案人员、预入职人员；
		// 有项目人员，仅更新，否则看预入职人员，新增或更新，加导入标签；
		// 返回结果list。

		//对前端传递的文件进行校验
		if (paramVo == null || Common.isEmpty(paramVo.getDeptId())) {
			return R.failed("请前端传参！");
		}
		String deptId = paramVo.getDeptId();
		TSettleDomain dept = tSettleDomainService.getById(deptId);
		if (dept == null || Common.isEmpty(dept.getId())) {
			return R.failed("未找到项目！");
		}
		// 预入职-员工声明
		TPreEmpDeclaration tPreEmpDeclaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
		if (tPreEmpDeclaration == null || Common.isEmpty(tPreEmpDeclaration.getId())) {
			return R.failed("请联系管理员添加员工声明TPreEmpDeclaration数据！");
		}
		String declarId = tPreEmpDeclaration.getId();
		//对前端传递的文件进行校验
		if (file == null || file.isEmpty()) {
			return R.failed("文件为空，重新上传");
		}
		//获取文件名称 判断文件是否为 Execl
		String filename = file.getOriginalFilename();
		if (filename == null || Common.isEmpty(filename)) {
			return R.failed("文件名称为空，请重新上传！");
		}
		if (!(filename.endsWith(".xls") || filename.endsWith(".xlsx"))) {
			return R.failed("文件名称格式有误，请重新上传！" + filename);
		}
		InputStream inputStream = file.getInputStream();
		R<ExcelSheetVo> voR = null;
		ExcelSheetVo vo;
		List<String> specialIdCardList = null;

		R<ListStringVo> specialRes = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl()
				, salaryProperties.getAppId(), "/tsalarystandardoriginal/inner/getSpecialIdCardList", null, ListStringVo.class, SecurityConstants.FROM_IN);
		if (Common.isNotNull(specialRes) && specialRes.getData() != null && specialRes.getData().getListVo() != null){
			specialIdCardList = specialRes.getData().getListVo();
		}

		int maxRow = 1000;
		if (filename.endsWith(".xlsx")) {
			voR = DiyExcelImportUtil.readXlsx(inputStream, specialIdCardList, false, paramVo.getSheetName(), maxRow);
		} else {
			return R.failed("请使用标准模板（高版本的EXCEL）导入！");
		}
		if (voR != null && voR.getCode() == CommonConstants.SUCCESS) {
			vo = voR.getData();
		} else {
			return R.failed(voR == null ? "预入职导入识别表格异常！" : voR.getMsg());
		}
		String[] modelTitle = {"员工类型", "员工姓名", "身份证号", "身份证开始日期", "身份证截止日期", "婚姻状况", "民族"
				, "政治面貌", "手机号码", "邮箱", "户籍所在地-省", "户籍所在地-市", "户籍所在地-区/县", "户口性质", "档案所在地-省"
				, "档案所在地-市", "档案所在地-区/县", "通信地址-省", "通信地址-市", "通信地址-区/县", "通信地址-详细地址"
				, "紧急联系人姓名", "紧急联系人与本人关系", "联系地址-省", "联系地址-市", "联系地址-区/县", "联系地址-详细地址"
				, "手机号码（紧急联系人）", "学历", "学校", "专业", "教育开始时间", "教育结束时间", "是否为首份工作", "工作单位"
				, "工作岗位", "开始工作日期", "结束工作日期", "家庭成员姓名", "家庭成员与本人关系", "手机号码（家庭成员）", "是否有职业资格证书"
				, "申报年度", "职业资格名称", "是否曾被认定为工伤", "是否有职业病", "职业病名称", "是否有传染性疾病", "传染病名称"
				, "是否被劳动能力鉴定委员会鉴定为具有伤残等级", "伤残病名称", "伤残等级"
				, "是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种", "是否曾经或正在追究与承担过刑事责任"
				, "银行卡号", "开户总行", "开户省", "开户市", "开户支行", "计税月份"};
		int modelLength = modelTitle.length;
		// 1 验证表头：
		if (vo.getTitleList() != null && !vo.getTitleList().isEmpty()) {
			if (vo.getTitleList().size() != modelLength) {
				return R.failed("请检查表头列数！模板列数为：" + modelLength + "，您导入的表头列数为：" + vo.getTitleList().size());
			}
			ExcelColumnVo title;
			// 标题行的内容
			String titleStr;
			StringBuilder errorTitle = new StringBuilder();
			for (int i = 0; i < vo.getTitleList().size(); i++) {
				title = vo.getTitleList().get(i);
				titleStr = title.getContent();
				if (!modelTitle[i].equals(titleStr)) {
					errorTitle.append("第").append((i + 1)).append("列表头应为：").append(modelTitle[i]).append("，您的表头为").append(titleStr).append("；");
				}
			}
			if (errorTitle.length() > 0) {
				return R.failed("表头错误：" + errorTitle + " 请检查调整后再次导入");
			}
		} else {
			return R.failed("表格没有表头，请检查表格数据！");
		}

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

			PreUploadEmpImportVo detail;
			List<TCheckIdCard> checkList = new ArrayList<>();
			List<String> mobileList = new ArrayList<>();
			List<TCheckBankNo> bankList = new ArrayList<>();
			YifuUser user = SecurityUtils.getUser();
			TCheckIdCard idCardCheck;
			TCheckBankNo bankCheck;

			Map<Integer, String> titleMap = new HashMap<>();
			// 得到类的所有field
			Field[] allFields = PreUploadEmpImportVo.class.getDeclaredFields();
			// 从map中得到对应列的field
			Field field;
			// 将有注解的field存放到fieldsMap中
			Map<String, Field> fieldsMap = new HashMap<>();
			for (int i = 0; i < allFields.length; i++) {
				field = allFields[i];
				if (field.isAnnotationPresent(ExcelAttribute.class)) {
					// 设置类的私有字段属性可访问
					field.setAccessible(true);
					fieldsMap.put(field.getName(), field);
					titleMap.put(i, field.getName());
				}
			}
			ExcelAttribute attr;  //获取属性对应的注解属性
			Class<?> fieldType;  // 取得类型,并根据对象类型设置值

			List<PreUploadEmpImportVo> excelList = new ArrayList<>();
			String idNumber = "empIdcard";
			String shuName;
			String shuValue;
			String dictValue;
			// 必填项未填写
			StringBuilder errorMust;
			// 格式不正确
			StringBuilder errorFormat;
			// 校验是否通过
			StringBuilder errorCheck;
			// 已存在的主档案Map
			Map<String, String> empMap = new HashMap<>();
			// 已存在的主档案
			String curVo;
			// 人员map
			Map<String, TEmployeeProject> proMap = tEmployeeProjectService.getMapByDeptIdAndDelete(paramVo.getDeptId());
			TEmployeeProject project;
			// 预入职map
			Map<String, TPreEmpMain> preMap = this.getMapByDeptId(paramVo.getDeptId());
			TPreEmpMain main;
			// 字典Map
			Map<String, String> dictMap = new HashMap<>();
			// 存放父级area的值
			Map<String, String> parentAreaMap = new HashMap<>();
			Map<String, Date> startDateMap;
			int lineNum = 2;
			Date date1;
			Date date2;
			for (Map<String, String> rowMap : vo.getContentList()) {
				curVo = null;
				errorMust = new StringBuilder();
				errorFormat = new StringBuilder();
				// 每一行都要初始化起始时间
				startDateMap = new HashMap<>();
				detail = new PreUploadEmpImportVo();
				detail.setLineNum(lineNum++);
				for (int i = 0; i < modelLength; i++) {
					shuName = titleMap.get(i);
					shuValue = rowMap.get(String.valueOf(i));
					if (Common.isNotNull(shuName)) {
						// 忽略Value的值
						if (!shuName.contains("Value")) {
							if (idNumber.equals(shuName)) {
								if (Common.isEmpty(shuValue)) {
									errorMust.append("身份证号;");
								} else {
									curVo = empMap.get(shuValue);
								}
							}
							field = fieldsMap.get(shuName);
							if (field != null) {
								attr = field.getAnnotation(ExcelAttribute.class);
								// 必填
								if (curVo == null && attr.isNotEmpty() && Common.isEmpty(shuValue)) {
									errorMust.append(attr.name()).append(";");
								}
								if (Common.isNotNull(shuValue)) {
									shuValue = shuValue.trim();
									//校验字段是否符合要求 返回错误信息
									dictValue = DiyExcelImportUtil.validateUtil(shuValue, attr, errorFormat, dictMap, parentAreaMap, shuName, curVo != null, startDateMap);
									//校验字段是否符合要求2 开户行
									if (curVo == null && "bankName".equals(shuName) && bankMap.get(shuValue) == null) {
										errorFormat.append(attr.name()).append("_不符合财务要求，请查薪资配置；");
									}
									fieldType = field.getType();
									if (Common.isNotNull(fieldType)) {
										DiyExcelImportUtil.setFields(field, shuValue, fieldType, detail);
									}
									// 塞字典返回的值
									if (Common.isNotNull(dictValue)) {
										field = fieldsMap.get(shuName + "Value");
										if (field != null) {
											fieldType = field.getType();
											if (Common.isNotNull(fieldType)) {
												DiyExcelImportUtil.setFieldsValue(field, dictValue, fieldType, detail);
											}
										}
									}
								}
							}
						}
					}
				}
				// 第一步：校验是否通过：身份证号是否有（反馈信息：身份证号不存在）→人员是否已在项（或已导入待审核）
				// （反馈信息：人员已在项，如需更新信息，请点击“批量更新”入口更新；人员“待审核”，如需更新，可“审核不通过”再次导入）
				if (Common.isNotNull(detail.getEmpIdcard())) {
					project = proMap.get(detail.getEmpIdcard());
					if (project != null) {
						detail.setErrorInfo("人员已在项，如需更新信息，请点击“批量更新”入口更新");
					} else {
						main = preMap.get(detail.getEmpIdcard());
						if (main != null && Common.isNotNull(main.getStatus()) && CommonConstants.TWO_STRING.equals(main.getStatus())) {
							detail.setErrorInfo("人员“待审核”，如需更新，可“审核不通过”再次导入");
						} else {

							// 第二步：其他信息并行校验
							// 1必填项未填写：紧急联系人
							// 2格式不正确：计税月份
							// 3校验是否通过：姓名&身份证号是否一致、手机号是否真实、姓名&银行卡号是否一致

							// 1必填项未填写：紧急联系人
							// 有主档案，则判断附属信息是否联动必填
							if (curVo != null) {
								// 主要工作经历
								// 主要家庭成员信息
								// 职业资格信息——职业资格证书
								if (Common.isEmpty(detail.getFirstWorkFlag())
										&& Common.isEmpty(detail.getFamilyName())
										&& Common.isEmpty(detail.getHaveQualification())) {
									errorMust.append("附属信息：主要工作经历、主要家庭成员信息、职业资格信息不能都为空！");
								} else {
									// 主要工作经历
									judgeWorkFlag(detail, errorMust);
									// 主要家庭成员信息
									judgeFamily(detail, errorMust);
									// 职业资格信息——职业资格证书
									judgeQualification(detail, errorMust);
								}
							} else {
								// 主的其他信息必填校验
								if (Common.isEmpty(detail.getEmpNatrue())) {
									errorMust.append("员工类型;");
								}
								if (Common.isEmpty(detail.getEmpName())) {
									errorMust.append("员工姓名;");
								}
								// 主的其他联动必填
								// 最高教育经历
								judgeEducation(detail, errorMust);
								// 主要工作经历
								judgeWorkFlag(detail, errorMust);
								// 主要家庭成员信息
								judgeFamily(detail, errorMust);
								// 职业资格信息——职业资格证书
								judgeQualification(detail, errorMust);
								// 伤残信息
								judgeDisability(detail, errorMust);
								// 银行卡号
								judgeBank(detail, errorMust);
							}
							// 2格式不正确：在循环里已经判断了
							// 3校验是否通过：姓名&身份证号是否一致、手机号是否真实、姓名&银行卡号是否一致
							if (curVo != null) {
								if (Common.isNotNull(detail.getContractTel())) {
									mobileList.add(detail.getContractTel());
								}
							} else {
								if (Common.isNotNull(detail.getEmpName())) {
									if (Common.isNotNull(detail.getEmpIdcard())) {
										idCardCheck = new TCheckIdCard();
										idCardCheck.setIdCard(detail.getEmpIdcard());
										idCardCheck.setName(detail.getEmpName());
										idCardCheck.setCreateUser(user.getId());
										idCardCheck.setReason(user.getNickname());
										checkList.add(idCardCheck);
									}
									if (Common.isNotNull(detail.getBankNo())) {
										bankCheck = new TCheckBankNo();
										bankCheck.setBankNo(detail.getBankNo());
										bankCheck.setName(detail.getEmpName());
										bankCheck.setIdNum(detail.getEmpIdcard());
										bankList.add(bankCheck);
									}
								}
								// 手机号码
								if (Common.isNotNull(detail.getEmpPhone())) {
									mobileList.add(detail.getEmpPhone());
								}
								// 手机号码（紧急联系人）
								if (Common.isNotNull(detail.getTel())) {
									mobileList.add(detail.getTel());
								}
								// 手机号码（家庭成员）
								if (Common.isNotNull(detail.getContractTel())) {
									mobileList.add(detail.getContractTel());
								}
							}
							StringBuilder errorInfo = new StringBuilder();
							if (errorMust.length() > 0) {
								errorInfo.append("必填项未填写：").append(errorMust);
							}
							if (errorFormat.length() > 0) {
								errorInfo.append("格式不正确：").append(errorFormat);
							}
							detail.setErrorInfo(errorInfo.toString());
							if (curVo != null || errorInfo.length()>0) {
								detail.setIsMain(false);
							} else {
								detail.setIsMain(true);
								empMap.put(detail.getEmpIdcard(), CommonConstants.ZERO_STRING);
							}
						}
					}
				} else {
					detail.setErrorInfo("身份证号不存在！");
				}
				if ("长期".equals(detail.getValidityEnd())) {
					detail.setValidityEnd("2999-12-31");
				}
				// 身份证起止有效期 都有值 且 截止日期正常
				if (Common.isNotNull(detail.getValidityStart())
						&& Common.isNotNull(detail.getValidityEnd())){
					date1 = DateUtil.stringToDate(detail.getValidityStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT);
					date2 =  DateUtil.stringToDate(detail.getValidityEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT);
					if (null == date1 || null == date2){
						detail.setErrorInfo(EmployeeConstants.EMP_VALIDITY_DATE_ERROR);
					}else {
						if (!date2.after(date1)){
							detail.setErrorInfo(EmployeeConstants.EMP_VALIDITY_END_START_DATE);
						}
					}
				}
				excelList.add(detail);
			}

			// 批量校验 卡号与手机号
			Map<String, Boolean> bankNoMap = new HashMap<>();
			Map<String, Boolean> phoneMap = new HashMap<>();
			Map<String, Boolean> idCardMap = new HashMap<>();
			if (!bankList.isEmpty()) {
				R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckbankno/inner/checkBankNoAndNameBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					bankNoMap = checkListR.getData().getCheckMap();
				}
			}
			if (!mobileList.isEmpty()) {
				R<CheckBatchVo> phoneR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckmobile/inner/checkMobileBatch", mobileList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (phoneR != null && phoneR.getData() != null) {
					phoneMap = phoneR.getData().getCheckMap();
				}
			}
			if (!checkList.isEmpty()) {
				R<CheckBatchVo> idCardR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckidcard/inner/checkIdCardBatch", checkList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (idCardR != null && idCardR.getData() != null) {
					idCardMap = idCardR.getData().getCheckMap();
				}
			}
			int idCardFlag = 0;
			if (idCardMap != null && !idCardMap.isEmpty()) {
				if (idCardMap.get("全部正确") != null) {
					idCardFlag = 1;
				}
				if (idCardMap.get("全部错误") != null) {
					idCardFlag = 2;
				}
			}
			Boolean resultB;
			// 要保存的list
			List<PreUploadEmpImportVo> saveList = new ArrayList<>();
			// 返回的错误excel
			List<PreUploadEmpImportVo> errorList = new ArrayList<>();
			// 用于查询预入职相关信息
			List<String> idCardList = new ArrayList<>();
			for (PreUploadEmpImportVo info : excelList) {
				errorCheck = new StringBuilder();
				if (Common.isNotNull(info.getIsMain())) {
					if (Boolean.TRUE.equals(info.getIsMain())) {
						if (Common.isNotNull(info.getEmpName())) {
							if (idCardFlag == 0) {
								if (Common.isNotNull(info.getEmpIdcard())) {
									resultB = idCardMap.get(info.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + info.getEmpName());
									if (resultB != null) {
										if (Boolean.FALSE.equals(resultB)) {
											errorCheck.append("姓名&身份证号不一致;");
										}
									} else {
										errorCheck.append("姓名&身份证号未校验;");
									}
								}
							} else if (idCardFlag == 2) {
								errorCheck.append("姓名&身份证号不一致；");
							}
							if (Common.isNotNull(info.getBankNo())) {
								resultB = bankNoMap.get(info.getBankNo() + CommonConstants.DOWN_LINE_STRING + info.getEmpName());
								if (resultB != null) {
									if (Boolean.FALSE.equals(resultB)) {
										errorCheck.append("姓名&银行卡号不一致;");
									}
								} else {
									errorCheck.append("姓名&银行卡号未校验;");
								}
							}
						}
						// 手机号码
						if (Common.isNotNull(info.getEmpPhone())) {
							resultB = phoneMap.get(info.getEmpPhone());
							if (resultB != null) {
								if (Boolean.FALSE.equals(resultB)) {
									errorCheck.append("手机号码校验不通过;");
								}
							} else {
								errorCheck.append("手机号码未校验;");
							}
						}
						// 手机号码（紧急联系人）
						if (Common.isNotNull(info.getTel())) {
							resultB = phoneMap.get(info.getTel());
							if (resultB != null) {
								if (Boolean.FALSE.equals(resultB)) {
									errorCheck.append("手机号码（紧急联系人）校验不通过;");
								}
							} else {
								errorCheck.append("手机号码（紧急联系人）未校验;");
							}
						}
						// 手机号码（家庭成员）
						if (Common.isNotNull(info.getContractTel())) {
							resultB = phoneMap.get(info.getContractTel());
							if (resultB != null) {
								if (Boolean.FALSE.equals(resultB)) {
									errorCheck.append("手机号码（家庭成员）校验不通过;");
								}
							} else {
								errorCheck.append("手机号码（家庭成员）未校验;");
							}
						}
					} else {
						// 手机号码（家庭成员）
						if (Common.isNotNull(info.getContractTel())) {
							resultB = phoneMap.get(info.getContractTel());
							if (resultB != null) {
								if (Boolean.FALSE.equals(resultB)) {
									errorCheck.append("手机号码（家庭成员）校验不通过;");
								}
							} else {
								errorCheck.append("手机号码（家庭成员）未校验;");
							}
						}
					}
				}
				if (errorCheck.length() > 0) {
					info.setErrorInfo(info.getErrorInfo() + "校验未通过：" + errorCheck);
					errorList.add(info);
				} else if (Common.isEmpty(info.getErrorInfo())) {
					// 全部验证成功
					saveList.add(info);
					idCardList.add(info.getEmpIdcard());
				} else {
					errorList.add(info);
				}
			}
			// 验证通过的，开始保存
			if (!saveList.isEmpty()) {
				List<String> preList = baseMapper.getTPreEmpMainListByCardAndDept(idCardList, deptId);
				if (preList != null && !preList.isEmpty()) {
					baseMapper.deleteBadByMainIdList(preList);
					baseMapper.deleteContactByMainIdList(preList);
					baseMapper.deleteDisabilityByMainIdList(preList);
					baseMapper.deleteEducationByMainIdList(preList);
					baseMapper.deleteFamilyByMainIdList(preList);
					baseMapper.deleteEmployeeByMainIdList(preList);
					baseMapper.deleteProjectByMainIdList(preList);
					baseMapper.deleteWorkRecordingByMainIdList(preList);
					baseMapper.deleteProfessionalByMainIdList(preList);
					baseMapper.deleteOtherFileByMainIdList(preList);
					baseMapper.deleteAttaByDomainIdList(preList);
					baseMapper.deletePreMainIdList(preList);
				}

				// 保存主表信息
				List<TPreEmpMain> mainList = new ArrayList<>();
				for (PreUploadEmpImportVo info : saveList) {
					if (Common.isNotNull(info.getIsMain()) && Boolean.TRUE.equals(info.getIsMain())) {
						main = new TPreEmpMain();
						main.setSourType(CommonConstants.ONE_STRING);
						main.setEmpIdcard(info.getEmpIdcard());
						main.setEmpName(info.getEmpName());
						main.setSettleDomain(dept.getId());
						main.setDeptId(dept.getId());
						main.setDeptName(dept.getDepartName());
						main.setDeptNo(dept.getDepartNo());
						main.setUnitId(dept.getCustomerId());
						main.setUnitName(dept.getCustomerName());
						main.setUnitNo(dept.getCustomerNo());
						main.setBusinessPrimaryType(dept.getBusinessPrimaryType());
						main.setBusinessSecondType(dept.getBusinessSecondType());
						main.setBusinessThirdType(dept.getBusinessThirdType());
						main.setStatus(CommonConstants.ONE_STRING);
						main.setDeclarationId(declarId);
						main.setEmpPhone(info.getEmpPhone());
						main.setEmpNatrue(info.getEmpNatrueValue());
						// 给下面的附属信息使用的
						main.setFirstWorkFlag(info.getFirstWorkFlag());
						main.setHaveQualification(info.getHaveQualification());

						mainList.add(main);
					}
				}
				this.saveBatch(mainList);
				Map<String, TPreEmpMain> saveMainMap = new HashMap<>();
				for (TPreEmpMain saveMain : mainList) {
					saveMainMap.put(saveMain.getEmpIdcard(), saveMain);
				}

				List<TEmployeeInfo> oldEmpList = tEmployeeInfoService.getListByIdCardList(idCardList);
				Map<String, TEmployeeInfo> oldEmpMap = new HashMap<>();
				if (oldEmpList != null && !oldEmpList.isEmpty()) {
					for (TEmployeeInfo e : oldEmpList) {
						oldEmpMap.put(e.getEmpIdcard(), e);
					}
				}
				// 紧急联系人
				Map<String, String> oldContactMap = new HashMap<>();
				List<TEmpContactInfo> contactList = tEmpContactInfoService.getContactByIdCardList(idCardList);
				if (contactList != null && !contactList.isEmpty()) {
					for (TEmpContactInfo contact : contactList) {
						oldContactMap.put(contact.getEmpIdcard(), contact.getId());
					}
				}
				// 伤残
				Map<String, String> oldDisabilityMap = new HashMap<>();
				List<TEmpDisabilityInfo> disabilityList = tEmpDisabilityInfoService.getTEmpDisabilityByIdCardList(idCardList);
				if (disabilityList != null && !disabilityList.isEmpty()) {
					for (TEmpDisabilityInfo disability : disabilityList) {
						oldDisabilityMap.put(disability.getEmpIdcard(), disability.getId());
					}
				}
				// 不良
				Map<String, String> oldBadRecordMap = new HashMap<>();
				List<TEmpBadRecord> badRecordList = tEmpBadRecordService.getBadByIdCard(idCardList);
				if (badRecordList != null && !badRecordList.isEmpty()) {
					for (TEmpBadRecord badRecord : badRecordList) {
						oldBadRecordMap.put(badRecord.getEmpIdcard(), badRecord.getId());
					}
				}
				// 最高学历
				Map<String, String> oldEducationMap = new HashMap<>();
				List<TEmpEducation> educationList = tEmpEducationService.getTEmpEducationByIdCard(idCardList);
				if (educationList != null && !educationList.isEmpty()) {
					for (TEmpEducation education : educationList) {
						oldEducationMap.put(education.getEmpIdcard(), education.getId());
					}
				}

				TEmployeeInfo employee;
				TPreEmployeeInfo tPreEmployeeInfo;
				TPreEmployeeProject tPreEmployeeProject;
				String empId = null;
				// 组装1 预入职 档案
				List<TPreEmployeeInfo> preEmployeeInfoList = new ArrayList<>();
				List<TPreEmployeeInfo> preEmployeeInfoNeedSalaryList = new ArrayList<>();
				List<String> needSalaryList = new ArrayList<>();
				List<TPreEmployeeProject> preEmployeeProjectList = new ArrayList<>();
				List<TPreEmpBadRecord> preEmpBadRecordList = new ArrayList<>();
				List<TPreEmpContactInfo> preEmpContactInfoList = new ArrayList<>();
				List<TPreEmpDisabilityInfo> preEmpDisabilityInfoList = new ArrayList<>();
				List<TPreEmpEducation> preEmpEducationList = new ArrayList<>();
				List<TPreEmpFamily> preEmpFamilyList = new ArrayList<>();
				List<TPreEmpWorkRecording> preEmpWorkRecordingList = new ArrayList<>();
				List<TPreEmpProfessionalQualification> preEmpProfessionalQualificationList = new ArrayList<>();

				TPreEmpBadRecord tPreEmpBadRecord;
				TPreEmpContactInfo tPreEmpContactInfo;
				TPreEmpDisabilityInfo tPreEmpDisabilityInfo;
				TPreEmpEducation tPreEmpEducation;
				TPreEmpFamily tPreEmpFamily;
				TPreEmpWorkRecording tPreEmpWorkRecording;
				TPreEmpProfessionalQualification tPreEmpProfessionalQualification;
				String mainId;
				String empIdCard;
				Date endDate = DateUtil.stringToDate("2999-12-31", DateUtil.ISO_EXPANDED_DATE_FORMAT);
				// 组装附属信息
				for (PreUploadEmpImportVo info : saveList) {
					main = saveMainMap.get(info.getEmpIdcard());
					empId = null;
					if (main != null) {
						employee = oldEmpMap.get(info.getEmpIdcard());
						mainId = main.getId();
						empIdCard = main.getEmpIdcard();
						// 1、2、预入职档案表、项目档案表
						if (Common.isNotNull(info.getIsMain()) && Boolean.TRUE.equals(info.getIsMain())) {
							tPreEmployeeInfo = new TPreEmployeeInfo();
							tPreEmployeeProject = new TPreEmployeeProject();

							project = proMap.get(info.getEmpIdcard());
							tPreEmployeeInfo.setEmpName(main.getEmpName());
							tPreEmployeeInfo.setEmpIdcard(main.getEmpIdcard());
							if (employee != null) {
								empId = employee.getId();
								BeanUtil.copyProperties(employee, tPreEmployeeInfo, ID);
								tPreEmployeeInfo.setOldId(employee.getId());
								if (project != null) {
									BeanUtil.copyProperties(project, tPreEmployeeProject, ID);
									tPreEmployeeProject.setOldId(project.getId());
								}
							}

							tPreEmployeeInfo.setPreMainId(mainId);
							tPreEmployeeInfo.setCreateBy(user.getId());
							tPreEmployeeInfo.setCreateName(user.getNickname());
							tPreEmployeeInfo.setCreateTime(LocalDateTime.now());
							tPreEmployeeInfo.setValidityStart(info.getValidityStartValue());
							if ("长期".equals(info.getValidityEnd())) {
								tPreEmployeeInfo.setValidityEnd(endDate);
							} else {
								tPreEmployeeInfo.setValidityEnd(info.getValidityEndValue());
							}
							tPreEmployeeInfo.setEmpNatrue(info.getEmpNatrueValue());
							tPreEmployeeInfo.setEmpSex(IdCardUtil.getSex(empIdCard));
							java.sql.Date empBirthday = com.yifu.cloud.plus.v1.yifu.archives.util.IdCardUtil.getBirthdate(empIdCard);
							tPreEmployeeInfo.setEmpBirthday(empBirthday);
							tPreEmployeeInfo.setEmpAge(IdCardUtil.IdNOToAge(empIdCard));
							tPreEmployeeInfo.setEmpMarriStatus(info.getEmpMarriStatusValue());
							tPreEmployeeInfo.setEmpNational(info.getEmpNationalValue());
							tPreEmployeeInfo.setPoliticalStatus(info.getPoliticalStatusValue());
							tPreEmployeeInfo.setEmpEmail(info.getEmpEmail());
							tPreEmployeeInfo.setEmpPhone(info.getEmpPhone());
							// 2024-10-30 20:02:53 测试jld认为如果没写户籍省，则带出档案。我认为有道理
							if (Common.isNotNull(info.getIdProvinceValue())) {
								tPreEmployeeInfo.setIdProvince(Integer.parseInt(info.getIdProvinceValue()));
								if (Common.isNotNull(info.getIdCityValue())) {
									tPreEmployeeInfo.setIdCity(Integer.parseInt(info.getIdCityValue()));
								} else {
									tPreEmployeeInfo.setIdCity(null);
								}
								if (Common.isNotNull(info.getIdTownValue())) {
									tPreEmployeeInfo.setIdTown(Integer.parseInt(info.getIdTownValue()));
								} else {
									tPreEmployeeInfo.setIdTown(null);
								}
							}
							tPreEmployeeInfo.setEmpRegisType(info.getEmpRegisTypeValue());
							if (Common.isNotNull(info.getFileProvinceValue())) {
								tPreEmployeeInfo.setFileProvince(Integer.parseInt(info.getFileProvinceValue()));
							}
							if (Common.isNotNull(info.getFileCityValue())) {
								tPreEmployeeInfo.setFileCity(Integer.parseInt(info.getFileCityValue()));
							}
							if (Common.isNotNull(info.getFileTownValue())) {
								tPreEmployeeInfo.setFileTown(Integer.parseInt(info.getFileTownValue()));
							} else {
								tPreEmployeeInfo.setFileTown(null);
							}
							if (Common.isNotNull(info.getEducationNameValue())) {
								tPreEmployeeInfo.setHignEducation(info.getEducationNameValue());
								if ("5".equals(info.getEducationNameValue())
										|| "6".equals(info.getEducationNameValue())
										|| "7".equals(info.getEducationNameValue())
										|| "8".equals(info.getEducationNameValue())) {
									tPreEmployeeInfo.setIsCollege(CommonConstants.ONE_INT);
								} else {
									tPreEmployeeInfo.setIsCollege(CommonConstants.ZERO_INT);
								}
							}
							tPreEmployeeInfo.setSchool(info.getSchool());
							tPreEmployeeInfo.setMajor(info.getMajor());
							tPreEmployeeInfo.setAdmissionDate(info.getEntryDateValue());
							tPreEmployeeInfo.setGradutionDate(info.getGradutionDateValue());
							tPreEmployeeInfo.setContactAddress(info.getContactAddress());
							// 2024-10-17 14:30:06 倩倩上午测试用例评审会说要联动导入，没有卡号，后面填写的不生效：
							if (Common.isNotNull(info.getBankNo())) {
								tPreEmployeeInfo.setBankName(info.getBankName());
								tPreEmployeeInfo.setBankProvince(info.getBankProvinceValue());
								tPreEmployeeInfo.setBankCity(info.getBankCityValue());
								tPreEmployeeInfo.setBankSubName(info.getBankSubName());
								tPreEmployeeInfo.setBankNo(info.getBankNo());
								tPreEmployeeInfo.setTaxMonth(info.getTaxMonthValue());
							} else {
								preEmployeeInfoNeedSalaryList.add(tPreEmployeeInfo);
								needSalaryList.add(empIdCard);
							}
							tPreEmployeeInfo.setTaxMonthFlag(CommonConstants.ONE_STRING);
							tPreEmployeeInfo.setContactProvince(info.getContactProvinceValue());
							tPreEmployeeInfo.setContactCity(info.getContactCityValue());
							tPreEmployeeInfo.setContactTown(info.getContactTownValue());
							tPreEmployeeInfo.setFirstWorkFlag(info.getFirstWorkFlagValue());
							tPreEmployeeInfo.setHaveQualification(info.getHaveQualificationValue());
							tPreEmployeeInfo.setFileSource(CommonConstants.SEVEN_STRING);
							preEmployeeInfoList.add(tPreEmployeeInfo);

							tPreEmployeeProject.setPreMainId(mainId);
							tPreEmployeeProject.setCreateBy(user.getId());
							tPreEmployeeProject.setCreateName(user.getNickname());
							tPreEmployeeProject.setCreateTime(LocalDateTime.now());
							tPreEmployeeProject.setProjectSource(CommonConstants.EIGHT_STRING);
							tPreEmployeeProject.setEmpName(main.getEmpName());
							tPreEmployeeProject.setEmpIdcard(main.getEmpIdcard());
							tPreEmployeeProject.setUnitId(dept.getCustomerId());
							tPreEmployeeProject.setUnitName(dept.getCustomerName());
							tPreEmployeeProject.setUnitNo(dept.getCustomerNo());
							tPreEmployeeProject.setBusinessPrimaryType(dept.getBusinessPrimaryType());
							tPreEmployeeProject.setBusinessSecondType(dept.getBusinessSecondType());
							tPreEmployeeProject.setBusinessThirdType(dept.getBusinessThirdType());
							tPreEmployeeProject.setDeptId(main.getDeptId());
							tPreEmployeeProject.setDeptName(main.getDeptName());
							tPreEmployeeProject.setDeptNo(main.getDeptNo());
							preEmployeeProjectList.add(tPreEmployeeProject);

							// 其他附属信息
							tPreEmpBadRecord = new TPreEmpBadRecord();
							tPreEmpBadRecord.setOldId(oldBadRecordMap.get(empIdCard));
							tPreEmpBadRecord.setPreMainId(mainId);
							tPreEmpBadRecord.setSettleDomain(deptId);
							tPreEmpBadRecord.setProject(dept.getDepartName());
							tPreEmpBadRecord.setProjectCode(dept.getDepartNo());

							tPreEmpBadRecord.setEmpName(main.getEmpName());
							tPreEmpBadRecord.setEmpId(empId);
							tPreEmpBadRecord.setEmpIdcard(empIdCard);
							tPreEmpBadRecord.setCreateBy(user.getId());
							tPreEmpBadRecord.setCreateName(user.getNickname());
							tPreEmpBadRecord.setCreateTime(LocalDateTime.now());
							if ("是".equals(info.getRemark())) {
								// 有不良记录，存项目信息
								tPreEmpBadRecord.setRemark("曾经或正在追究与承担过刑事责任");
								// 1.9.6-chenyuxi: 记录不良记录标识
								tPreEmpBadRecord.setBadRecordFlag(CommonConstants.ZERO_STRING);
							} else {
								tPreEmpBadRecord.setRemark("未曾经或正在追究与承担过刑事责任");
								// 1.9.6-chenyuxi: 记录不良记录标识
								tPreEmpBadRecord.setBadRecordFlag(CommonConstants.ONE_STRING);
							}
							preEmpBadRecordList.add(tPreEmpBadRecord);

							// 紧急联系人
							tPreEmpContactInfo = new TPreEmpContactInfo();
							tPreEmpContactInfo.setOldId(oldContactMap.get(empIdCard));
							tPreEmpContactInfo.setEmpId(empId);
							tPreEmpContactInfo.setPreMainId(mainId);
							tPreEmpContactInfo.setCreateBy(user.getId());
							tPreEmpContactInfo.setCreateName(user.getNickname());
							tPreEmpContactInfo.setCreateTime(LocalDateTime.now());
							// 紧急联系人姓名	与本人关系	联系地址-省	联系地址-市	联系地址-区/县	联系地址-详细地址	手机号码（紧急联系人）
							tPreEmpContactInfo.setEmpName(info.getContactEmpName());
							tPreEmpContactInfo.setEmpIdcard(empIdCard);
							tPreEmpContactInfo.setRelationType(info.getRelationType());
							tPreEmpContactInfo.setRelationProvince(info.getRelationProvinceValue());
							tPreEmpContactInfo.setRelationCity(info.getRelationCityValue());
							tPreEmpContactInfo.setRelationTown(info.getRelationTownValue());
							tPreEmpContactInfo.setAddress(info.getAddress());
							tPreEmpContactInfo.setTel(info.getTel());
							preEmpContactInfoList.add(tPreEmpContactInfo);

							// 伤残
							tPreEmpDisabilityInfo = new TPreEmpDisabilityInfo();
							tPreEmpDisabilityInfo.setOldId(oldDisabilityMap.get(empIdCard));
							tPreEmpDisabilityInfo.setPreMainId(mainId);
							tPreEmpDisabilityInfo.setSettleDomain(deptId);
							tPreEmpDisabilityInfo.setEmpId(empId);
							if (employee != null) {
								tPreEmpDisabilityInfo.setEmpName(employee.getEmpName());
								tPreEmpDisabilityInfo.setEmpCode(employee.getEmpCode());
							}
							tPreEmpDisabilityInfo.setEmpIdcard(empIdCard);
							tPreEmpDisabilityInfo.setCreateBy(user.getId());
							tPreEmpDisabilityInfo.setCreateName(user.getNickname());
							tPreEmpDisabilityInfo.setCreateTime(LocalDateTime.now());
							// 是否曾被认定为工伤	是否有职业病	职业病名称	是否有传染性疾病	传染病名称	是否被劳动能力鉴定委员会鉴定为具有伤残等级	伤残病名称	伤残等级	是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种
							tPreEmpDisabilityInfo.setInjuryIdentification(info.getInjuryIdentificationValue());
							tPreEmpDisabilityInfo.setOccupationalDiseaseFlag(info.getOccupationalDiseaseFlagValue());
							tPreEmpDisabilityInfo.setOccupationalDisease(info.getOccupationalDisease());
							tPreEmpDisabilityInfo.setInfectiousDiseaseFlag(info.getInfectiousDiseaseFlagValue());
							tPreEmpDisabilityInfo.setInfectiousName(info.getInfectiousName());
							tPreEmpDisabilityInfo.setDisabilityFlag(info.getDisabilityFlagValue());
							tPreEmpDisabilityInfo.setDisabilityName(info.getDisabilityName());
							tPreEmpDisabilityInfo.setDisabilityLevel(info.getDisabilityLevelValue());
							tPreEmpDisabilityInfo.setOtherFlag(info.getOtherFlagValue());
							// tPreEmpDisabilityInfo.setRemark(info.getRemark())
							preEmpDisabilityInfoList.add(tPreEmpDisabilityInfo);

							// 最高教育经历
							tPreEmpEducation = new TPreEmpEducation();
							tPreEmpEducation.setOldId(oldEducationMap.get(empIdCard));
							tPreEmpEducation.setPreMainId(mainId);
							tPreEmpEducation.setSettleDomain(deptId);
							tPreEmpEducation.setEmpId(empId);
							tPreEmpEducation.setHighIdentification(CommonConstants.ZERO_STRING);
							if (employee != null) {
								tPreEmpEducation.setEmpName(employee.getEmpName());
								tPreEmpEducation.setEmpCode(employee.getEmpCode());
							}
							tPreEmpEducation.setEmpIdcard(empIdCard);
							tPreEmpEducation.setCreateBy(user.getId());
							tPreEmpEducation.setCreateName(user.getNickname());
							tPreEmpEducation.setCreateTime(LocalDateTime.now());
							// 学历	学校	专业	教育开始时间	教育结束时间
							tPreEmpEducation.setEducationName(info.getEducationNameValue());
							tPreEmpEducation.setSchool(info.getSchool());
							tPreEmpEducation.setMajor(info.getMajor());
							tPreEmpEducation.setEntryDate(info.getEntryDateValue());
							tPreEmpEducation.setGradutionDate(info.getGradutionDateValue());
							preEmpEducationList.add(tPreEmpEducation);
						}

						// 主要家庭成员信息
						if (Common.isNotNull(info.getFamilyName())) {
							tPreEmpFamily = new TPreEmpFamily();
							tPreEmpFamily.setSettleDomain(deptId);
							tPreEmpFamily.setEmpId(empId);
							if (employee != null) {
								tPreEmpFamily.setEmpName(employee.getEmpName());
								tPreEmpFamily.setEmpCode(employee.getEmpCode());
							}
							tPreEmpFamily.setEmpIdcard(empIdCard);
							tPreEmpFamily.setPreMainId(mainId);
							tPreEmpFamily.setCreateBy(user.getId());
							tPreEmpFamily.setCreateName(user.getNickname());
							tPreEmpFamily.setCreateTime(LocalDateTime.now());
							tPreEmpFamily.setFamilyName(info.getFamilyName());
							tPreEmpFamily.setRelationshipSelf(info.getRelationshipSelfValue());
							tPreEmpFamily.setContractTel(info.getContractTel());
							preEmpFamilyList.add(tPreEmpFamily);
						}

						// 主要工作经历
						if (Common.isNotNull(info.getFirstWorkFlag())
								&& CommonConstants.IS_FALSE.equals(main.getFirstWorkFlag())
								&& CommonConstants.IS_FALSE.equals(info.getFirstWorkFlag())) {
							tPreEmpWorkRecording = new TPreEmpWorkRecording();
							tPreEmpWorkRecording.setSettleDomain(deptId);
							tPreEmpWorkRecording.setEmpId(empId);
							if (employee != null) {
								tPreEmpWorkRecording.setEmpName(employee.getEmpName());
								tPreEmpWorkRecording.setEmpCode(employee.getEmpCode());
							}
							tPreEmpWorkRecording.setEmpIdcard(empIdCard);
							tPreEmpWorkRecording.setPreMainId(mainId);
							tPreEmpWorkRecording.setCreateBy(user.getId());
							tPreEmpWorkRecording.setCreateName(user.getNickname());
							tPreEmpWorkRecording.setCreateTime(LocalDateTime.now());
							tPreEmpWorkRecording.setWorkUnit(info.getWorkUnit());
							tPreEmpWorkRecording.setWorkJob(info.getWorkJob());
							tPreEmpWorkRecording.setStartDate(info.getStartDateValue());
							tPreEmpWorkRecording.setEndDate(info.getEndDateValue());
							preEmpWorkRecordingList.add(tPreEmpWorkRecording);
						}

						// 职业资格信息——职业资格证书
						if (Common.isNotNull(info.getHaveQualification())
								&& CommonConstants.IS_TRUE.equals(main.getHaveQualification())
								&& CommonConstants.IS_TRUE.equals(info.getHaveQualification())) {
							tPreEmpProfessionalQualification = new TPreEmpProfessionalQualification();
							tPreEmpProfessionalQualification.setPreMainId(mainId);
							tPreEmpProfessionalQualification.setSettleDomain(deptId);
							tPreEmpProfessionalQualification.setEmpId(empId);
							if (employee != null) {
								tPreEmpProfessionalQualification.setEmpName(employee.getEmpName());
								tPreEmpProfessionalQualification.setEmpCode(employee.getEmpCode());
							}
							tPreEmpProfessionalQualification.setEmpIdcard(empIdCard);
							tPreEmpProfessionalQualification.setCreateBy(user.getId());
							tPreEmpProfessionalQualification.setCreateName(user.getNickname());
							tPreEmpProfessionalQualification.setCreateTime(LocalDateTime.now());
							// 是否有职业资格证书	申报年度	职业资格名称
							tPreEmpProfessionalQualification.setDeclareYear(info.getDeclareYearValue());
							tPreEmpProfessionalQualification.setQualificationType(info.getQualificationTypeValue());
							// 1.9.6-chenyuxi:增加标识
							tPreEmpProfessionalQualification.setHaveQualification(CommonConstants.ZERO_STRING);
							preEmpProfessionalQualificationList.add(tPreEmpProfessionalQualification);
						}
					}
				}

				if (!preEmployeeInfoList.isEmpty()) {
					if (!preEmployeeInfoNeedSalaryList.isEmpty()) {
						if (!needSalaryList.isEmpty()) {
							// 查薪资服务的卡号
							R<TSalaryEmpMapVo> salaryEmpBankRes = HttpDaprUtil.invokeMethodPost(salaryProperties.getAppUrl()
									, salaryProperties.getAppId(), "/tsalaryemployee/inner/getSalaryEmpMap", needSalaryList, TSalaryEmpMapVo.class, SecurityConstants.FROM_IN);
							Map<String, TSalaryEmployee> salaryEmpBankMap;
							if (Common.isEmpty(salaryEmpBankRes) || Common.isEmpty(salaryEmpBankRes.getCode()) || salaryEmpBankRes.getCode() != CommonConstants.SUCCESS){
								return R.failed("获取薪资服务开户行信息失败！");
							} else {
								if (salaryEmpBankRes.getData() != null && salaryEmpBankRes.getData().getSalaryEmpMap() != null
										&& !salaryEmpBankRes.getData().getSalaryEmpMap().isEmpty()) {
									salaryEmpBankMap = salaryEmpBankRes.getData().getSalaryEmpMap();
									TSalaryEmployee info;
									for (TPreEmployeeInfo emp : preEmployeeInfoNeedSalaryList) {
										info = salaryEmpBankMap.get(emp.getEmpIdcard());
										if (info != null) {
											emp.setBankName(info.getBankName());
											emp.setBankProvince(info.getBankProvince());
											emp.setBankCity(info.getBankCity());
											emp.setBankSubName(info.getBankSubName());
											emp.setBankNo(info.getBankNo());
											emp.setTaxMonth(info.getTaxMonth());
										}
									}
								}
							}


						}
					}
					tPreEmployeeInfoService.saveBatch(preEmployeeInfoList);
				}
				if (!preEmployeeProjectList.isEmpty()) {
					tPreEmployeeProjectService.saveBatch(preEmployeeProjectList);
				}
				if (!preEmpBadRecordList.isEmpty()) {
					tPreEmpBadRecordService.saveBatch(preEmpBadRecordList);
				}
				if (!preEmpContactInfoList.isEmpty()) {
					tPreEmpContactInfoService.saveBatch(preEmpContactInfoList);
				}
				if (!preEmpDisabilityInfoList.isEmpty()) {
					tPreEmpDisabilityInfoService.saveBatch(preEmpDisabilityInfoList);
				}
				if (!preEmpEducationList.isEmpty()) {
					tPreEmpEducationService.saveBatch(preEmpEducationList);
				}
				if (!preEmpFamilyList.isEmpty()) {
					tPreEmpFamilyService.saveBatch(preEmpFamilyList);
				}
				if (!preEmpWorkRecordingList.isEmpty()) {
					tPreEmpWorkRecordingService.saveBatch(preEmpWorkRecordingList);
				}
				if (!preEmpProfessionalQualificationList.isEmpty()) {
					tPreEmpProfessionalService.saveBatch(preEmpProfessionalQualificationList);
				}
			}
			if (!errorList.isEmpty()) {
				return new R<>(CommonConstants.TWO_INT, null, errorList);
			} else {
				//数据保存
				return R.ok();
			}
		} else {
			return R.failed("识别到表头下存在空白行，若非空白表，请删除空白行再导入！");
		}
	}

	/**
	 * @param deptId
	 * @Description: 查找项目下的预入职信息
	 * @Author: hgw
	 * @Date: 2024/10/14 16:31
	 * @return: java.util.Map<java.lang.String, com.yifu.cloud.plus.v1.yifu.archives.entity.TPreEmpMain>
	 **/
	private Map<String, TPreEmpMain> getMapByDeptId(String deptId) {
		Map<String, TPreEmpMain> preMap = new HashMap<>();
		if (Common.isNotNull(deptId)) {
			List<TPreEmpMain> preList = this.list(Wrappers.<TPreEmpMain>query().lambda()
					.eq(TPreEmpMain::getDeptId, deptId)
					.ne(TPreEmpMain::getStatus, CommonConstants.FIVE_STRING));
			if (preList != null && !preList.isEmpty()) {
				for (TPreEmpMain pre : preList) {
					preMap.put(pre.getEmpIdcard(), pre);
				}
			}
		}
		return preMap;
	}

	private void judgeBank(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		if (Common.isNotNull(detail.getBankNo()) && (Common.isEmpty(detail.getBankName())
				|| Common.isEmpty(detail.getBankProvince())
				|| Common.isEmpty(detail.getBankCity())
				|| Common.isEmpty(detail.getTaxMonth()) )) {
			errorMust.append("银行卡号不为空则必填：");
			if (Common.isEmpty(detail.getBankName())) {
				errorMust.append("开户行总行;");
			}
			if (Common.isEmpty(detail.getBankProvince())) {
				errorMust.append("开户省;");
			}
			if (Common.isEmpty(detail.getBankCity())) {
				errorMust.append("开户市;");
			}
			if (Common.isEmpty(detail.getTaxMonth())) {
				errorMust.append("计税月份;");
			}
		}
	}

	private void judgeDisability(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		if (Common.isNotNull(detail.getOccupationalDiseaseFlag())) {
			if (detail.getOccupationalDiseaseFlag().contains("是") && Common.isEmpty(detail.getOccupationalDisease())) {
				errorMust.append("是否有职业病为是则必填：职业病名称；");
			} else if (detail.getOccupationalDiseaseFlag().contains("否")) {
				detail.setOccupationalDisease(null);
			}
		}
		if (Common.isNotNull(detail.getInfectiousDiseaseFlag())) {
			if (detail.getInfectiousDiseaseFlag().contains("是") && Common.isEmpty(detail.getInfectiousName())) {
				errorMust.append("是否有传染性疾病为是则必填：传染病名称；");
			} else if (detail.getInfectiousDiseaseFlag().contains("否")) {
				detail.setInfectiousName(null);
			}
		}
		if (Common.isNotNull(detail.getDisabilityFlag())) {
			if (detail.getDisabilityFlag().contains("是") && (Common.isEmpty(detail.getDisabilityName()) || Common.isEmpty(detail.getDisabilityLevel()))) {
				errorMust.append("是否被劳动能力鉴定委员会鉴定为具有伤残等级为是则必填：");
				if (Common.isEmpty(detail.getDisabilityName())) {
					errorMust.append("伤残病名称;");
				}
				if (Common.isEmpty(detail.getDisabilityLevel())) {
					errorMust.append("伤残等级;");
				}
			} else if (detail.getDisabilityFlag().contains("否")) {
				detail.setDisabilityName(null);
				detail.setDisabilityLevel(null);
				detail.setDisabilityLevelValue(null);
			}
		}
	}

	private void judgeQualification(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		if (Common.isNotNull(detail.getHaveQualification())
				&& detail.getHaveQualification().contains("是") && (Common.isEmpty(detail.getDeclareYear())
				|| Common.isEmpty(detail.getQualificationType()))) {
			errorMust.append("是否有职业资格证书为是则必填：");
			if (Common.isEmpty(detail.getDeclareYear())) {
				errorMust.append("申报年度;");
			}
			if (Common.isEmpty(detail.getQualificationType())) {
				errorMust.append("职业资格名称;");
			}
		}
	}

	private void judgeFamily(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		if (Common.isNotNull(detail.getFamilyName()) && (Common.isEmpty(detail.getRelationshipSelf())
				|| Common.isEmpty(detail.getContractTel()))) {
			errorMust.append("成员姓名填写则必填：");
			if (Common.isEmpty(detail.getRelationshipSelf())) {
				errorMust.append("与本人关系;");
			}
			if (Common.isEmpty(detail.getContractTel())) {
				errorMust.append("手机号码（家庭成员）;");
			}
		}
	}

	private void judgeWorkFlag(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		if (Common.isNotNull(detail.getFirstWorkFlag())
				&& detail.getFirstWorkFlag().contains("否") && (Common.isEmpty(detail.getWorkUnit())
				|| Common.isEmpty(detail.getWorkJob())
				|| Common.isEmpty(detail.getStartDate())
				|| Common.isEmpty(detail.getEndDate()))) {
			errorMust.append("是否为首份工作为否则必填：");
			if (Common.isEmpty(detail.getWorkUnit())) {
				errorMust.append("工作单位;");
			}
			if (Common.isEmpty(detail.getWorkJob())) {
				errorMust.append("工作岗位;");
			}
			if (Common.isEmpty(detail.getStartDate())) {
				errorMust.append("开始工作日期;");
			}
			if (Common.isEmpty(detail.getEndDate())) {
				errorMust.append("结束工作日期;");
			}
		}
	}

	private void judgeEducation(PreUploadEmpImportVo detail, StringBuilder errorMust) {
		boolean isCollege = Common.isNotNull(detail.getEducationName())
				&& (detail.getEducationName().contains("大专")
				|| detail.getEducationName().contains("本科")
				|| detail.getEducationName().contains("硕士")
				|| detail.getEducationName().contains("博士"));
		if (isCollege && (Common.isEmpty(detail.getSchool())
				|| Common.isEmpty(detail.getMajor())
				|| Common.isEmpty(detail.getEntryDate())
				|| Common.isEmpty(detail.getGradutionDate()))) {
			errorMust.append("大专及以上则必填：");
			if (Common.isEmpty(detail.getSchool())) {
				errorMust.append("学校;");
			}
			if (Common.isEmpty(detail.getMajor())) {
				errorMust.append("专业;");
			}
			if (Common.isEmpty(detail.getEntryDate())) {
				errorMust.append("教育开始时间;");
			}
			if (Common.isEmpty(detail.getGradutionDate())) {
				errorMust.append("教育结束时间;");
			}
		}
	}

	/**
	 * 根据身份证与姓名查询用户手机号和来源
	 *
	 * @param empIdCard 身份证
	 * @param empName 姓名
	 * @return EmpMainToCVo
	 * @author chenyuxi
	 * @date 2024-10-24 16:01:47
	 * @since mvp1.7.0
	 */
	@Override
	public R<EmpMainToCVo> getPhoneByCardAndName(String empIdCard, String empName) {
		if(Common.isEmpty(empIdCard) || Common.isEmpty(empName)){
			return R.failed("身份证、姓名都要必填");
		}
		EmpMainToCVo empMainToCVo = new EmpMainToCVo();
		// 默认不在系统
		empMainToCVo.setEmpFrom(CommonConstants.TWO_STRING);
		empMainToCVo.setEmpPhone("");
		empMainToCVo.setPreStatus("");
		// 用身份证先查是否在【在档人员】里
		TEmployeeInfo employee = tEmployeeInfoService.getInfoByIdcard(empIdCard);
		if (employee != null) {
			// 在档人员
			if (!empName.equals(employee.getEmpName())) {
				return R.failed("在档人员里找不到身份证对应的人员");
			} else {
				empMainToCVo.setEmpFrom(CommonConstants.ZERO_STRING);
				empMainToCVo.setEmpPhone(employee.getEmpPhone());
				empMainToCVo.setPreStatus("");
				return R.ok(empMainToCVo);
			}
		} else {
			// 用身份证先查是否在【预入职】里
			TPreEmpMain preEmpMain = baseMapper.selectOne(Wrappers.<TPreEmpMain>query().lambda()
					.eq(TPreEmpMain::getEmpIdcard, empIdCard)
					.ne(TPreEmpMain::getStatus, CommonConstants.FIVE_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (preEmpMain != null) {
				// 在档人员
				if (!empName.equals(preEmpMain.getEmpName())) {
					return R.failed("预入职里找不到身份证对应的人员");
				} else {
					empMainToCVo.setEmpFrom(CommonConstants.ONE_STRING);
					empMainToCVo.setEmpPhone(preEmpMain.getEmpPhone());
					empMainToCVo.setPreStatus(preEmpMain.getStatus());
					return R.ok(empMainToCVo);
				}
			}
		}

		return R.ok(empMainToCVo);
	}

	/**
	 * 发送手机验证码
	 *
	 * @param empPhone 手机号
	 * @return R<String>
	 * @author chenyuxi
	 * @date 2024-10-24 16:01:47
	 * @since mvp1.7.0
	 */
	@Override
	public R<String> sendCode(String empPhone) {
		//获取验证码
		String code = RandomUtil.getSix();
		String phoneCodeKey = CacheConstants.MVP_TOC_PHONE_CODE_PREFIX.concat(empPhone);
		if (Common.isNotNull(redisUtil.get(phoneCodeKey))) {
			code = (String)redisUtil.get(phoneCodeKey);
		}
		//发短信
		AliSmsResult result = SmsUtil.sendSms(empPhone, code);
		//验证码存缓存
		if (AliSmsResult.SUCCESS_CODE.equals(result.getCode())) {
			redisUtil.set(phoneCodeKey, code, 300L);
			return R.ok("验证码已发送");
		} else {
			return R.failed(null == result.getMessage() ? "获取验证码错误，告知管理员，阿里云短信配置错误！" : result.getMessage());
		}
	}

	/**
	 * 校验手机验证码
	 *
	 * @param empPhone 手机号
	 * @param verifyCode 验证码
	 * @return R<String>
	 *
	 * @author chenyuxi
	 * @date 2024-10-24 16:01:47
	 * @since mvp1.7.0
	 */
	@Override
	public R<String> checkCode(String empPhone, String verifyCode) {
		String phoneCodeKey = CacheConstants.MVP_TOC_PHONE_CODE_PREFIX.concat(empPhone);
		if (Common.isNotNull(redisUtil.get(phoneCodeKey))) {
			String code = (String)redisUtil.get(phoneCodeKey);
			if (!verifyCode.equals(code)) {
				return R.failed("验证码错误！");
			}
		} else {
			return R.failed("验证码过期！");
		}
		// 校验通过移除已使用的验证码
		redisUtil.remove(phoneCodeKey);

		return R.ok("验证码通过");
	}
	@Override
	public R  preEmpCount(String departNo, String startDate, String endDate){
		if (Common.isEmpty(departNo)
				|| Common.isEmpty(startDate)
				|| Common.isEmpty(endDate)
				|| DateUtil.isDate(startDate)
				|| DateUtil.isDate(endDate)) {
			return  R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		return R.ok(tAttaInfoService.getAttInfoCountByParam(departNo,startDate,endDate));
	}
	/**
	 * @Author fxj
	 * @Description 预入职C端签名图盘打包下载
	 * @Date 14:07 2025/1/10
	 * @Param
	 * @return
	 **/
	@Override
	public void exportEmpsFile(String departName,String departNo, String startDate, String endDate, HttpServletResponse response) {
		if (zipAtomicInteger.incrementAndGet() <= 1) {
			try {
				extracted(departName, departNo, startDate, endDate, response);
			} catch (Exception e) {
				log.error("导出异常：", e);
			} finally {
				zipAtomicInteger.decrementAndGet();
			}
		} else {
			// 前面做了+1（atomicInteger.incrementAndGet()）这里也要-1
			zipAtomicInteger.decrementAndGet();
			log.error("预入职签名文件导出超出阈值：" + ResultConstants.FILE_DOWN_LOAD_DATA);
			exportError(response, ResultConstants.FILE_DOWN_LOAD_DATA);
		}



	}

	private void extracted(String departName, String departNo, String startDate, String endDate, HttpServletResponse response) {
		if (Common.isEmpty(departNo)
				|| Common.isEmpty(startDate)
				|| Common.isEmpty(endDate)
				|| DateUtil.isDate(startDate)
				|| DateUtil.isDate(endDate)) {
			throw new RuntimeException(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		List<TAttaInfoVo> handles = tAttaInfoService.getAttInfoByParam(departNo, startDate, endDate);
		if (Common.isEmpty(handles)) {
			exportError(response, CommonConstants.NO_DATA_TO_HANDLE);
		}
		// 判断文件大小 超出100M  104,857,600  直接提示重新筛选条件
		long size = 0;
		if (Common.isNotNull(handles)){
			for (TAttaInfoVo vo:handles){
				size = size + vo.getAttaSize();
			}
			if (size > 104857600){
				exportError(response, CommonConstants.DATA_TOO_LARGER_FOR_DOWN);
			}
		}
		HttpGet httpGet;
		try {
			//初始化导出 response
			response.setContentType("application/octet-stream");
			response.setHeader("content-type", "application/octet-stream");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(departName + departNo, "UTF-8") + ".zip");
			CloseableHttpClient httpClient = HttpClients.createDefault();
			// 获取人员档案所有的附件信息
			getFilesInfo(handles);
			// 处理附件 压缩并下载
			if (Common.isNotNull(handles)) {
				try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(response.getOutputStream())){
					CloseableHttpResponse response1;
					HttpEntity entity;
					byte[] data;
					ZipArchiveEntry entry;
					for (TAttaInfoVo fileAtta : handles) {
						if (Common.isNotNull(fileAtta.getAttaUrl())){
							httpGet = new HttpGet(fileAtta.getAttaUrl());
							response1 = httpClient.execute(httpGet);
							entity = response1.getEntity();
							data = EntityUtils.toByteArray(entity);
							entry = new ZipArchiveEntry(fileAtta.getEmpName() + fileAtta.getEmpIdcard() + ".png");
							zipOutput.putArchiveEntry(entry);
							zipOutput.write(data);
							zipOutput.closeArchiveEntry();
						}
					}
					zipOutput.finish();
				} catch (Exception e) {
					log.error("C端项目人员签字附件下载打包异常：",e);
				}
			}
		} catch (IOException e) {
			log.error("C端项目人员签字附件下载异常：",e);
		}finally {
			if (Common.isNotNull(handles)){
				handles.clear();
			}
		}
	}

	private void getFilesInfo(List<TAttaInfoVo> handles) {
		URL url;
		// 获取其他附件以外的附件如身份证正反面
		if (Common.isNotNull(handles)) {
			for (TAttaInfoVo atta : handles) {
				if (CommonConstants.TWENTY_THREE_STRING.equals(atta.getRelationType())) {
					url = ossUtil.getObjectUrl(null, atta.getAttaSrc());
					atta.setAttaUrl(url.toString().replace("http", "https"));
				}
			}
		}
	}
}
