/*
 *    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.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.yifu.archives.entity.*;
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.vo.PreEmpMainDetailVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPreEmpMainSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPreEmpMainVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 预入职-主表
 *
 * @author hgw
 * @date 2024-06-17 11:31:08
 */
@Log4j2
@AllArgsConstructor
@Service
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 tPreEmpProfessionalQualificationService;
	// 附件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 tEmpProfessionalQualificationService;
	// 项目
	private final TSettleDomainService tSettleDomainService;

	/**
	 * 预入职-主表简单分页查询
	 *
	 * @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> 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 {
				tPreEmpDeclaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
			}
			vo.setTPreEmpDeclaration(tPreEmpDeclaration);
			// 预入职-员工伤残信息表
			TPreEmpDisabilityInfo tPreEmpDisabilityInfo = tPreEmpDisabilityInfoService.getTPreEmpDisabilityInfoList(id);
			vo.setTPreEmpDisabilityInfo(tPreEmpDisabilityInfo);
			// 预入职-员工学历信息表
			TPreEmpEducation tPreEmpEducation = tPreEmpEducationService.getTPreEmpEducationList(id);
			vo.setTPreEmpEducation(tPreEmpEducation);
			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamily = tPreEmpFamilyService.getTPreEmpFamilyList(id);
			vo.setTPreEmpFamily(tPreEmpFamily);
			// 预入职-人员档案表
			TPreEmployeeInfo tPreEmployeeInfo = tPreEmployeeInfoService.getTPreEmployeeInfoList(id);
			vo.setTPreEmployeeInfo(tPreEmployeeInfo);
			// 预入职-项目档案表
			TPreEmployeeProject tPreEmployeeProject = tPreEmployeeProjectService.getTPreEmployeeProjectList(id);
			vo.setTPreEmployeeProject(tPreEmployeeProject);
			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualification = tPreEmpProfessionalQualificationService.getTPreEmpProfessionalQualificationList(id);
			vo.setTPreEmpProfessionalQualification(tPreEmpProfessionalQualification);
			// 预入职-员工工作履历信息表
			List<TPreEmpWorkRecording> tPreEmpWorkRecording = tPreEmpWorkRecordingService.getTPreEmpWorkRecordingList(id);
			vo.setTPreEmpWorkRecording(tPreEmpWorkRecording);

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

	/**
	 * @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
	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
	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();
		if (main != null && Common.isNotNull(main.getEmpIdcard())) {
			TPreEmployeeProject tPreEmployeeProject = vo.getTPreEmployeeProject();
			if (tPreEmployeeProject != null && Common.isNotNull(tPreEmployeeProject.getOldId())) {
				// 预入职-人员档案表
				TPreEmployeeInfo tPreEmployeeInfo = vo.getTPreEmployeeInfo();
				if (tPreEmployeeInfo != null && Common.isNotNull(tPreEmployeeInfo.getOldId())) {
					// 转到更新档案去
					return updateToEmployeeByPre(vo);
				} else {
					return R.failed("档案原ID不可为空！");
				}
			} else {
				main.setStatus(status);
				this.saveOrUpdate(main);
				String mainId = main.getId();

				// 预入职-员工不良记录表
				TPreEmpBadRecord tPreEmpBadRecord = vo.getTPreEmpBadRecord();
				if (tPreEmpBadRecord != null) {
					tPreEmpBadRecord.setPreMainId(mainId);
					tPreEmpBadRecordService.saveOrUpdate(tPreEmpBadRecord);
				}
				// 预入职-紧急联络人
				TPreEmpContactInfo tPreEmpContactInfo = vo.getTPreEmpContactInfo();
				if (tPreEmpContactInfo != null) {
					tPreEmpContactInfo.setPreMainId(mainId);
					tPreEmpContactInfoService.saveOrUpdate(tPreEmpContactInfo);
				}
				// 预入职-员工伤残信息表
				TPreEmpDisabilityInfo tPreEmpDisabilityInfo = vo.getTPreEmpDisabilityInfo();
				if (tPreEmpDisabilityInfo != null) {
					tPreEmpDisabilityInfo.setPreMainId(mainId);
					tPreEmpDisabilityInfoService.saveOrUpdate(tPreEmpDisabilityInfo);
				}
				// 预入职-员工学历信息表
				TPreEmpEducation tPreEmpEducation = vo.getTPreEmpEducation();
				if (tPreEmpEducation != null) {
					tPreEmpEducation.setPreMainId(mainId);
					tPreEmpEducationService.saveOrUpdate(tPreEmpEducation);
				}
				// 预入职-员工家庭信息表
				List<TPreEmpFamily> tPreEmpFamily = vo.getTPreEmpFamily();
				if (tPreEmpFamily != null) {
					for (TPreEmpFamily info : tPreEmpFamily) {
						info.setPreMainId(mainId);
					}
					tPreEmpFamilyService.saveOrUpdateBatch(tPreEmpFamily);
				}
				// 预入职-人员档案表
				TPreEmployeeInfo tPreEmployeeInfo = vo.getTPreEmployeeInfo();
				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);
							}
						}
					}
					// 生成性别年龄等：
					this.setBaseSexInfo(tPreEmployeeInfo);
					tPreEmployeeInfo.setPreMainId(mainId);
					tPreEmployeeInfoService.saveOrUpdate(tPreEmployeeInfo);
				}
				// 预入职-项目档案表
				if (tPreEmployeeProject != null) {
					tPreEmployeeProject.setPreMainId(mainId);
					tPreEmployeeProjectService.saveOrUpdate(tPreEmployeeProject);
				}
				// 预入职-员工职业资格信息表
				List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualification = vo.getTPreEmpProfessionalQualification();
				if (tPreEmpProfessionalQualification != null) {
					for (TPreEmpProfessionalQualification info : tPreEmpProfessionalQualification) {
						info.setPreMainId(mainId);
					}
					tPreEmpProfessionalQualificationService.saveOrUpdateBatch(tPreEmpProfessionalQualification);
				}
				// 预入职-员工工作履历信息表
				List<TPreEmpWorkRecording> tPreEmpWorkRecording = vo.getTPreEmpWorkRecording();
				if (tPreEmpWorkRecording != null) {
					for (TPreEmpWorkRecording info : tPreEmpWorkRecording) {
						info.setPreMainId(mainId);
					}
					tPreEmpWorkRecordingService.saveOrUpdateBatch(tPreEmpWorkRecording);
				}
			}
			return R.ok("成功");
		} else {
			return R.failed("身份证不可为空！");
		}
	}

	/**
	 * @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) {
		YifuUser user = SecurityUtils.getUser();
		// 预入职-人员档案表
		TPreEmployeeInfo tPreEmployeeInfo = vo.getTPreEmployeeInfo();
		// 预入职-项目档案表
		TPreEmployeeProject tPreEmployeeProject = vo.getTPreEmployeeProject();
		// 预入职-员工学历信息表
		TPreEmpEducation tPreEmpEducation = vo.getTPreEmpEducation();
		// 如果档案项目id都没有，则新增。newFlag是true：
		boolean 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 && Common.isNotNull(tPreEmployeeInfo.getOldId())
				&& Common.isNotNull(tPreEmployeeProject.getOldId())) {
			newFlag = false;
			empId = tPreEmployeeInfo.getOldId();
			emp = tEmployeeInfoService.getById(empId);
			if (emp != null) {
				BeanUtil.copyProperties(tPreEmployeeInfo, emp);
				tEmployeeInfoService.updateById(emp);
			} else {
				emp = this.saveTEmployeeInfo(user, tPreEmployeeInfo);
				empId = emp.getId();
			}
			empIdCard = emp.getEmpIdcard();
			project = tEmployeeProjectService.getById(tPreEmployeeProject.getOldId());
			if (project != null) {
				BeanUtil.copyProperties(tPreEmployeeInfo, project);
				tEmployeeInfoService.updateById(emp);
			} else {
				project = this.saveTEmployeeProject(project, user, tPreEmployeeProject, emp, dept);
			}
		} else {
			// 新建档案、项目档案，将档案id赋值，给其他附属信息
			if (tPreEmployeeInfo != null) {
				if (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);
						}
					}
				}
				// 生成性别年龄等：
				this.setBaseSexInfo(tPreEmployeeInfo);

				// 1人员档案
				emp = this.saveTEmployeeInfo(user, tPreEmployeeInfo);
				empId = emp.getId();
				empIdCard = emp.getEmpIdcard();
				// 2项目档案
				project = this.saveTEmployeeProject(project, user, tPreEmployeeProject, emp, dept);
			}
		}

		// 3:其他附属信息

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

		// 最高学历
		if (tPreEmpEducation != null) {
			TEmpEducation tEmpEducation = null;
			if (Common.isNotNull(tPreEmpEducation.getOldId())) {
				tEmpEducation = tEmpEducationService.getById(tPreEmpEducation.getOldId());
			}
			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);
			if (Common.isNotNull(empIdCard)) {
				tEmpEducationService.updateEducationToNoByIdCard(empIdCard);
			}
			tEmpEducationService.saveOrUpdate(tEmpEducation);
		}
		// 预入职-员工不良记录表
		TPreEmpBadRecord tPreEmpBadRecord = vo.getTPreEmpBadRecord();
		if (tPreEmpBadRecord != null) {
			TEmpBadRecord tEmpBadRecord = null;
			if (Common.isNotNull(tPreEmpBadRecord.getOldId())) {
				tEmpBadRecord = tEmpBadRecordService.getById(tPreEmpBadRecord.getOldId());
			}
			if (tEmpBadRecord == null) {
				tEmpBadRecord = new TEmpBadRecord();
			}
			BeanUtil.copyProperties(tPreEmpEducation, tEmpBadRecord);
			tEmpBadRecordService.saveOrUpdate(tEmpBadRecord);
		}
		// 预入职-紧急联络人
		TPreEmpContactInfo tPreEmpContactInfo = vo.getTPreEmpContactInfo();
		if (tPreEmpContactInfo != null) {
			TEmpContactInfo tEmpContactInfo = null;
			if (Common.isNotNull(tPreEmpContactInfo.getOldId())) {
				tEmpContactInfo = tEmpContactInfoService.getById(tPreEmpContactInfo.getOldId());
			}
			if (tEmpContactInfo == null) {
				tEmpContactInfo = new TEmpContactInfo();
			}
			BeanUtil.copyProperties(tPreEmpContactInfo, tEmpContactInfo);
			tEmpContactInfoService.saveOrUpdate(tEmpContactInfo);
		}
		// 预入职-员工伤残信息表
		TPreEmpDisabilityInfo tPreEmpDisabilityInfo = vo.getTPreEmpDisabilityInfo();
		if (tPreEmpDisabilityInfo != null) {
			TEmpDisabilityInfo tEmpDisabilityInfo = null;
			if (Common.isNotNull(tPreEmpDisabilityInfo.getOldId())) {
				tEmpDisabilityInfo = tEmpDisabilityInfoService.getById(tPreEmpDisabilityInfo.getOldId());
			}
			if (tEmpDisabilityInfo == null) {
				tEmpDisabilityInfo = new TEmpDisabilityInfo();
			}
			BeanUtil.copyProperties(tPreEmpContactInfo, tEmpDisabilityInfo);
			tEmpDisabilityInfoService.saveOrUpdate(tEmpDisabilityInfo);
		}

		// 预入职-员工家庭信息表
		List<TPreEmpFamily> tPreEmpFamilyList = vo.getTPreEmpFamily();
		if (tPreEmpFamilyList != null) {
			// 先删除其他信息
			tEmpFamilyService.deleteByEmpIdAndTable(empId, "t_emp_family");
			List<TEmpFamily> tEmpFamilyList = new ArrayList<>();
			TEmpFamily tEmpFamily;
			for (TPreEmpFamily tPreEmpFamily : tPreEmpFamilyList) {
				tEmpFamily = new TEmpFamily();
				BeanUtil.copyProperties(tPreEmpContactInfo, tEmpFamily);
				if (Common.isNotNull(tPreEmpFamily.getOldId())) {
					tEmpFamily.setId(tPreEmpFamily.getOldId());
				}
				tEmpFamilyList.add(tEmpFamily);
			}
			tEmpFamilyService.saveOrUpdateBatch(tEmpFamilyList);
		}
		// 预入职-员工职业资格信息表
		List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualificationList = vo.getTPreEmpProfessionalQualification();
		if (tPreEmpProfessionalQualificationList != null) {
			// 先删除其他信息
			tEmpFamilyService.deleteByEmpIdAndTable(empId, "t_pre_emp_professional_qualification");
			List<TEmpProfessionalQualification> tEmpProfessionalQualificationList = new ArrayList<>();
			TEmpProfessionalQualification info;
			for (TPreEmpProfessionalQualification preInfo : tPreEmpProfessionalQualificationList) {
				info = new TEmpProfessionalQualification();
				BeanUtil.copyProperties(tPreEmpContactInfo, info);
				if (Common.isNotNull(preInfo.getOldId())) {
					info.setId(preInfo.getOldId());
				}
				tEmpProfessionalQualificationList.add(info);
			}
			tEmpProfessionalQualificationService.saveOrUpdateBatch(tEmpProfessionalQualificationList);
		}
		// 预入职-员工工作履历信息表
		List<TPreEmpWorkRecording> tPreEmpWorkRecordingList = vo.getTPreEmpWorkRecording();
		if (tPreEmpWorkRecordingList != null) {
			// 先删除其他信息
			tEmpFamilyService.deleteByEmpIdAndTable(empId, "t_pre_emp_work_recording");
			List<TEmpWorkRecording> tEmpWorkRecordingList = new ArrayList<>();
			TEmpWorkRecording info;
			for (TPreEmpWorkRecording preInfo : tPreEmpWorkRecordingList) {
				info = new TEmpWorkRecording();
				BeanUtil.copyProperties(tPreEmpContactInfo, info);
				if (Common.isNotNull(preInfo.getOldId())) {
					info.setId(preInfo.getOldId());
				}
				tEmpWorkRecordingList.add(info);
			}
			tEmpWorkRecordingService.saveOrUpdateBatch(tEmpWorkRecordingList);
		}
		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.getByEmpIdAndDeptId(tPreEmployeeProject.getEmpIdcard(), tPreEmployeeProject.getDeptId());
			if (project == null) {
				project = tEmployeeProjectService.getByEmpIdAndDeptIdAndDelete(tPreEmployeeProject.getEmpIdcard(), tPreEmployeeProject.getDeptId());
				if (project != null) {
					project.setProjectStatus(CommonConstants.ZERO_INT);
					project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
				}
			}
			isNew = false;
			if (project == null) {
				isNew = true;
				project = new TEmployeeProject();
			}
			BeanUtil.copyProperties(tPreEmployeeProject, project);
			if (isNew) {
				// 新项目档案塞基本属性
				this.setNewEmpProjectBaseData(project, emp, dept, user);
			}
			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.setDeleteFlag(CommonConstants.STATUS_NORMAL);
			}
		}
		boolean isNew = false;
		if (emp == null) {
			isNew = true;
			emp = new TEmployeeInfo();
		}
		BeanUtil.copyProperties(tPreEmployeeInfo, emp);
		if (isNew) {
			// 新员工塞基本属性
			this.setNewEmpBaseData(emp, user);
		}
		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()).replaceAll("-", ""));
		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);
		}
		//员工编码生成规则
		insTEmployeePro.setEmpCode(tEmployeeInfo.getEmpCode());
		insTEmployeePro.setCreateBy(user.getId());
		insTEmployeePro.setEmpName(tEmployeeInfo.getEmpName());
		insTEmployeePro.setCreateName(user.getNickname());
		insTEmployeePro.setProjectSource(CommonConstants.SIX_STRING);
		insTEmployeePro.setEmpId(tEmployeeInfo.getId());
	}


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

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

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

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

	/**
	 * 预入职-主表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TPreEmpMainSearchVo searchVo) {
		String fileName = "预入职-主表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TPreEmpMain> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TPreEmpMain.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(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 = EasyExcel.writerSheet("预入职-主表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("预入职-主表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	@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 Long noPageCountDiy(TPreEmpMainSearchVo searchVo) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TPreEmpMain::getId, idList);
		}
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TPreEmpMainSearchVo entity) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TPreEmpMain::getCreateTime, entity.getCreateTimes()[0])
					.le(TPreEmpMain::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TPreEmpMain::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TPreEmpMainVo> util1 = new ExcelUtil<>(TPreEmpMainVo.class);
		;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.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 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);
		}
		return R.ok(errorMessageList);
	}

	private void importTPreEmpMain(List<TPreEmpMainVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TPreEmpMainVo excel = excelVOList.get(i);
			// 数据合法情况 TODO

			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TPreEmpMainVo excel) {
		TPreEmpMain insert = new TPreEmpMain();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}
}
