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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.constants.EmployeeConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpEducationMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TBusinessEmployeeExtendInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeLogService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.DoJointTask;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.EmpBusinessConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSocialProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 项目档案表
 *
 * @author huyc
 * @date 2022-06-20 09:19:40
 */
@Service
@RequiredArgsConstructor
@Log4j2
@EnableConfigurationProperties({DaprUpmsProperties.class, DaprCheckProperties.class, DaprSocialProperties.class})
public class TEmployeeProjectServiceImpl extends ServiceImpl<TEmployeeProjectMapper, TEmployeeProject> implements TEmployeeProjectService {

	@Autowired
	private TEmployeeLogService tEmployeeLogService;

	@Autowired
	private TEmployeeInfoMapper tEmployeeInfoMapper;

	@Autowired
	private TSettleDomainService tSettleDomainService;

	@Autowired
	private TEmployeeContractInfoMapper contractInfoMapper;

	@Autowired
	private TEmpEducationMapper empEducationMapper;

	@Autowired
	private TBusinessEmployeeExtendInfoService businessEmployeeExtendInfoService;

	@Autowired
	private DaprSocialProperties daprSocialProperties;

	@Autowired
	@Lazy
	private DoJointTask doJointTask;

	@Override
	public R addCheck(TEmployeeProject tEmployeeProject) {

		Map<String, Object> map = new HashMap<>();

		//身份证系统中是否已有
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));

		//项目下已有身份证信息
		TEmployeeProject employeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeProject::getDeptNo, tEmployeeProject.getDeptNo())
				.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL));
		if (!Common.isEmpty(employeeProject)) {

			//身份证实名认证
			if (!Common.isEmpty(tEmployeeInfo) && !tEmployeeProject.getEmpName().equals(tEmployeeInfo.getEmpName())) {
				return R.failed("姓名和身份证不一致，请确认后再次新增");
			}

			//项目状态为已减项
			if (CommonConstants.dingleDigitIntArray[1] == employeeProject.getProjectStatus() &&
					!Common.isEmpty(tEmployeeInfo)) {
				map.put("empProId", employeeProject.getId());
				if (CommonConstants.dingleDigitIntArray[0] == tEmployeeInfo.getFileStatus()) {
					return new R<>(CommonConstants.dingleDigitIntArray[4], "该人员已减项，是否“复项”", map);
				} else {
					map.put("employeeId", tEmployeeInfo.getId());
					return new R<>(CommonConstants.dingleDigitIntArray[2], "该人员已减档减项，是否“复档复项”", map);
				}
			}
			//状态为草稿、已审核
			if (CommonConstants.dingleDigitIntArray[0] == employeeProject.getStatus() ||
					CommonConstants.dingleDigitIntArray[1] == employeeProject.getStatus()) {
				return R.failed("人员已有该项目信息，禁止重复添加！");
			}
		} else {
			if (Common.isEmpty(tEmployeeInfo)) {
				return R.failed("该人员暂无档案信息，禁止关联项目，如要添加，请先至“在档人员”处建档");
				//身份证实名认证
			} else if (!tEmployeeProject.getEmpName().equals(tEmployeeInfo.getEmpName())) {
				return R.failed("姓名和身份证不一致，请确认后再次新增");
			}
			//判断是否已经减档
			if (tEmployeeInfo.getFileStatus() == CommonConstants.dingleDigitIntArray[1]) {
				map.put("employeeId", tEmployeeInfo.getId());
				return new R<>(CommonConstants.dingleDigitIntArray[3], "该人员在离职库已存在，是否“恢复档案”", map);
			}
		}
		//项目编码校验
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, tEmployeeProject.getDeptNo())
				.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
				.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING));
		if (Common.isEmpty(tSettleDomain)) {
			return R.failed("未找到对应的项目或者项目已停止合作，请核实");
		}
		return R.ok();
	}

	@Override
	public R saveEmp(TEmployeeProject tEmployeeProject) {
		//查询人员档案
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT));
		if (Common.isNotNull(tEmployeeInfo)) {

			TEmployeeInfo tEmployeeInfoCompare = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());

			//获取项目和单位信息
			TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDepartNo, tEmployeeProject.getDeptNo()).eq(TSettleDomain::getDeleteFlag,
							CommonConstants.STATUS_NORMAL)
					.eq(TSettleDomain::getStopFlag, CommonConstants.STATUS_NORMAL));
			if (Common.isNotNull(tSettleDomain)) {
				tEmployeeProject.setDeptId(tSettleDomain.getId());
				tEmployeeProject.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
				tEmployeeProject.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
				tEmployeeProject.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
				tEmployeeProject.setUnitId(tSettleDomain.getCustomerId());
				tEmployeeProject.setUnitNo(tSettleDomain.getCustomerNo());
				tEmployeeProject.setUnitName(tSettleDomain.getCustomerName());
				String empNO = getEmpNo(tEmployeeProject.getDeptNo());
				tEmployeeProject.setEmpNo(empNO);
			}
			tEmployeeProject.setEmpId(tEmployeeInfo.getId());
			tEmployeeProject.setProjectSource(CommonConstants.dingleDigitStrArray[5]);
			this.save(tEmployeeProject);

			if (CommonConstants.ZERO_STRING.equals(tEmployeeProject.getEmpNatrue())) {
				tEmployeeInfo.setEmpNatrue(CommonConstants.ZERO_STRING);
			} else if (CommonConstants.ONE_STRING.equals(tEmployeeProject.getEmpNatrue()) &&
					!CommonConstants.ZERO_STRING.equals(tEmployeeInfo.getEmpNatrue())) {
				tEmployeeInfo.setEmpNatrue(CommonConstants.ONE_STRING);
			}
			tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() + CommonConstants.ONE_INT);
			tEmployeeInfoMapper.updateById(tEmployeeInfo);
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],
					tEmployeeInfoCompare.getId(), "", tEmployeeInfoCompare, tEmployeeInfo);
			return R.ok();
		}
		return R.failed("未在人员档案中查到身份信息");
	}

	@Override
	public R updateProject(TEmployeeProject tEmployeeProject) {
		TEmployeeProject compareProject = this.getById(tEmployeeProject.getId());
		boolean flag = this.updateById(tEmployeeProject);
		TEmployeeProject newProject = this.getById(tEmployeeProject.getId());
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT));
		if (Common.isNotNull(tEmployeeInfo)) {
			TEmployeeInfo tEmployeeInfoCompare = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());
			//查询该人员所有的的项目档案
			List<TEmployeeProject> list = this.list(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, tEmployeeProject.getEmpIdcard())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));

			//从剩下的项目档案中查找员工类型并更新
			if (Common.isNotNull(list)) {
				Set<String> empNatrue = list.stream().map(TEmployeeProject::getEmpNatrue).collect(Collectors.toSet());
				if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.THREE_STRING))) {
					tEmployeeInfo.setEmpNatrue(CommonConstants.THREE_STRING);
				} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ZERO_STRING))) {
					tEmployeeInfo.setEmpNatrue(CommonConstants.ZERO_STRING);
				} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ONE_STRING))) {
					tEmployeeInfo.setEmpNatrue(CommonConstants.ONE_STRING);
				} else {
					tEmployeeInfo.setEmpNatrue(CommonConstants.TWO_STRING);
				}
			}

			tEmployeeInfoMapper.updateById(tEmployeeInfo);
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],
					tEmployeeInfoCompare.getId(), "", tEmployeeInfoCompare, tEmployeeInfo);
		}
		tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
				tEmployeeProject.getId(), compareProject, newProject);
		return R.ok(flag);
	}

	@Override
	@Transactional
	public R removeProjectInfo(String id) {

		TEmployeeProject tEmployeeProject = this.getById(id);
		//对比对象
		TEmployeeProject compareProject = this.getById(id);

		if (tEmployeeProject.getInsuranceStatus() != CommonConstants.dingleDigitIntArray[0] ||
				tEmployeeProject.getSocialStatus() != CommonConstants.dingleDigitIntArray[0] ||
				tEmployeeProject.getFundStatus() != CommonConstants.dingleDigitIntArray[0]) {

			return R.failed("人员在该项目下存在进行中/未完结的服务,禁止删除");
		}

		//逻辑删除项目档案
		tEmployeeProject.setDeleteFlag(CommonConstants.ONE_STRING);
		baseMapper.updateById(tEmployeeProject);

		//更新操作记录
		tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
				tEmployeeProject.getId(), compareProject, tEmployeeProject);

		List<TEmployeeInfo> updList = new ArrayList<>();
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT));

		if (Common.isNotNull(tEmployeeInfo)) {
			updList.add(tEmployeeInfo);
			YifuUser user = SecurityUtils.getUser();
			doJointTask.doUpdateEmployeeInfo(updList, user);
		}
		return R.ok();
	}

	@Override
	public R reEmpInfo(JSONObject jsonObject) {
		if (Common.isNotNull(jsonObject)) {
			String empId = jsonObject.getString("empId");
			String empProId = jsonObject.getString("empProId");

			TEmployeeInfo tEmployeeInfoOld;
			TEmployeeProject tEmployeeProjectOld;
			if (!Common.isEmpty(empId) && Common.isEmpty(empProId)) {
				//复档
				tEmployeeInfoOld = tEmployeeInfoMapper.selectById(empId);
				TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(empId);
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[0]);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], empId,
						"", tEmployeeInfoOld, tEmployeeInfo);
			} else if (Common.isEmpty(empId) && !Common.isEmpty(empProId)) {
				//复项
				tEmployeeProjectOld = this.getById(empProId);
				TEmployeeProject tEmployeeProject = this.getById(empProId);
				tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[0]);
				this.updateById(tEmployeeProject);

				TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
						.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
						.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL)
						.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT));

				if (Common.isNotNull(tEmployeeInfo)) {
					tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());
					//查询该人员所有的的项目档案
					List<TEmployeeProject> list = this.list(Wrappers.<TEmployeeProject>query().lambda()
							.eq(TEmployeeProject::getEmpIdcard, tEmployeeProject.getEmpIdcard())
							.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
							.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));

					//从剩下的项目档案中查找员工类型并更新
					if (Common.isNotNull(list)) {
						Set<String> empNatrue = list.stream().map(TEmployeeProject::getEmpNatrue).collect(Collectors.toSet());
						if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.THREE_STRING))) {
							tEmployeeInfo.setEmpNatrue(CommonConstants.THREE_STRING);
						} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ZERO_STRING))) {
							tEmployeeInfo.setEmpNatrue(CommonConstants.ZERO_STRING);
						} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ONE_STRING))) {
							tEmployeeInfo.setEmpNatrue(CommonConstants.ONE_STRING);
						} else {
							tEmployeeInfo.setEmpNatrue(CommonConstants.TWO_STRING);
						}
					}
					tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() + CommonConstants.ONE_INT);
					tEmployeeInfoMapper.updateById(tEmployeeInfo);
					tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],
							tEmployeeInfo.getId(), "", tEmployeeInfoOld, tEmployeeInfo);
				}
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],
						"", empProId, tEmployeeProjectOld, tEmployeeProject);
			} else {
				tEmployeeInfoOld = tEmployeeInfoMapper.selectById(empId);
				tEmployeeProjectOld = this.getById(empProId);
				//复档复项
				TEmployeeProject tEmployeeProject = this.getById(empProId);
				tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[0]);
				this.updateById(tEmployeeProject);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],
						"", empProId, tEmployeeProjectOld, tEmployeeProject);

				TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(empId);
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[0]);

				//查询该人员所有的的项目档案
				List<TEmployeeProject> list = this.list(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getEmpIdcard, tEmployeeProject.getEmpIdcard())
						.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
						.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));

				//从剩下的项目档案中查找员工类型并更新
				if (Common.isNotNull(list)) {
					Set<String> empNatrue = list.stream().map(TEmployeeProject::getEmpNatrue).collect(Collectors.toSet());
					if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.THREE_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.THREE_STRING);
					} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ZERO_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.ZERO_STRING);
					} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ONE_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.ONE_STRING);
					} else {
						tEmployeeInfo.setEmpNatrue(CommonConstants.TWO_STRING);
					}
				}
				tEmployeeInfo.setProjectNum(CommonConstants.ONE_INT);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], empId,
						"", tEmployeeInfoOld, tEmployeeInfo);
			}
		} else {
			return R.failed("传参为空！");
		}
		return R.ok();
	}

	@Override
	public R deleteEmpPro(TEmployeeProject tEmployeeProject) {
		if (Common.isNotNull(tEmployeeProject)) {
			TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
			TEmployeeProject tEmployeeProjectOld = this.getById(tEmployeeProject.getId());
			String code = "";
			StringBuilder errorTemp = new StringBuilder();
			if (tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[1]
					||tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[2]
					||tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[3]) {
				errorTemp.append("社保未派减、");
			}
			if (tEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[1]
					||tEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[2]) {
				errorTemp.append("公积金未派减、");
			}
			// 未作废，在用 或 审核中
			long contractCount = contractInfoMapper.selectCount(Wrappers.<TEmployeeContractInfo>query().lambda()
					.eq(TEmployeeContractInfo::getEmpIdcard,tEmployeeProject.getEmpIdcard())
					.eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
					.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
					.eq(TEmployeeContractInfo::getDeptNo,tEmployeeProject.getDeptNo())
					.and(obj->obj.eq(TEmployeeContractInfo::getInUse,CommonConstants.ZERO_STRING)
					.or()
					.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ZERO_STRING)
					.or()
					.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ONE_STRING))
			);
			if (contractCount > CommonConstants.ZERO_INT){
				errorTemp.append("合同可用或在途、");
			}
			if (Common.isNotNull(errorTemp.toString())){
				return R.failed(errorTemp.substring(0,errorTemp.length()-1) +",禁止减项");
			}
			tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[1]);
			tEmployeeProject.setLeaveTime(LocalDateTime.now());
			this.updateById(tEmployeeProject);

			TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());

			//查询该人员其他的项目档案
			List<TEmployeeProject> list = this.list(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, tEmployeeProject.getEmpIdcard())
					.ne(TEmployeeProject::getDeptNo, tEmployeeProject.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));

			if (tEmployeeProject.getIsLeaveEmployee() == CommonConstants.dingleDigitIntArray[1]) {
				if (Common.isNotNull(list)) {
					return R.failed("该人员存在其他进行中的项目，禁止同步减档！");
				}
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[1]);
				tEmployeeInfo.setLeaveReason(tEmployeeProject.getLeaveReason());
				if (Common.isNotNull(tEmployeeProject.getLeaveRemark())) {
					tEmployeeInfo.setLeaveRemark(tEmployeeProject.getLeaveRemark());
				}
				tEmployeeInfo.setLeaveTime(DateUtil.getCurrentDateTime());
				YifuUser user = SecurityUtils.getUser();
				tEmployeeInfo.setLeaveUser(user.getId());
				tEmployeeInfo.setLeaveUserName(user.getNickname());
				code = CommonConstants.ONE_STRING;
			} else {
				//从剩下的项目档案中查找员工类型并更新
				if (Common.isNotNull(list)) {
					Set<String> empNatrue = list.stream().map(TEmployeeProject::getEmpNatrue).collect(Collectors.toSet());
					if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.THREE_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.THREE_STRING);
					} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ZERO_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.ZERO_STRING);
					} else if (empNatrue.stream().anyMatch(e -> e.equals(CommonConstants.ONE_STRING))) {
						tEmployeeInfo.setEmpNatrue(CommonConstants.ONE_STRING);
					} else {
						tEmployeeInfo.setEmpNatrue(CommonConstants.TWO_STRING);
					}
				}
			}
			if (tEmployeeInfo.getProjectNum() != CommonConstants.ZERO_INT) {
				tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() - CommonConstants.ONE_INT);
			}
			tEmployeeInfoMapper.updateById(tEmployeeInfo);
			TEmployeeProject newInfo = this.getById(tEmployeeProject.getId());

			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], tEmployeeInfo.getId(),
					"", tEmployeeInfoOld, tEmployeeInfo);
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
					tEmployeeProject.getId(), tEmployeeProjectOld, newInfo);
			if (CommonConstants.ONE_STRING.equals(code)) {
				return R.ok(null, "减项减档成功");
			} else {
				return R.ok(null, "减项成功，项目状态已更新为“已减项”");
			}
		}
		return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	}

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

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

				@Override
				public void invoke(EmployeeXProjectVO 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());
					deleteListAdd(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);
	}

	public R<List<ErrorMessage>> deleteListAdd(List<EmployeeXProjectVO> excelVOList, List<ErrorMessage> errorMessageList) {

		//项目档案更新list
		List<TEmployeeProject> updProjectList = new ArrayList<>();
		//人员档案更新list
		List<TEmployeeInfo> updList = new ArrayList<>();
		// 新老项目档案vo
		EmployeeProjectNewOldVO newOldProject;
		// 新老项目档案List
		List<EmployeeProjectNewOldVO> updateProjectList = new ArrayList<>();
		String leaveReason;
		// 渲染字典值
		Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
				CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "social_reduce_reason");

		TEmployeeProject tEmployeeProject;
		TEmployeeInfo tEmployeeInfo;
		TEmployeeProject tEmployeeProjectOld;
		// 在途和在用合同数目
		long contractCount;
		StringBuilder  errorTemp;
		StringBuilder errorMessage;
		// 执行数据插入操作 组装 PostDto
		for (EmployeeXProjectVO excel : excelVOList) {
			//根据身份证和项目编码获取项目档案
			tEmployeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeProject::getDeptNo, excel.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));

			leaveReason = null == dicObj? "":dicObj.get(excel.getLeaveReason());

			errorMessage = new StringBuilder();
			if (Common.isNotNull(excel.getEmpName())) {
				errorMessage.append(excel.getEmpName());
				errorMessage.append(";");
			}
			errorMessage.append(excel.getEmpIdcard());
			errorMessage.append(";");
			errorMessage.append(excel.getDeptNo());
			errorMessage.append(";");
			errorMessage.append(leaveReason);
			errorMessage.append(";");
			if (Common.isNotNull(excel.getLeaveRemark())) {
				errorMessage.append(excel.getLeaveRemark());
				errorMessage.append(";");
			}
			if (Common.isNotNull(tEmployeeProject)) {
				errorTemp = new StringBuilder();
				if (tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[1]
						||tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[2]
						||tEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[3]) {
					errorTemp.append("社保未派减、");
				}
				if (tEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[1]
						||tEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[2]) {
					errorTemp.append("公积金未派减、");
				}
				// 未作废，在用 或 审核中
				contractCount = contractInfoMapper.selectCount(Wrappers.<TEmployeeContractInfo>query().lambda()
						.eq(TEmployeeContractInfo::getEmpIdcard,tEmployeeProject.getEmpIdcard())
						.eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
						.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
						.eq(TEmployeeContractInfo::getDeptNo,tEmployeeProject.getDeptNo())
						.and(obj->obj.eq(TEmployeeContractInfo::getInUse,CommonConstants.ZERO_STRING)
						.or()
						.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ZERO_STRING)
						.or()
						.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ONE_STRING))
				);
				if (contractCount > CommonConstants.ZERO_INT){
					errorTemp.append("合同可用或在途、");
				}
				if (Common.isNotNull(errorTemp.toString())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorMessage +errorTemp.substring(0,errorTemp.length()-1) +",禁止减项"));
					break;
				}
				tEmployeeProjectOld = this.getById(tEmployeeProject.getId());
				tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[1]);
				tEmployeeProject.setLeaveReason(excel.getLeaveReason());
				tEmployeeProject.setLeaveRemark(excel.getLeaveRemark());
				tEmployeeProject.setLeaveTime(LocalDateTime.now());
				updProjectList.add(tEmployeeProject);

				newOldProject = new EmployeeProjectNewOldVO();
				newOldProject.setOldProjectEmployee(tEmployeeProjectOld);
				newOldProject.setNewProjectEmployee(tEmployeeProject);
				updateProjectList.add(newOldProject);

				tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
				//从剩下的项目档案中查找员工类型并更新
				updList.add(tEmployeeInfo);
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorMessage +
						MsgUtils.getMessage(ErrorCodes.PROJECT_PERSON_SEARCH_EXIT)));
			}
		}
		if (!errorMessageList.isEmpty()) {
			return R.failed(errorMessageList);
		} else {
			YifuUser user = SecurityUtils.getUser();
			//更新项目档案
			if (!updProjectList.isEmpty()) {
				baseMapper.updateReduceEmpProject(updProjectList);
			}
			//更新人员档案
			if (!updList.isEmpty()) {
				List<TEmployeeInfo> updEmpInfoList = updList.stream().distinct().collect(Collectors.toList());
				doJointTask.doUpdateEmployeeInfo(updEmpInfoList, user);
			}
			// 记录变更日志
			if (!updateProjectList.isEmpty()) {
				doJointTask.saveModificationRecord(updateProjectList,user);
			}
		}
		return R.ok();
	}

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

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

				@Override
				public void invoke(EmployeeProjectVO 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());
					importListAdd(cachedDataList, errorMessageList, isAdd);
					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);
	}

	/**
	 * 新增档案
	 *
	 * @param excelVOList
	 * @param errorMessageList
	 * @param idAdd
	 * @author huyc
	 * @date 2022-06-20 18:52:16
	 */
	@Transactional
	public void importListAdd(List<EmployeeProjectVO> excelVOList, List<ErrorMessage> errorMessageList, String idAdd) {
		// 通用校验获取失败的数据
		List<TEmployeeInfo> updateList = new ArrayList<>();
		List<TEmployeeProject> proInsList = new ArrayList<>();
		List<TEmployeeProject> proupdateList = new ArrayList<>();

		// 获取身份证、手机号列表，批量查询档案
		Map<String, Integer> idCardMap = new HashMap<>();
		String idCard;
		String deptNo;

		TSettleDomain tSettleDomain;
		TEmployeeInfo tEmployeeInfo;
		TEmployeeProject tEmployeeProject;
		EmployeeProjectVO excel;
		// 执行数据插入操作 组装 PostDto
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);

			idCard = excel.getEmpIdcard();
			deptNo = excel.getDeptNo();
			if (excel.getEmpNatrue().equals(CommonConstants.ZERO_STRING)
					|| excel.getEmpNatrue().equals(CommonConstants.ONE_STRING)
					|| excel.getEmpNatrue().equals(CommonConstants.THREE_STRING)) {
				if (excel.getContractType().equals(CommonConstants.ONE_STRING) && Common.isEmpty(excel.getWorkingHours())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "工时制不能为空！"));
				}
				if (Common.isEmpty(excel.getEnjoinDate())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "入职日期不能为空！"));
				}
				if (Common.isEmpty(excel.getTryPeriod())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "试用期不能为空！"));
				}
			}
			if (idCardMap.get(idCard.concat(deptNo)) != null) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "第" + (excel.getRowIndex())
						+ "行身份证号+项目编码与第" + idCardMap.get(idCard) + "行重复！"));
			} else {
				idCardMap.put(idCard.concat(deptNo), i + 2);
			}

			//根据身份证获取人员档案
			tEmployeeInfo= tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
					.eq(TEmployeeInfo::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));
			//根据身份证和项目编码获取项目档案
			tEmployeeProject = baseMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeProject::getDeptNo, excel.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL));

			//状态为草稿、已审核
			if (Common.isNotNull(tEmployeeProject) && CommonConstants.ZERO_INT == tEmployeeProject.getProjectStatus()) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeConstants.EXIT_PRIJECT_STATUS));
			}
			//不存在复档或复项的情况
			//档案无（在档人员、离职库皆无），项目无
			if (Common.isEmpty(tEmployeeInfo) && Common.isEmpty(tEmployeeProject)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_EXIT_EMPPROJECT_ERROR)));
				//档案有（在档人员），项目无
			} else if (Common.isNotNull(tEmployeeInfo) && Common.isEmpty(tEmployeeProject)
					&& CommonConstants.ZERO_INT == tEmployeeInfo.getFileStatus()) {
				//项目编码校验
				tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
						.eq(TSettleDomain::getDepartNo, excel.getDeptNo())
						.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
						.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING));
				if (Common.isEmpty(tSettleDomain)) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.PROJECT_SEARCH_NOT_EXIST)));
				}
				updateExcelPost(updateList, tEmployeeInfo);
				insertExcelPro(excel, proInsList, tEmployeeInfo,tSettleDomain);
				//档案有（在档人员），项目有（草稿/已审核）；
			} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.ZERO_INT == tEmployeeInfo.getFileStatus()
					&& Common.isNotNull(tEmployeeProject) && CommonConstants.ZERO_INT == tEmployeeProject.getProjectStatus()) {
				updateExcelPost(updateList, tEmployeeInfo);
				updateExcelPro(excel, proupdateList, tEmployeeProject);
			}

			//存在复档或复项的情况，允许复档复项
			if (Common.isNotNull(tEmployeeInfo)) {
				if (CommonConstants.ONE_STRING.equals(idAdd)) {
					//档案有（离职库），项目（已减档）
					if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus() && Common.isNotNull(tEmployeeProject)
							&& CommonConstants.ONE_INT == tEmployeeProject.getProjectStatus()) {
						updateExcelPro(excel, proupdateList, tEmployeeProject);
						//档案有（离职库），项目无；
					} else if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus()
							&& Common.isEmpty(tEmployeeProject)) {
						//项目编码校验
						tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
								.eq(TSettleDomain::getDepartNo, excel.getDeptNo())
								.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
								.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING));
						if (Common.isEmpty(tSettleDomain)) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.PROJECT_SEARCH_NOT_EXIST)));
						}
						insertExcelPro(excel, proInsList, tEmployeeInfo, tSettleDomain);
						//档案有（在档人员），项目（已减档）
					} else if (CommonConstants.ZERO_INT == tEmployeeInfo.getFileStatus() && Common.isNotNull(
							tEmployeeProject) && CommonConstants.ONE_INT == tEmployeeProject.getProjectStatus()) {
						updateExcelPro(excel, proupdateList, tEmployeeProject);
					}
					updateExcelPost(updateList, tEmployeeInfo);
					//不允许复档复项
				} else {
					//档案有（离职库），项目（已减档）
					if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus()
							&& Common.isNotNull(tEmployeeProject) && CommonConstants.ONE_INT == tEmployeeProject.getProjectStatus()) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_EMP_PROJECT_ERROR)));
					} else if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus()
							&& Common.isEmpty(tEmployeeProject)) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_REDUCE_EMP_ERROR)));
						//档案有（在档人员），项目（已减档）
					} else if (CommonConstants.ZERO_INT == tEmployeeInfo.getFileStatus()
							&& Common.isNotNull(tEmployeeProject) && CommonConstants.ONE_INT == tEmployeeProject.getProjectStatus()) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_REDUCE_PROJECT_ERROR)));
					}
				}
			}
		}

		if (CollUtil.isEmpty(errorMessageList)) {
			try {
				if (!updateList.isEmpty()) {
					YifuUser user = SecurityUtils.getUser();
					doJointTask.doUpdateEmployeeInfo(updateList, user);
				}
				if (!proInsList.isEmpty()) {
					baseMapper.insertExcelEmpProject(proInsList);
				}
				if (!proupdateList.isEmpty()) {
					baseMapper.updateExcelEmpProject(proupdateList);
				}
			} catch (Exception e) {
				log.error("数据更新异常", e);
			}
		}
	}

	@Override
	@Transactional
	public R<List<ErrorMessage>> importEmpProjectUpdate(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeProjectUpdateVO> util1 = new ExcelUtil<>(EmployeeProjectUpdateVO.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, EmployeeProjectUpdateVO.class, new ReadListener<EmployeeProjectUpdateVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmployeeProjectUpdateVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeProjectUpdateVO 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());
					importEmpProjectUpdate(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);
	}

	/**
	 * @Author huyc
	 * @Description 批量更新项目档案信息
	 * @Date 19:25 2022/6/21
	 **/
	public void importEmpProjectUpdate(List<EmployeeProjectUpdateVO> excelVOList, List<ErrorMessage> errorMessageList) {

		// 项目档案更新List
		List<TEmployeeProject> updateList = new ArrayList<>();
		// 人员档案更新List
		List<TEmployeeInfo> updTEmployeeList = new ArrayList<>();

		Map<String, Integer> checkCountMap = new HashMap<>();

		// 新老项目档案vo
		EmployeeProjectNewOldVO newOldProject;
		// 新老项目档案List
		List<EmployeeProjectNewOldVO> updateProjectList = new ArrayList<>();

		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			EmployeeProjectUpdateVO excel = excelVOList.get(i);

			String checkCount = excel.getEmpIdcard().concat(excel.getDeptNo());
			if (Common.isNotNull(checkCountMap.get(checkCount))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "第" + (excel.getRowIndex()) + "行身份证号+项目编码与第" + checkCountMap.get(checkCount) + "行重复！"));
			} else {
				checkCountMap.put(checkCount, i + 2);
			}
			//根据身份证和项目编码获取项目档案
			TEmployeeProject tEmployeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeProject::getDeptNo, excel.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL));
			if (Common.isEmpty(tEmployeeProject)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_EMP_EXIT_ERROR)));
			} else {
				if (tEmployeeProject.getProjectStatus() != CommonConstants.dingleDigitIntArray[0]) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.CHECKS_EMP_DELETE_ERROR)));
				} else {
					updateExcelProj(excel, updateList, tEmployeeProject);
					TEmployeeProject tEmployeeProjectOld = this.getById(tEmployeeProject.getId());
					newOldProject = new EmployeeProjectNewOldVO();
					newOldProject.setOldProjectEmployee(tEmployeeProjectOld);
					newOldProject.setNewProjectEmployee(tEmployeeProject);
					updateProjectList.add(newOldProject);

					TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
							.eq(TEmployeeInfo::getEmpIdcard, excel.getEmpIdcard())
							.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT)
							.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));
					updTEmployeeList.add(tEmployeeInfo);
				}
			}
		}

		// 数据合法情况
		if (CollUtil.isEmpty(errorMessageList)) {
			try {
				if (updateList.size() > CommonConstants.dingleDigitIntArray[0]) {
					baseMapper.updateExcelEmpProject(updateList);
				}
				if (updTEmployeeList.size() > CommonConstants.dingleDigitIntArray[0]) {
					List<TEmployeeInfo> updEmpInfoList = updTEmployeeList.stream().distinct().collect(Collectors.toList());
					YifuUser user = SecurityUtils.getUser();
					doJointTask.doUpdateEmployeeInfo(updEmpInfoList, user);
				}
				// 记录变更日志
				if (updateProjectList.size() > CommonConstants.dingleDigitIntArray[0]) {
					for (EmployeeProjectNewOldVO newOldProjectLog : updateProjectList) {
						tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1]
								, newOldProjectLog.getNewProjectEmployee().getId(), ""
								, newOldProjectLog.getOldProjectEmployee(), newOldProjectLog.getNewProjectEmployee());
					}
				}
			} catch (Exception e) {
				log.error("数据更新异常", e);
			}
		}
	}

	/**
	 * 插入excel Pro
	 */
	private void insertExcelPro(EmployeeProjectVO excel, List<TEmployeeProject> proInsList, TEmployeeInfo tEmployeeInfo,
								TSettleDomain tSettleDomain) {

		TEmployeeProject insTEmployeePro = new TEmployeeProject();
		BeanUtil.copyProperties(excel, insTEmployeePro);
		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 = getEmpNo(insTEmployeePro.getDeptNo());
			insTEmployeePro.setEmpNo(empNO);
		}
		//员工编码生成规则
		insTEmployeePro.setEmpCode(tEmployeeInfo.getEmpCode());
		YifuUser user = SecurityUtils.getUser();
		insTEmployeePro.setCreateBy(user.getId());
		insTEmployeePro.setEmpName(tEmployeeInfo.getEmpName());
		insTEmployeePro.setCreateName(user.getNickname());
		insTEmployeePro.setProjectSource(CommonConstants.SIX_STRING);
		insTEmployeePro.setEmpId(tEmployeeInfo.getId());
		proInsList.add(insTEmployeePro);
	}

	@Override
	@Transactional
	public R<List<ErrorMessage>> batchRemoveByIds(List<String> ids) {
		List<ErrorMessage> errorList = new ArrayList<>();

		List<TEmployeeProject> updList = new ArrayList<>();

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

		if (Common.isEmpty(ids)) {
			return R.failed(ErrorCodes.PARAM_NOT_EMPTY);
		}
		List<TEmployeeProject> list = new ArrayList<>();
		if (Common.isNotEmpty(ids)) {
			list = baseMapper.selectList(Wrappers.<TEmployeeProject>query().lambda().in(TEmployeeProject::getId, ids)
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT));
		}
		if (Common.isNotEmpty(list)) {
			int i = 0;
			for (TEmployeeProject delProject : list) {
				++i;
				try {
					if (CommonConstants.dingleDigitIntArray[0] == delProject.getStatus()) {
						delProject.setDeleteFlag(CommonConstants.ONE_STRING);
						updList.add(delProject);
						TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
								.eq(TEmployeeInfo::getEmpIdcard, delProject.getEmpIdcard())
								.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));
						infoUpdList.add(tEmployeeInfo);
					} else {
						errorList.add(new ErrorMessage(i, delProject.getEmpName() + ";" +
								delProject.getEmpIdcard() + ";" + delProject.getDeptNo() + ";" + "项目档案状态为已审核，禁止删除"));
					}
				} catch (Exception e) {
					log.error("项目档案批量删除异常：" + e.getMessage());
					errorList.add(new ErrorMessage(i, MsgUtils.getMessage("项目档案批量删除异常：", e.getMessage())));
					return R.failed(errorList, CommonConstants.RESULT_DATA_FAIL);
				}
			}
		}
		if (CollUtil.isNotEmpty(errorList)) {
			return R.failed(errorList);
		} else {
			if (!updList.isEmpty()) {
				for (TEmployeeProject tEmployeeProject : updList) {
					baseMapper.updateById(tEmployeeProject);
				}
			}
			if (!infoUpdList.isEmpty()) {
				YifuUser user = SecurityUtils.getUser();
				doJointTask.doUpdateEmployeeInfo(infoUpdList, user);
			}
		}
		return R.ok();
	}

	@Override
	public IPage<TEmployeeProject> getTEmployeeProjectInfoPage(Page page, TEmployeeProject tEmployeeProject) {
		return baseMapper.getTEmployeeProjectInfoPage(page, tEmployeeProject);
	}


	/**
	 * @Author huyc
	 * @Description 批量导出项目档案信息
	 * @Date 10:55 2022/6/23
	 **/
	@Override
	public void listExportProject(HttpServletResponse response, EmployeeProjectExportParamVO searchVo, List<String> exportFields) {
		String fileName = "项目档案批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		// 根据用户传入确定要导出的字段
		Set<String> includeColumnFiledNames = new HashSet<>(exportFields);
		//获取要导出的列表  gettEmpProInfoExportVos
		List<EmployeeProjectExportVO> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		try (ServletOutputStream 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"));
			ExcelUtil<EmployeeProjectExportVO> util = new ExcelUtil<>(EmployeeProjectExportVO.class);
			// 获取所有字典type
			Map<String,String> nameAndDicTypeMap = util.getConverterDicType();
			// 获取所有字典对应的值
			Map<String,String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, EmployeeProjectExportVO.class)
					.registerConverter(new DictConverter(nameAndDicTypeMap,redisLabelMap))
					.includeColumnFieldNames(includeColumnFiledNames).build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				WriteSheet writeSheet;
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet("项目档案批量导出"+index).build();
						excelWriter.write(list,writeSheet);
						index++;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("项目档案批量导出"+index).build();
				excelWriter.write(list,writeSheet);
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			excelWriter.finish();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}
	}

	private List<EmployeeProjectExportVO> noPageDiy(EmployeeProjectExportParamVO searchVo) {
		return baseMapper.noPageDiy(searchVo);
	}

	private int noPageCountDiy(EmployeeProjectExportParamVO searchVo) {
		return baseMapper.noPageCountDiy(searchVo);
	}

	/**
	 * @param employeeInfo
	 * @Description: 新增项目档案
	 * @Author: huyc
	 * @Date: 2022/6/23 18:06
	 **/
	@Override
	public void saveEmployeeProjectInfo(TEmployeeInfo employeeInfo) {
		TEmployeeProject tEmployeeProject = new TEmployeeProject();
		tEmployeeProject.setEmpId(employeeInfo.getId());
		tEmployeeProject.setEmpCode(employeeInfo.getEmpCode());
		tEmployeeProject.setEmpNatrue(employeeInfo.getEmpNatrue());
		tEmployeeProject.setEmpName(employeeInfo.getEmpName());
		tEmployeeProject.setEmpIdcard(employeeInfo.getEmpIdcard());
		tEmployeeProject.setPost(employeeInfo.getPost());
		tEmployeeProject.setProjectSource(CommonConstants.dingleDigitStrArray[4]);

		String empNO = getEmpNo(employeeInfo.getDeptNo());
		tEmployeeProject.setEmpNo(empNO);
		tEmployeeProject.setDeptNo(employeeInfo.getDeptNo());

		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, employeeInfo.getDeptNo()).eq(TSettleDomain::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.eq(TSettleDomain::getStopFlag, CommonConstants.STATUS_NORMAL));
		if (Common.isNotNull(tSettleDomain)) {
			tEmployeeProject.setDeptId(tSettleDomain.getId());
			tEmployeeProject.setDeptName(tSettleDomain.getDepartName());
			tEmployeeProject.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
			tEmployeeProject.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
			tEmployeeProject.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
			tEmployeeProject.setUnitId(tSettleDomain.getCustomerId());
			tEmployeeProject.setUnitNo(tSettleDomain.getCustomerNo());
			tEmployeeProject.setUnitName(tSettleDomain.getCustomerName());
		}
		baseMapper.insert(tEmployeeProject);
	}

	/**
	 * 更新人员档案
	 */
	private void updateExcelPost(List<TEmployeeInfo> updateList, TEmployeeInfo tEmployeeInfo) {
		tEmployeeInfo.setFileStatus(CommonConstants.ZERO_INT);
		updateList.add(tEmployeeInfo);
	}

	/**
	 * 更新项目档案
	 */
	private void updateExcelPro(EmployeeProjectVO excel, List<TEmployeeProject> proupdateList, TEmployeeProject tEmployeeProject) {
		BeanUtil.copyProperties(excel, tEmployeeProject);
		YifuUser user = SecurityUtils.getUser();
		tEmployeeProject.setUpdateBy(user.getId());
		proupdateList.add(tEmployeeProject);
		// 记录变更日志
		TEmployeeProject tEmployeeProjectOld = this.getById(tEmployeeProject.getId());
		tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
				tEmployeeProject.getId(), tEmployeeProjectOld, tEmployeeProject);
	}

	/**
	 * 更新项目档案
	 */
	private void updateExcelProj(EmployeeProjectUpdateVO excel, List<TEmployeeProject> proupdateList, TEmployeeProject tEmployeeProject) {
		BeanUtil.copyProperties(excel, tEmployeeProject);
		YifuUser user = SecurityUtils.getUser();
		tEmployeeProject.setUpdateBy(user.getId());
		proupdateList.add(tEmployeeProject);
	}

	@Override
	public List<TEmployeeProject> getListByEmpId(String empId, int projectStatus) {
		TEmployeeProject project = new TEmployeeProject();
		project.setEmpId(empId);
		if (projectStatus == 0) {
			project.setProjectStatus(CommonConstants.ZERO_INT);
		}
		project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		return this.list(Wrappers.query(project));
	}

	@Override
	public List<TEmployeeProject> getListByEmpIdAndDeptNo(String empId, String deptNo) {
		TEmployeeProject project = new TEmployeeProject();
		project.setEmpId(empId);
		project.setDeptNo(deptNo);
		project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		return this.list(Wrappers.query(project));
	}

	@Override
	public R getItemByEmpNo(String empIdcard, String empNo) {
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, empNo)
				.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
				.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING));
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, empIdcard)
				.eq(TEmployeeInfo::getFileStatus, CommonConstants.ZERO_INT)
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ZERO_STRING));
		Map<String, Object> map = new HashMap<>();
		String empCode = "";
		if (Common.isNotNull(tEmployeeInfo)) {
			empCode = tEmployeeInfo.getEmpCode();
		}
		String customerName = "";
		if (Common.isNotNull(tSettleDomain)) {
			customerName = tSettleDomain.getCustomerName();
		}
		map.put("empCode", empCode);
		map.put("itemInfo", tSettleDomain);
		map.put("customerName", customerName);
		return R.ok(map);
	}

	@Override
	public TEmployeeProject getByEmpIdAndDeptId(String empId, String deptId) {
		TEmployeeProject employeeProject = null;
		if (Common.isEmpty(empId) || Common.isEmpty(deptId)) {
			return employeeProject;
		}
		employeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpId, empId)
				.eq(TEmployeeProject::getDeptId, deptId)
				.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
				.eq(TEmployeeProject::getDeleteFlag, CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
		return employeeProject;
	}

	@Override
	public R<Map<String, String>> getProjectByIdCard(String empIdCard) {
		List<TEmployeeProject> projects = baseMapper.selectList(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getDeleteFlag, CommonConstants.ZERO_STRING)
				.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
				.eq(TEmployeeProject::getEmpIdcard, empIdCard));
		Map<String, String> projectMap = new HashMap<>();
		if (Common.isNotNull(projects)) {
			for (TEmployeeProject project : projects) {
				projectMap.put(project.getDeptName(), project.getDeptNo());
			}
		}
		return R.ok(projectMap);
	}

	//获取员工编码
	@Override
	public String getEmpNo(String deptNo) {
		String str = "";
		String empNo = baseMapper.findEmployeeMaxOnlyNoByDepId(deptNo);
		if (!Common.isEmpty(empNo)) {
			str = NoUtil.productionNo(empNo, CommonConstants.EMPLOYEE_INIT_NO_START);
		} else {
			str = deptNo + CommonConstants.EMPLOYEE_INIT_NO;
		}
		return str;
	}

	/**
	 * @Description: 更新社保公积金状态 ： 0 无社保|无公积金 1 处理中 2.部分购买 3.正常 4.已派减
	 * 派增：
	 * 1、派单处社保或公积金状态为待审核、待办理、办理中，项目档案处社保或公积金状态为处理中1；
	 * 2、派单处社保或公积金状态为审核不通过或办理失败，项目档案处社保状态为无社保，公积金状态为无公积金0；
	 * 3、派单处社保状态为部分办理失败，项目档案处社保状态为部分购买 2
	 * 4、派单处社保或公积金状态为办理成功，项目档案处社保或公积金状态为正常 3
	 * 派减：
	 * 1、派减状态为待审核、待办理、审核不通过、办理失败，项目档案处社保或公积金状态不变；
	 * 2、派减状态为办理成功，项目档案处社保或公积金状态变为已派减 4
	 * 人员档案处社保或公积金状态根据身份证+项目进行整合：
	 * 社保状态优先级：正常>部分购买>处理中>已派减>无社保
	 * 公积金状态优先级：正常>处理中>已派减>无公积金
	 * @Author: fxj
	 * @Date: 2022/08/01 18:52
	 **/
	@Override
	public Boolean updateProjectSocialFund(UpProjectSocialFundVo vo) {
		if (Common.isEmpty(vo) || Common.isEmpty(vo.getEmpIdCard()) || Common.isEmpty(vo.getDepartNo())){
			return false;
		}
		TEmployeeInfo employee = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard,vo.getEmpIdCard())
				.eq(TEmployeeInfo::getDeleteFlag,CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
		// : 0 无社保|无公积金 1 处理中 2.部分购买 3.正常 4.已派减
		if (Common.isNotNull(employee)){
			if (Common.isNotNull(vo.getSocialStatus())){
				employee.setSocialStatus(Integer.parseInt(vo.getSocialStatus()));
			}
			if (Common.isNotNull(vo.getFundStatus())){
				employee.setFundStatus(Integer.parseInt(vo.getFundStatus()));
			}
			if (Common.isNotNull(vo.getFileProvince())){
				employee.setFileProvince(Integer.parseInt(vo.getFileProvince()));
			}
			if (Common.isNotNull(vo.getFileCity())){
				employee.setFileCity(Integer.parseInt(vo.getFileCity()));
				if (Common.isNotNull(vo.getFileTown())){
					employee.setFileTown(Integer.parseInt(vo.getFileTown()));
				}else {
					employee.setFileTown(null);
				}
			}
			if (Common.isNotNull(vo.getMobile())){
				employee.setEmpPhone(vo.getMobile());
			}
			tEmployeeInfoMapper.updateSocialInfoById(employee);
		}
		TEmployeeProject project = baseMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getDeptNo,vo.getDepartNo())
				.eq(TEmployeeProject::getEmpIdcard,vo.getEmpIdCard())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		// : 0 无社保|无公积金 1 处理中 2.部分购买 3.正常 4.已派减
		if (Common.isNotNull(project)){
			if (Common.isNotNull(vo.getSocialStatus())){
				project.setSocialStatus(Integer.parseInt(vo.getSocialStatus()));
			}
			if (Common.isNotNull(vo.getFundStatus())){
				project.setFundStatus(Integer.parseInt(vo.getFundStatus()));
			}
			baseMapper.updateSocialAndFundStatusById(project);
		}
		return true;
	}

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

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

	/**
	 * @Description: everyMonthUpdateEmployeeSalaryStatus
	 * @Author: hgw
	 * @Date: 2022/11/24 14:56
	 * @return: void
	 **/
	@Override
	public void everyMonthUpdateEmployeeSalaryStatus() {
		baseMapper.everyMonthUpdateEmployeeSalaryStatus();
	}

	/**
	 * @Description: 每天更新人员档案、项目档案的过期合同为2不在用
	 * @Author: hgw
	 * @Date: 2022/11/24 14:56
	 * @return: void
	 **/
	@Override
	public void everyDayUpdateEmployeContractStatus() {
		baseMapper.everyDayUpdateEmployeContractStatus();
	}

	@Override
	public R<List<TSettleDomainDataVo>> selectSettleMentData(List<String> deptNoList) {
		List<TSettleDomainDataVo> list = new ArrayList<>();
		TSettleDomainDataVo t;
		if (Common.isNotNull(deptNoList)) {
			for (String deptNo:deptNoList) {
				t = new TSettleDomainDataVo();
				t.setDepartNo(deptNo);
				//查询项目档案在档人数
				long projectNum = baseMapper.selectCount(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getDeptNo,deptNo)
						.eq(TEmployeeProject::getProjectStatus,CommonConstants.ZERO_INT)
						.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING));
				t.setProjectNum(projectNum);
				//项目员工合同在用数
				long contractNum = baseMapper.selectCount(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getDeptNo,deptNo)
						.eq(TEmployeeProject::getProjectStatus,CommonConstants.ZERO_INT)
						.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
						.eq(TEmployeeProject::getContractStatus,CommonConstants.ONE_INT));
				t.setContractNum(contractNum);
				//查询社保在保人数
				long socialNum = baseMapper.selectCount(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getDeptNo,deptNo)
						.eq(TEmployeeProject::getProjectStatus,CommonConstants.ZERO_INT)
						.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
						.and(obj -> obj.eq(TEmployeeProject::getSocialStatus, CommonConstants.ONE_INT)
								.or().eq(TEmployeeProject::getSocialStatus, CommonConstants.TWO_INT)
								.or().eq(TEmployeeProject::getSocialStatus, CommonConstants.THREE_INT)));
				t.setSocialNum(socialNum);
				//查询公积金在保人数
				long fundNum = baseMapper.selectCount(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getDeptNo, deptNo)
						.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
						.eq(TEmployeeProject::getDeleteFlag, CommonConstants.ZERO_STRING)
						.and(obj -> obj.eq(TEmployeeProject::getFundStatus, CommonConstants.ONE_INT)
								.or().eq(TEmployeeProject::getFundStatus, CommonConstants.TWO_INT)
								.or().eq(TEmployeeProject::getFundStatus, CommonConstants.THREE_INT)));
				t.setFundNum(fundNum);
				list.add(t);
			}
			return R.ok(list);
		}else {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
	}

	/**
	 * B端获取登录用户对应单位的员工数据
	 * @Author fxj
	 * @Date 2020-08-25
	 * @UpdateDate 2021-08-09 wwg
	 * @param page
	 * @param query
	 * @return
	 **/
	@Override
	public IPage<BusinessEmployeeExtendListVO> getTEmployeeBusinessPage(Page<EmployeeBusinessVo> page, THroBusinessUserQuery query) {
		if (StringUtils.isNotBlank(query.getEmployeeTagName())) {
			String empTag = String.format(CommonConstants.TAG_FROMAT, Integer.valueOf(query.getEmployeeTagName()));
			query.setEmployeeTagName(empTag);
		}
		IPage<BusinessEmployeeExtendListVO> pageData = baseMapper.getTEmployeeBusinessPage(page,query);
		List<BusinessEmployeeExtendListVO> voList = pageData.getRecords();
		if (Common.isNotNull(voList)){
			pageData.setRecords(voList);
		}
		return pageData;
	}

	@Override
	public EmployeeBusinessDetailVo getEmployeeBusinessInfoById(String empId, String settleDomain) {
		EmployeeBusinessDetailVo businessDetailVo = new EmployeeBusinessDetailVo();
		TEmployeeProject employeeInfo = baseMapper.selectById(empId);
		EmployeeBusinessVo businessVo = new EmployeeBusinessVo();
		// 有档案数据封装数据 无数据直接返回
		if (null == employeeInfo){
			return businessDetailVo;
		}else {
			TBusinessEmployeeExtendInfo tBusinessEmployeeExtendInfo =  this.businessEmployeeExtendInfoService.getByEmpIdCard(employeeInfo.getEmpIdcard());
			TEmployeeInfo employee = tEmployeeInfoMapper.selectById(employeeInfo.getEmpId());
			initEmpBusinessInfo(employeeInfo, employee, businessVo, tBusinessEmployeeExtendInfo);
		}

		// 获取合同数据(去除作废，终止)
		List<TEmployeeContractInfo> contractInfoList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
				.eq(TEmployeeContractInfo::getEmpIdcard,employeeInfo.getEmpIdcard())
				.eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
				.ne(TEmployeeContractInfo::getSituation, EmployeeConstants.SITUATION_SIX)
				.ne(TEmployeeContractInfo::getSituation, EmployeeConstants.SITUATION_SEVEN)
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
				.isNotNull(TEmployeeContractInfo::getAuditTimeLast)
				.eq(TEmployeeContractInfo::getSettleDomain, settleDomain)
				.orderByDesc(TEmployeeContractInfo::getContractStart));
		// 处理详情对应的合同信息
		if (Common.isNotNull(contractInfoList)) {
			initEmpBusinessContractInfo(businessDetailVo, contractInfoList);
		}
		// 获取最高学历
		List<TEmpEducation> educations = empEducationMapper.selectList(Wrappers.<TEmpEducation>query().lambda()
				.eq(TEmpEducation::getEmpId,empId)
				.eq(TEmpEducation::getHighIdentification,CommonConstants.ZERO_STRING)
				.eq(TEmpEducation::getDeleteFlag,CommonConstants.ZERO_STRING)
				.orderByDesc(TEmpEducation::getCreateTime));
		// 处理学历信息
		if (Common.isNotNull(educations)){
			TEmpEducation empEducation = educations.get(CommonConstants.ZERO_INT);
			if (null != empEducation){
				businessVo.setSchool(empEducation.getSchool());
				businessVo.setEducationName(empEducation.getEducationName());
			}
		}
		// 获取社保和公积金派减信息
		SocialAndFundReduceVo vo = new SocialAndFundReduceVo();
		vo.setEmpId(employeeInfo.getEmpId());
		R<SocialAndFundReduceVo> reduceVoR = HttpDaprUtil.invokeMethodPost(daprSocialProperties.getAppUrl(), daprSocialProperties.getAppId()
				, "/tdispatchinfo/inner/getSocialAndFundReduceInfo", vo, SocialAndFundReduceVo.class, SecurityConstants.FROM_IN);
		if (null != reduceVoR && reduceVoR.getData() != null){
			businessDetailVo.setSocialReduceDate(reduceVoR.getData().getSocialReduceDate());
			businessDetailVo.setFundReduceDate(reduceVoR.getData().getFundReduceDate());
		}
		businessDetailVo.setEmployeeBusinessVo(businessVo);
		return businessDetailVo;
	}

	@Override
	public R<EmployeeBusinessVo> getEmployeeBusinessVoById(String empId) {
		TEmployeeProject employeeInfo = baseMapper.selectById(empId);
		EmployeeBusinessVo businessVo = new EmployeeBusinessVo();
		// 有档案数据封装数据 无数据直接返回
		if (null == employeeInfo){
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}else {
			TBusinessEmployeeExtendInfo tBusinessEmployeeExtendInfo =  this.businessEmployeeExtendInfoService.getByEmpIdCard(employeeInfo.getEmpIdcard());
			TEmployeeInfo employee = tEmployeeInfoMapper.selectById(employeeInfo.getEmpId());
			initEmpBusinessInfo(employeeInfo, employee, businessVo, tBusinessEmployeeExtendInfo);
		}
		return R.ok(businessVo);
	}

	private void initEmpBusinessContractInfo(EmployeeBusinessDetailVo businessDetailVo
			, List<TEmployeeContractInfo> contractInfoList) {
		businessDetailVo.setSituationCount(contractInfoList.size());
		if (businessDetailVo.getSituationCount() > CommonConstants.ONE_INT){
			businessDetailVo.setSituation(EmpBusinessConstants.empContractSituationRenew);
		}else {
			businessDetailVo.setSituation(EmpBusinessConstants.empContractSituationNew);
		}
		businessDetailVo.setContractInfoList(contractInfoList);
		TEmployeeContractInfo contractInfo = contractInfoList.get(CommonConstants.ZERO_INT);
		if (null != contractInfo.getContractEnd()){
			businessDetailVo.setContractEndDate(DateUtil.formatDate(contractInfo.getContractEnd()));
		}
		if (null != contractInfo.getContractStart()){
			businessDetailVo.setContractStartDate(DateUtil.formatDate(contractInfo.getContractStart()));
		}
		for (TEmployeeContractInfo info:contractInfoList){
			//在用的，固定期限的，尝试计算过期天数
			if (CommonConstants.ZERO_STRING.equals(info.getInUse()) && null != info.getContractEnd()){
				int dayCount = DateUtil.getDayDiff(info.getContractEnd(), new Date());
				if (dayCount <= EmpBusinessConstants.ninety && dayCount > CommonConstants.ZERO_INT){
					businessDetailVo.setContractOverdue(dayCount);
				}
				break;
			}
		}
	}

	private void initEmpBusinessInfo(TEmployeeProject employeeInfo, TEmployeeInfo employee
			, EmployeeBusinessVo businessVo, TBusinessEmployeeExtendInfo tBusinessEmployeeExtendInfo) {
		businessVo.setEmpId(employeeInfo.getEmpId());
		businessVo.setSettleDomain(employeeInfo.getDeptId());
		businessVo.setBelongUnit(employeeInfo.getUnitId());
		if (employee != null) {
			businessVo.setEmpAge(employee.getEmpAge());
			businessVo.setEmpBirthday(employee.getEmpBirthday());
			businessVo.setEmpNational(employee.getEmpNational());
			businessVo.setEmpRegisType(employee.getEmpRegisType());
			businessVo.setEmpSex(employee.getEmpSex());
		}
		businessVo.setEmpIdcard(employeeInfo.getEmpIdcard());
		businessVo.setEmpName(employeeInfo.getEmpName());
		businessVo.setEmpPhone(employeeInfo.getEmpPhone());

		businessVo.setEnjoinDate(employeeInfo.getEnjoinDate());
		businessVo.setPost(employeeInfo.getPost());
		businessVo.setRemark(employeeInfo.getRemark());
		businessVo.setWorkFlag(String.valueOf(employeeInfo.getProjectStatus()));
		businessVo.setWorkingHours(employeeInfo.getWorkingHours());
		businessVo.setBusinessEnjoinDate(employeeInfo.getEnjoinDate());
		businessVo.setBusinessPost(employeeInfo.getPost());

		// 设置拓展表信息 合电2.0版本 ---wwg
		if (null != tBusinessEmployeeExtendInfo) {
			businessVo.setFirstDegreeAndMajor(tBusinessEmployeeExtendInfo.getFirstDegreeAndMajor());
			businessVo.setFirstDegreeGraduateSchool(tBusinessEmployeeExtendInfo.getFirstDegreeGraduateSchool());
			businessVo.setHighestDegreeAndMajor(tBusinessEmployeeExtendInfo.getHighestDegreeAndMajor());
			businessVo.setHighestDegreeGraduateSchool(tBusinessEmployeeExtendInfo.getHighestDegreeGraduateSchool());
			businessVo.setContactInfo(tBusinessEmployeeExtendInfo.getContactInfo());
			businessVo.setArchivesAddr(tBusinessEmployeeExtendInfo.getArchivesAddr());
			businessVo.setEmployeeTags(tBusinessEmployeeExtendInfo.getEmployeeTags());
			businessVo.setDepartName(tBusinessEmployeeExtendInfo.getDepartName());
			businessVo.setDepartId(tBusinessEmployeeExtendInfo.getDepartId());
			businessVo.setDepartCode(tBusinessEmployeeExtendInfo.getDepartCode());
			businessVo.setExtendId(tBusinessEmployeeExtendInfo.getId());
			if (null != tBusinessEmployeeExtendInfo.getBusinessEnjoinDate()) {
				businessVo.setBusinessEnjoinDate(tBusinessEmployeeExtendInfo.getBusinessEnjoinDate());
			}
			if(StringUtils.isNotBlank(tBusinessEmployeeExtendInfo.getBusinessPost())) {
				businessVo.setBusinessPost(tBusinessEmployeeExtendInfo.getBusinessPost());
			}
			businessVo.setBusinessLeaveDate(tBusinessEmployeeExtendInfo.getBusinessLeaveDate());
			businessVo.setBusinessTelecomNumber(tBusinessEmployeeExtendInfo.getBusinessTelecomNumber());
			businessVo.setLeaveReason(tBusinessEmployeeExtendInfo.getBusinessLeaveReason());
		}
	}

	@Override
	public R<List<BusinessEmployeeExtentExcelVO>> exportByParams(THroBusinessUserQuery query) {
		if (StringUtils.isNotBlank(query.getEmployeeTagName())) {
			String empTag = String.format(CommonConstants.TAG_FROMAT, Integer.valueOf(query.getEmployeeTagName()));
			query.setEmployeeTagName(empTag);
		}
		return R.ok(this.baseMapper.getTEmployeeBusinessList(query));
	}
}
