/*
 *    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 com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.constants.ArchivesConstants;
import com.yifu.cloud.plus.v1.yifu.archives.constants.EmployeeConstants;
import com.yifu.cloud.plus.v1.yifu.archives.constants.EmployeeContractConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.*;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ResultConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchListVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseServiceParamListVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSocialProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.CspDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialFundInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 员工合同
 *
 * @author hgw
 * @date 2022-06-29 20:45:22
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties({DaprSocialProperties.class})
public class TEmployeeContractInfoServiceImpl extends ServiceImpl<TEmployeeContractInfoMapper, TEmployeeContractInfo> implements TEmployeeContractInfoService {

	private static final String ID_NOT_EMPTY = "ID,EMP_ID不可为空";

	private static final String EMPINFO_IS_NOT_EXITS_BYID = "未找到人员档案与项目档案！";

	private final TEmployeeInfoMapper tEmployeeInfoMapper;
	private final TEmployeeProjectService tEmployeeProjectService;
	private final TSettleDomainService tSettleDomainService;
	private final TAttaInfoService tAttaInfoService;
	private final TEmployeeContractAuditMapper tEmployeeContractAuditMapper;
	private final TEmployeeLogService tEmployeeLogService;
	private final TWorkHandlerInfoService workHandlerInfoService;
	private final TPreEmpMainMapper preEmpMainMapper;
	private final TPreEmployeeProjectMapper preEmployeeProjectMapper;
	@Autowired
	private DaprSocialProperties socialProperties;
	// 缓存信息
	private final CacheManager cacheManager;

	private final TEmployeeContractPreMapper contractPreMapper;

	private final TEmployeeContractPreNewMapper contractPreNewMapper;

	private final TEmpContractAlertMapper contractAlertMapper;

	private final TGzOfferInfoMapper gzOfferInfoMapper;

	private final LGuaziOfferRecordService lGuaziOfferRecordService;

	private final TGzContractService tGzContractService;

	private final TGzPushEntryService tGzPushEntryService;

	private final TGzEmpInfoMapper tGzEmpInfoMapper;

	private final CspDaprUtils cspDaprUtil;

	/**
	 * 员工合同信息表简单分页查询
	 *
	 * @param tEmployeeContractInfo 员工合同信息表
	 * @return
	 */
	@Override
	public IPage<TEmployeeContractInfo> getTEmployeeContractInfoPage(Page<TEmployeeContractInfo> page, TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractInfoPage(page, tEmployeeContractInfo);
	}
	/**
	 * 审核列表
	 *
	 * @param tEmployeeContractInfo 员工合同信息表
	 * @return
	 */
	@Override
	public IPage<TEmployeeContractInfo> getTEmployeeContractInfoPageByAudit(Page<TEmployeeContractInfo> page, TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractInfoPageByAudit(page, tEmployeeContractInfo);
	}

	@Override
	public List<TEmployeeContractInfo> getTEmployeeContractList(TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractList(tEmployeeContractInfo);
	}

	@Override
	public List<EmployeeContractExportVO> getTEmployeeContractExport(TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractExport(tEmployeeContractInfo);
	}

	@Override
	public List<EmployeeContractExportVO> getTEmployeeContractExportHistory(TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractExportHistory(tEmployeeContractInfo);
	}

	@Override
	public R<List<ErrorMessage>> saveNewContract(TEmployeeContractInfo tEmployeeContractInfo) {
		try {
			if (Common.isEmpty(tEmployeeContractInfo.getEmpId()) || Common.isEmpty(tEmployeeContractInfo.getSettleDomain())) {
				return R.failed(EmployeeConstants.EMPID_NOT_EMPTY);
			}
			return this.setBaseInfo(tEmployeeContractInfo, null);
		} catch (Exception e) {
			log.error("员工合同保存异常：" + e.getMessage());
			return R.failed("员工合同保存系统异常！");
		}
	}

	private R<List<ErrorMessage>> setBaseInfo(TEmployeeContractInfo tEmployeeContractInfo, TEmployeeProject tEmployeeProject) {

		// 获取人员档案
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeContractInfo.getEmpId());
		// 获取项目
		if (tEmployeeProject == null) {
			tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
					.lambda().eq(TEmployeeProject::getEmpId, tEmployeeContractInfo.getEmpId())
					.eq(TEmployeeProject::getDeptId, tEmployeeContractInfo.getSettleDomain())
					.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.last(CommonConstants.LAST_ONE_SQL));
		}
		if (null == tEmployeeInfo || tEmployeeProject == null) {
			return R.failed(EMPINFO_IS_NOT_EXITS_BYID);
		}

		if (!(ArchivesConstants.contractSituation[0].equals(tEmployeeContractInfo.getSituation()) ||
				ArchivesConstants.contractSituation[6].equals(tEmployeeContractInfo.getSituation()))) {
			TSettleDomain settleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDepartNo, tEmployeeContractInfo.getDeptNo())
					.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
					.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
			if (Common.isEmpty(settleDomain)) {
				return R.failed(EmployeeConstants.EMP_DISPATCH_SETTLEDOMAIN_STOP);
			}
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			user = this.getNewYifuUser(tEmployeeContractInfo.getLeaveName());
		}
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}

		// 初始化
		this.initEmployeeContract(tEmployeeContractInfo, tEmployeeInfo, tEmployeeProject, user);

		// 新增合同拦截：
		R<List<ErrorMessage>> failed = judgeRule(tEmployeeContractInfo);
		if (failed != null) return failed;

		//是否归档：否
		tEmployeeContractInfo.setIsFile(CommonConstants.ONE_STRING);

		//是否在用：否
		tEmployeeContractInfo.setInUse(CommonConstants.ONE_STRING);

		ExcelAttributeValidityUtil<TEmployeeContractInfo> validity = new ExcelAttributeValidityUtil<>(TEmployeeContractInfo.class);
		validity.ValidityObj(tEmployeeContractInfo);
		if (null != validity.getErrorInfo() && !validity.getErrorInfo().isEmpty()) {
			return R.failed(validity.getErrorInfo(), ResultConstants.VALIDITY_FAIL);
		}

		return this.saveContractAndAtta(tEmployeeContractInfo, user);
	}

	/**
	 * @param tEmployeeContractInfo
	 * @Description: 合同新增前的拦截
	 * @Author: hgw
	 * @Date: 2022/12/23 14:54
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage>>
	 **/
	private R<List<ErrorMessage>> judgeRule(TEmployeeContractInfo tEmployeeContractInfo) {
		if (Common.isNotNull(tEmployeeContractInfo.getSituation())) {
			// "新签合同（正常签订）： 同一项目针对合同存在 在用的禁止发起；
			if (EmployeeConstants.SITUATION_ONE.equals(tEmployeeContractInfo.getSituation())) {
				TEmployeeContractInfo contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
						.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
						.eq(TEmployeeContractInfo::getDeptNo, tEmployeeContractInfo.getDeptNo())
						.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
				if (contractInfo != null) {
					return R.failed("该项目已存在在用合同，禁止新签！");
				}
			} else if (EmployeeConstants.SITUATION_TWO.equals(tEmployeeContractInfo.getSituation())) {
				// "正常续签（正常续签）： 要求后一份合同的开始时间要等于上一份合同的结束日期+1天（限制）"
				TEmployeeContractInfo contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
						.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
						.eq(TEmployeeContractInfo::getDeptNo, tEmployeeContractInfo.getDeptNo())
						.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
				if (contractInfo == null) {
					return R.failed("无在用合同，无法续签");
				} else if (contractInfo.getContractEnd() == null
						|| !(DateUtil.formatDate(DateUtil.addDayByDate(contractInfo.getContractEnd(), 1)).equals(DateUtil.formatDate(tEmployeeContractInfo.getContractStart())))
				) {
					return R.failed("续签请注意上一份合同的截止日期！");
				}
			} else if (EmployeeConstants.SITUATION_THREE.equals(tEmployeeContractInfo.getSituation())) {
				// 离职再入职： 同一项目存在可用禁止发起，存在审核通过且不可用允许发起
				TEmployeeContractInfo contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
						.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
						.eq(TEmployeeContractInfo::getDeptNo, tEmployeeContractInfo.getDeptNo())
						.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
				if (contractInfo != null) {
					return R.failed("该项目已存在在用合同，禁止离职再入职！");
				} else {
					contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.isNotNull(TEmployeeContractInfo::getAuditTimeLast).last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo == null) {
						return R.failed("该人员不存在审核通过一次的合同，禁止离职再入职！");
					}
				}
			}
			TEmployeeContractInfo contractInfo;
			if (!EmployeeConstants.SITUATION_SEVEN.equals(tEmployeeContractInfo.getSituation()) && !EmployeeConstants.SITUATION_SIX.equals(tEmployeeContractInfo.getSituation())) {
				if (CommonConstants.TWO_STRING.equals(tEmployeeContractInfo.getContractType()) || CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getContractType())) {
					contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getContractStart, tEmployeeContractInfo.getContractStart())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.and(obj -> obj.eq(TEmployeeContractInfo::getContractType, CommonConstants.TWO_STRING)
									.or()
									.eq(TEmployeeContractInfo::getContractType, CommonConstants.ZERO_STRING)
							)
							.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
									.or()
									.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
							)
							.last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo != null) {
						return R.failed("该员工已存在相同起始日期的合同，禁止重复添加");
					}
				} else {
					contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getContractStart, tEmployeeContractInfo.getContractStart())
							.eq(TEmployeeContractInfo::getContractEnd, tEmployeeContractInfo.getContractEnd())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
									.or()
									.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
							)
							.last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo != null) {
						return R.failed("该员工已存在相同起始和截止日期的合同，禁止重复添加");
					}
				}
			}
		}

		return null;
	}

	@Override
	public R<List<ErrorMessage>> updateContract(TEmployeeContractInfo tEmployeeContractInfo) {
		try {
			if (Common.isEmpty(tEmployeeContractInfo.getId()) || Common.isEmpty(tEmployeeContractInfo.getEmpId())) {
				return R.failed(ID_NOT_EMPTY);
			}
			YifuUser user = SecurityUtils.getUser();
			if (user == null || Common.isEmpty(user.getId())) {
				return R.failed(CommonConstants.PLEASE_LOG_IN);
			}
			// 初始化
			tEmployeeContractInfo.setUpdateBy(user.getId());
			tEmployeeContractInfo.setUpdateTime(LocalDateTime.now());

			//是否归档：否
			tEmployeeContractInfo.setIsFile(CommonConstants.ONE_STRING);
			//是否在用：否
			tEmployeeContractInfo.setInUse(CommonConstants.ONE_STRING);

			ExcelAttributeValidityUtil<TEmployeeContractInfo> validity = new ExcelAttributeValidityUtil<>(TEmployeeContractInfo.class);
			validity.ValidityObj(tEmployeeContractInfo);
			if (null != validity.getErrorInfo() && !validity.getErrorInfo().isEmpty()) {
				return R.failed(validity.getErrorInfo(), ResultConstants.VALIDITY_FAIL);
			}
			TEmployeeContractInfo contractInfo;
			if (!EmployeeConstants.SITUATION_SEVEN.equals(tEmployeeContractInfo.getSituation()) && !EmployeeConstants.SITUATION_SIX.equals(tEmployeeContractInfo.getSituation())) {
				if (CommonConstants.TWO_STRING.equals(tEmployeeContractInfo.getContractType()) || CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getContractType())) {
					contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getContractStart, tEmployeeContractInfo.getContractStart())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.and(obj -> obj.eq(TEmployeeContractInfo::getContractType, CommonConstants.TWO_STRING)
									.or()
									.eq(TEmployeeContractInfo::getContractType, CommonConstants.ZERO_STRING)
							)
							.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
									.or()
									.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
							)
							.last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo != null) {
						return R.failed("该员工已存在相同起始日期的合同，禁止重复添加");
					}
				} else {
					contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, tEmployeeContractInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getContractStart, tEmployeeContractInfo.getContractStart())
							.eq(TEmployeeContractInfo::getContractEnd, tEmployeeContractInfo.getContractEnd())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
									.or()
									.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
							)
							.last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo != null) {
						return R.failed("该员工已存在相同起始和截止日期的合同，禁止重复添加");
					}
				}
			}

			return this.saveContractAndAtta(tEmployeeContractInfo, user);
		} catch (Exception e) {
			log.error("员工合同保存异常：" + e.getMessage());
			return R.failed("员工合同保存系统异常！");
		}
	}


	private void initEmployeeContract(TEmployeeContractInfo tEmployeeContractInfo, TEmployeeInfo tEmployeeInfo
			, TEmployeeProject tEmployeeProject, YifuUser user) {
		tEmployeeContractInfo.setEmpId(tEmployeeInfo.getId());
		tEmployeeContractInfo.setEmpNatrue(tEmployeeProject.getEmpNatrue());
		tEmployeeContractInfo.setEmpIdcard(tEmployeeInfo.getEmpIdcard());
		tEmployeeContractInfo.setEmpName(tEmployeeInfo.getEmpName());
		tEmployeeContractInfo.setEmpNo(tEmployeeProject.getEmpNo());
		if (Common.isEmpty(tEmployeeContractInfo.getCreateBy())) {
			tEmployeeContractInfo.setCreateBy(null == user ? "" : user.getId());
			tEmployeeContractInfo.setCreateName(null == user ? "" : user.getNickname());
			tEmployeeContractInfo.setCreateTime(LocalDateTime.now());
		}
		tEmployeeContractInfo.setUpdateBy(null == user ? "" : user.getId());
		tEmployeeContractInfo.setUpdateTime(LocalDateTime.now());
		tEmployeeContractInfo.setSettleDomain(tEmployeeProject.getDeptId());
		tEmployeeContractInfo.setCustomerId(tEmployeeProject.getUnitId());
		tEmployeeContractInfo.setSubjectUnit(tEmployeeProject.getUnitName());
		tEmployeeContractInfo.setUnitNo(tEmployeeProject.getUnitNo());
		tEmployeeContractInfo.setSubjectDepart(tEmployeeProject.getDeptName());
		tEmployeeContractInfo.setDeptNo(tEmployeeProject.getDeptNo());
		tEmployeeContractInfo.setFileProvince(tEmployeeInfo.getFileProvince());
		tEmployeeContractInfo.setFileCity(tEmployeeInfo.getFileCity());
		tEmployeeContractInfo.setFileTown(tEmployeeInfo.getFileTown());
		tEmployeeContractInfo.setWorkFlag(String.valueOf(tEmployeeInfo.getFileStatus()));
		tEmployeeContractInfo.setWorkingStatusSub(CommonConstants.ZERO_STRING);
		//是否作废：否
		tEmployeeContractInfo.setIsObsolete(CommonConstants.ZERO_STRING);
		tEmployeeContractInfo.setDeleteFlag(CommonConstants.ZERO_INT);
		if (Common.isEmpty(tEmployeeContractInfo.getApplyNo())) {
			tEmployeeContractInfo.setApplyNo(this.getCode(false));
		}
	}

	/**
	 * @param isNew true:取数据库最新的
	 * @Description: 获取 申请编码
	 * @Author: hgw
	 * @Date: 2022/6/22 17:52
	 * @return: java.lang.String
	 **/
	@Override
	@Lock4j(expire = 60000, acquireTimeout = 1000)
	public String getCode(boolean isNew) {
		String nowDay = DateUtil.getThisDay();
		int nowNums;
		String empCode = null;
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_EMP_CONTRACT_CODE);
		if (isNew) {
			empCode = baseMapper.getMaxContractCode();
			nowNums = Integer.parseInt(empCode) + 1;
		} else {
			try {
				Object nowNumObj = cache.get(nowDay);
				if (Common.isNotNull(nowNumObj)) {
					SimpleValueWrapper value = (SimpleValueWrapper) nowNumObj;
					nowNums = (Integer) value.get() + 1;
				} else {
					empCode = baseMapper.getMaxContractCode();
					nowNums = Integer.parseInt(empCode) + 1;
				}
			} catch (NumberFormatException e) {
				log.error("获取人员合同当日最大编码时出错：" + empCode);
				nowNums = 1;
			}
		}
		cache.put(nowDay, nowNums);
		return "HT" + nowDay + this.getFourNum(String.valueOf(nowNums));
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取四位字符型数字
	 * @Author: hgw
	 * @Date: 2022-6-30 16:05:25
	 * @return: 五位字符型数字
	 **/
	private String getFourNum(String nowNums) {
		if (nowNums.length() >= 4) {
			return nowNums.substring(0, 4);
		}
		String[] zeroArr = {"0", "00", "000"};
		int num = 3 - nowNums.length();
		return zeroArr[num] + nowNums;
	}

	/**
	 * 保存员工合同表及附件关系表
	 *
	 * @param tEmployeeContractInfo
	 * @param user
	 * @return
	 * @Author fxj
	 * @Date 2019-09-09
	 **/
	private R<List<ErrorMessage>> saveContractAndAtta(TEmployeeContractInfo tEmployeeContractInfo, YifuUser user) {
		//档案柜存在就自动归档
		if (Common.isNotNull(tEmployeeContractInfo.getAttaList())) {
			tEmployeeContractInfo.setIsFile(CommonConstants.ZERO_STRING);
		}
		if (null != tEmployeeContractInfo.getSettleDomain()
				&& (Common.isEmpty(tEmployeeContractInfo.getSubjectUnit())
				|| Common.isEmpty(tEmployeeContractInfo.getSubjectDepart()))) {
			TSettleDomain settleDomain = tSettleDomainService.getById(tEmployeeContractInfo.getSettleDomain());
			if (null != settleDomain) {
				if (Common.isEmpty(tEmployeeContractInfo.getSubjectDepart())) {
					tEmployeeContractInfo.setSubjectDepart(settleDomain.getDepartName());
					tEmployeeContractInfo.setDeptNo(settleDomain.getDepartNo());
					tEmployeeContractInfo.setSubjectUnit(settleDomain.getCustomerName());
					tEmployeeContractInfo.setUnitNo(settleDomain.getCustomerNo());
				}
			}
		}
		//初始化审核类型  审核类型:0派增-社保派单、1派增-无社保新签、2派增-续签、3派减-作废、4派减-终止
		initType(tEmployeeContractInfo);

		if (Common.isEmpty(tEmployeeContractInfo.getId())) {
			if (Common.isEmpty(tEmployeeContractInfo.getApplyNo())) {
				String code = this.getCode(true);
				tEmployeeContractInfo.setApplyNo(code);
			}
			// 针对编码再做一次重复性校验
			String isCur = baseMapper.getContractByApplyNo(tEmployeeContractInfo.getApplyNo());
			if (Common.isNotNull(isCur)) {
				String code = this.getCode(true);
				tEmployeeContractInfo.setApplyNo(code);
			}
			//自动化派单创建人赋值
			if (Common.isNotNull(tEmployeeContractInfo.getPreName())) {
				tEmployeeContractInfo.setCreateName(tEmployeeContractInfo.getPreName());
				tEmployeeContractInfo.setCreateBy("1");
			}
			baseMapper.insert(tEmployeeContractInfo);

			// 标准合同、劳动派遣合同、其他。————社保公积金都派减，自动审核通过
			this.judgeAuditStatus(tEmployeeContractInfo, user);
			if (Common.isNotNull(tEmployeeContractInfo.getPreName())) {
				tEmployeeContractInfo.setCreateName(tEmployeeContractInfo.getPreName());
				tEmployeeContractInfo.setCreateTime(LocalDateTime.now());
			}
			baseMapper.updateById(tEmployeeContractInfo);

			//如果是否同步终止合同、减项、减档为是则生成同步任务处理清单
			//增加任务处理情况查询表数据
			if (Common.isNotNull(tEmployeeContractInfo.getChangeContractAndEmployee())
					&& CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getChangeContractAndEmployee())) {
				TWorkHandlerInfo handlerInfo1 = workHandlerInfoService.getOne(Wrappers.<TWorkHandlerInfo>query()
						.lambda().eq(TWorkHandlerInfo::getDetailId, tEmployeeContractInfo.getId())
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isEmpty(handlerInfo1)) {
					TWorkHandlerInfo handlerInfo = new TWorkHandlerInfo();
					handlerInfo.setEmpIdcard(tEmployeeContractInfo.getEmpIdcard());
					handlerInfo.setEmpName(tEmployeeContractInfo.getEmpName());
					handlerInfo.setDepartName(tEmployeeContractInfo.getSubjectDepart());
					handlerInfo.setDepartNo(tEmployeeContractInfo.getDeptNo());
					handlerInfo.setInfoFrom("合同终止");
					handlerInfo.setOperUser(user.getNickname());
					handlerInfo.setOperTime(LocalDateTime.now());
					handlerInfo.setDetailId(tEmployeeContractInfo.getId());
					handlerInfo.setOperResult(CommonConstants.ZERO_STRING);
					workHandlerInfoService.save(handlerInfo);
				}
			}
			if (Common.isNotNull(tEmployeeContractInfo.getAttaList()) && Common.isNotNull(tEmployeeContractInfo.getId())) {
				this.updateFileMainId(tEmployeeContractInfo);
			}
			//派单成功更新合同待签订列表数据
			//更新合同状态为2线下签待审核
			if (Common.isNotNull(tEmployeeContractInfo.getPreId())) {
				TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
						.eq(TEmployeeContractPre::getId, tEmployeeContractInfo.getPreId())
						.in(TEmployeeContractPre::getProcessStatus, Arrays.asList("0","1","3","5","7","11"))
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPre)) {
					//合同状态初始为签署中
					contractPre.setProcessStatus("1".equals(contractPre.getSignType()) ?
							CommonConstants.TWO_STRING : CommonConstants.SIX_STRING);
					contractPre.setContractId(tEmployeeContractInfo.getId());
					contractPre.setErrorInfo("");
					contractPre.setErrorTime(null);

					contractPre.setSignFlag(CommonConstants.ONE_STRING);
					contractPre.setRevokeReason("");
					contractPreMapper.updateById(contractPre);
				}
			}
			//续签待办自动化状态更新
			if (Common.isNotNull(tEmployeeContractInfo.getPreId())) {
				TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
						.eq(TEmployeeContractPreNew::getId, tEmployeeContractInfo.getPreNewId())
						.in(TEmployeeContractPreNew::getProcessStatus, Arrays.asList("0","1","3","5","7","11"))
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPreNew)) {
					//合同状态初始为签署中
					contractPreNew.setProcessStatus("1".equals(contractPreNew.getSignType()) ?
							CommonConstants.TWO_STRING : CommonConstants.SIX_STRING);
					contractPreNew.setContractId(tEmployeeContractInfo.getId());
					contractPreNew.setErrorInfo("");
					contractPreNew.setErrorTime(null);

					contractPreNew.setSignFlag(CommonConstants.ONE_STRING);
					contractPreNew.setRevokeReason("");
					contractPreNewMapper.updateById(contractPreNew);
					//更新续签待办提醒的办理状态为处理中
					LambdaUpdateWrapper<TEmpContractAlert> updateWrapper = new LambdaUpdateWrapper<>();
					updateWrapper.eq(TEmpContractAlert::getContractId, contractPreNew.getContractId())
							.set(TEmpContractAlert::getHandleStatus, CommonConstants.ONE_STRING);
					contractAlertMapper.update(null,updateWrapper);
				}
			}
			// 瓜子项目编码：皖A694302
			if (CommonConstants.GZ_DEPT_NO.equals(tEmployeeContractInfo.getDeptNo())) {
				//合同申请瓜子合同状态更新成待签署
				updateGzOfferStatus(tEmployeeContractInfo,"97",CommonConstants.THIRTEEN_STRING,user.getId(),user.getNickname());
			}
		} else {
			// 标准合同、劳动派遣合同、其他。————社保公积金都派减，自动审核通过
			this.judgeAuditStatus(tEmployeeContractInfo, user);
			//撤销签署重新提交的话判断有没有合同待签订数据，有的话更新状态
			TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
					.eq(TEmployeeContractPre::getContractId, tEmployeeContractInfo.getId())
					.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TEN_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(contractPre)) {
				if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.TWO_INT) {
					contractPre.setProcessStatus(CommonConstants.FOUR_STRING);
				} else if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.ONE_INT) {
					contractPre.setProcessStatus(CommonConstants.TWO_STRING);
				}
				contractPre.setRevokeReason("");
				contractPre.setSignFlag(CommonConstants.ONE_STRING);
				contractPreMapper.updateById(contractPre);
			}
			//续签撤销签署重新提交的话判断有没有合同待签订数据，有的话更新状态 2026-02-10
			TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
					.eq(TEmployeeContractPreNew::getId, tEmployeeContractInfo.getPreNewId())
					.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.TEN_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(contractPreNew)) {
				if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.TWO_INT) {
					contractPreNew.setProcessStatus(CommonConstants.FOUR_STRING);
				} else if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.ONE_INT) {
					contractPreNew.setProcessStatus(CommonConstants.TWO_STRING);
				}
				contractPreNew.setRevokeReason("");
				contractPreNew.setSignFlag(CommonConstants.ONE_STRING);
				contractPreNewMapper.updateById(contractPreNew);
				//更新续签待办提醒的办理状态为处理中
				LambdaUpdateWrapper<TEmpContractAlert> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.eq(TEmpContractAlert::getContractId, contractPreNew.getContractId())
						.set(TEmpContractAlert::getHandleStatus, CommonConstants.ONE_STRING);
				contractAlertMapper.update(null,updateWrapper);
			}
			baseMapper.updateById(tEmployeeContractInfo);


		}
		// 不是待提交，记录审核记录
		this.setAuditInfo(tEmployeeContractInfo);

		// 更新档案合同状态

		if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.TWO_INT) {
			this.updateEmployeeContractStatus(tEmployeeContractInfo);
		}
		if (CommonConstants.TWO_STRING.equals(tEmployeeContractInfo.getContractType())
				|| CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getContractType())) {
			tEmployeeContractInfo.setContractEnd(null);
			baseMapper.updateContractEnd(tEmployeeContractInfo);
		}
		if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.TWO_INT) {
			return R.ok(null, CommonConstants.SAVE_AND_UPDATE);
		} else {
			return R.ok(null, CommonConstants.SAVE_SUCCESS);
		}
	}

	/**
	 * @Author fxj
	 * @Description 初始化审核类型  审核类型:0派增-社保派单、1派增-无社保新签、2派增-续签、3派减-作废、4派减-终止
	 * @Date 15:28 2022/11/7
	 **/
	private void initType(TEmployeeContractInfo tEmployeeContractInfo) {
		// 初始化审核类型  审核类型:0派增-社保派单、1派增-无社保新签、2派增-续签、3派减-作废、4派减-终止
		if (ArchivesConstants.contractSituation[0].equals(tEmployeeContractInfo.getSituation())) {
			// 作废
			tEmployeeContractInfo.setType(CommonConstants.THREE_STRING);
		}
		if (ArchivesConstants.contractSituation[6].equals(tEmployeeContractInfo.getSituation())) {
			// 终止
			tEmployeeContractInfo.setType(CommonConstants.FOUR_STRING);
		}
		if (ArchivesConstants.contractSituation[1].equals(tEmployeeContractInfo.getSituation())
				|| ArchivesConstants.contractSituation[2].equals(tEmployeeContractInfo.getSituation())
				|| ArchivesConstants.contractSituation[4].equals(tEmployeeContractInfo.getSituation())
				|| ArchivesConstants.contractSituation[5].equals(tEmployeeContractInfo.getSituation())) {
			// 离职再入职 合同未到期重新签订 商务合同更改 正常续签
			tEmployeeContractInfo.setType(CommonConstants.TWO_STRING);
		}
		if (ArchivesConstants.contractSituation[3].equals(tEmployeeContractInfo.getSituation())) {
			//正常签订
			tEmployeeContractInfo.setType(CommonConstants.ONE_STRING);
		}
		if (Common.isNotNull(tEmployeeContractInfo.getSignType()) && "0".equals(tEmployeeContractInfo.getSignType())) {
			tEmployeeContractInfo.setType(CommonConstants.FIVE_STRING);
		}
	}

	/**
	 * @param tEmployeeContractInfo
	 * @Description: 更新附件的合同id
	 * @Author: hgw
	 * @Date: 2022/7/20 10:07
	 * @return: void
	 **/
	private void updateFileMainId(TEmployeeContractInfo tEmployeeContractInfo) {
		List<String> attaList = tEmployeeContractInfo.getAttaList();
		if (null != attaList && !attaList.isEmpty()) {
			TAttaInfo contractAtta;
			for (String attaId : attaList) {
				contractAtta = tAttaInfoService.getById(attaId);
				if (contractAtta != null && Common.isEmpty(contractAtta.getDomainId())) {
					contractAtta.setDomainId(tEmployeeContractInfo.getId());
					tAttaInfoService.updateById(contractAtta);
				}
			}
		}
	}

	/**
	 * @param tEmployeeContractInfo
	 * @Description: 保存审核操作记录
	 * @Author: hgw
	 * @Date: 2022/7/1 10:16
	 * @return: void
	 **/
	private void setAuditInfo(TEmployeeContractInfo tEmployeeContractInfo) {
		if (Common.isNotNull(tEmployeeContractInfo.getAuditStatus())
				&& CommonConstants.ZERO_INT != tEmployeeContractInfo.getAuditStatus()) {
			TEmployeeContractAudit audit = new TEmployeeContractAudit();
			if (CommonConstants.ONE_INT == tEmployeeContractInfo.getAuditStatus() ||
					CommonConstants.FOUR_INT == tEmployeeContractInfo.getAuditStatus()) {
				audit.setRootName("提交申请");
			}
			if (CommonConstants.dingleDigitIntArray[2] == tEmployeeContractInfo.getAuditStatus()) {
				audit.setRootName("合同审核");
				audit.setAuditStatus("审核通过");
				audit.setRemark(tEmployeeContractInfo.getAuditRemark());
			}
			if (CommonConstants.dingleDigitIntArray[3] == tEmployeeContractInfo.getAuditStatus()) {
				audit.setRootName("合同审核");
				audit.setAuditStatus("审核不通过");
				audit.setRemark(tEmployeeContractInfo.getAuditRemark());
			}
			audit.setLinkId(tEmployeeContractInfo.getId());
			audit.setLinkType(CommonConstants.ONE_INT);
			tEmployeeContractAuditMapper.insert(audit);
			if (Common.isNotNull(tEmployeeContractInfo.getPreName())) {
				audit.setCreateName(tEmployeeContractInfo.getPreName());
				audit.setCreateBy("1");
				audit.setCreateTime(LocalDateTime.now());
			}
			if (Common.isNotNull(tEmployeeContractInfo.getLeaveName())) {
				audit.setCreateName(tEmployeeContractInfo.getLeaveName());
				audit.setCreateBy("1");
				audit.setCreateTime(LocalDateTime.now());
			}
			if (Common.isNotNull(tEmployeeContractInfo.getReNewSubmitter())){
				audit.setCreateName(tEmployeeContractInfo.getReNewSubmitter());
			}
			tEmployeeContractAuditMapper.updateById(audit);
		}
	}

	/**
	 * @param tEmployeeContractInfo
	 * @Description: 保存审核操作记录
	 * @Author: huyc
	 * @Date: 2023/6/16 10:16
	 * @return: void
	 **/
	private void setAuditInfoNew(TEmployeeContractInfo tEmployeeContractInfo) {
		TEmployeeContractAudit audit = new TEmployeeContractAudit();
		audit.setRootName("终止合同联动");
		audit.setLinkId(tEmployeeContractInfo.getId());
		audit.setLinkType(CommonConstants.ONE_INT);
		tEmployeeContractAuditMapper.insert(audit);
	}

	/**
	 * @Description: 合同归档记录
	 * @Author: hgw
	 * @Date: 2022/7/7 10:28
	 * @return: void
	 **/
	private void setFileInfo(String id, String remark) {
		TEmployeeContractAudit audit = new TEmployeeContractAudit();
		audit.setRootName("合同归档");
		audit.setLinkId(id);
		audit.setLinkType(CommonConstants.ONE_INT);
		audit.setRemark(remark);
		tEmployeeContractAuditMapper.insert(audit);
	}

	private void updateEmployeeContractStatus(TEmployeeContractInfo tEmployeeContractInfo) {
		if (!CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getInUse())) {
			// 非作废、终止，本条变为在用
			if (Common.isEmpty(tEmployeeContractInfo.getSituation())
					|| (!EmployeeConstants.SITUATION_SIX.equals(tEmployeeContractInfo.getSituation())
					&& !EmployeeConstants.SITUATION_SEVEN.equals(tEmployeeContractInfo.getSituation()))) {
				// 其他变为不在用
				baseMapper.updateInUseStatusById(tEmployeeContractInfo.getEmpId(), tEmployeeContractInfo.getDeptNo(), tEmployeeContractInfo.getId(), CommonConstants.ONE_STRING);
				tEmployeeContractInfo.setAuditTimeLast(LocalDateTime.now());
				tEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);
				baseMapper.updateById(tEmployeeContractInfo);
			} else {
				// 2022-7-22 16:54:12 产品倩倩与测试说，作废终止审核通过，仅将原先选择的合同不在用即可
				if (Common.isNotNull(tEmployeeContractInfo.getOldContractId())) {
					TEmployeeContractInfo old = this.getById(tEmployeeContractInfo.getOldContractId());
					if (old != null && Common.isNotNull(old.getId()) && CommonConstants.ZERO_STRING.equals(old.getInUse())) {
						old.setInUse(CommonConstants.ONE_STRING);
						this.updateById(old);
					}
				}
			}
		}
		TEmployeeInfo employeeInfo = tEmployeeInfoMapper.selectById(tEmployeeContractInfo.getEmpId());
		if (employeeInfo != null) {
			employeeInfo.setContractStatus(CommonConstants.ONE_INT);
			if (Common.isNotNull(tEmployeeContractInfo.getSituation())
					&& (EmployeeConstants.SITUATION_SIX.equals(tEmployeeContractInfo.getSituation())
					|| EmployeeConstants.SITUATION_SEVEN.equals(tEmployeeContractInfo.getSituation()))) {
				TEmployeeContractInfo contractInfoInUse = this.getOne(Wrappers.<TEmployeeContractInfo>query()
						.lambda().eq(TEmployeeContractInfo::getEmpId, tEmployeeContractInfo.getEmpId())
						.and(obj -> obj.ge(TEmployeeContractInfo::getContractEnd, DateUtil.getThisDayByPatten("yyyy-MM-dd"))
								.or().isNull(TEmployeeContractInfo::getContractEnd))
						.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL));
				if (contractInfoInUse != null) {
					employeeInfo.setContractStatus(CommonConstants.ONE_INT);
				} else {
					employeeInfo.setContractStatus(CommonConstants.TWO_INT);
				}
			}
			tEmployeeInfoMapper.updateById(employeeInfo);
		}
		TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
				.lambda().eq(TEmployeeProject::getEmpId, tEmployeeContractInfo.getEmpId())
				.eq(TEmployeeProject::getDeptId, tEmployeeContractInfo.getSettleDomain())
				.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
				.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.last(CommonConstants.LAST_ONE_SQL));
		if (tEmployeeProject != null) {
			tEmployeeProject.setContractStatus(CommonConstants.ONE_INT);
			if (Common.isNotNull(tEmployeeContractInfo.getSituation())
					&& (EmployeeConstants.SITUATION_SIX.equals(tEmployeeContractInfo.getSituation())
					|| EmployeeConstants.SITUATION_SEVEN.equals(tEmployeeContractInfo.getSituation()))) {
				tEmployeeProject.setContractStatus(CommonConstants.TWO_INT);
			}
			tEmployeeProjectService.updateById(tEmployeeProject);
		}
	}

	@Override
	public boolean updateInUseStatusById(String empId, String deptNo, String ContractId) {
		return baseMapper.updateInUseStatusById(empId, deptNo, ContractId, CommonConstants.ONE_STRING) > 0;
	}

	@Override
	public R<String> auditContract(TEmployeeContractInfo tEmployeeContractInfo, YifuUser user, boolean isNotFascLog) {
		// 是否电子签，默认否
		boolean fascFlag = false;
		if (tEmployeeContractInfo != null) {
			if (Common.isEmpty(tEmployeeContractInfo.getId()) || Common.isEmpty(tEmployeeContractInfo.getAuditStatus())) {
				return R.failed("id、意见必填");
			}
			TEmployeeContractInfo contractInfo = this.getById(tEmployeeContractInfo.getId());
			if (Common.isNotNull(contractInfo.getSignType()) && CommonConstants.ZERO_STRING.equals(contractInfo.getSignType())) {
				fascFlag = true;
			}
			if (contractInfo.getAuditStatus() != CommonConstants.ONE_INT
					&& !fascFlag) {
				// 电子签的也要审核
				return R.failed("不是待审核状态！");
			}
			if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.dingleDigitIntArray[2]) {
				// 非作废、终止，本条变为在用
				if (Common.isEmpty(contractInfo.getSituation())
						|| (!EmployeeConstants.SITUATION_SIX.equals(contractInfo.getSituation())
						&& !EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation()))) {
					// 其他变为不在用
					baseMapper.updateInUseStatusById(contractInfo.getEmpId(), contractInfo.getDeptNo(), contractInfo.getId(), CommonConstants.ONE_STRING);
					tEmployeeContractInfo.setAuditTimeLast(LocalDateTime.now());
					tEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);
					// 更新档案、项目合同状态为（1可用）
					TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
							.lambda().eq(TEmployeeProject::getEmpId, contractInfo.getEmpId())
							.eq(TEmployeeProject::getDeptId, contractInfo.getSettleDomain())
							.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
							.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
							.last(CommonConstants.LAST_ONE_SQL));
					// 渲染字典值
					Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
							CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "personnel_type");
					String tempStr = null;
					for (Map.Entry<String, String> entry : dicObj.entrySet()) {
						if (Common.isNotNull(entry.getValue()) && entry.getValue().equals(contractInfo.getContractName())) {
							tempStr = entry.getKey();
							break;
						}
					}
					if (tEmployeeProject != null) {
						tEmployeeProject.setContractStatus(CommonConstants.ONE_INT);
						//签订类型正常签订的时候更新项目档案信息
						if (EmployeeConstants.SITUATION_ONE.equals(contractInfo.getSituation())) {
							tEmployeeProject.setContractType(null == tempStr ? "" : tempStr);
							tEmployeeProject.setWorkingHours(contractInfo.getWorkingHours());
							tEmployeeProject.setPost(contractInfo.getPost());
							tEmployeeProject.setEnjoinDate(contractInfo.getContractStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
							tEmployeeProject.setTryPeriod(contractInfo.getTryPeriod());
						}
						tEmployeeProjectService.updateById(tEmployeeProject);
					}
					// 更新档案、项目合同状态为（1在用）
					TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(contractInfo.getEmpId());
					if (tEmployeeInfo != null) {
						tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
						tEmployeeInfoMapper.updateById(tEmployeeInfo);
					}
					//签订类型正常签订的时候更新预入职列表
					if (EmployeeConstants.SITUATION_ONE.equals(contractInfo.getSituation())) {
						//根据项目编码和身份证号查询预入职列表
						TPreEmpMain empMain = preEmpMainMapper.selectOne(Wrappers.<TPreEmpMain>query()
								.lambda().eq(TPreEmpMain::getEmpIdcard, contractInfo.getEmpIdcard())
								.eq(TPreEmpMain::getDeptNo, contractInfo.getDeptNo())
								.ne(TPreEmpMain::getStatus, CommonConstants.FIVE_STRING)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Optional.ofNullable(empMain).isPresent()) {
							//查询预入职项目档案表
							TPreEmployeeProject preEmployeeProject = preEmployeeProjectMapper.selectOne(Wrappers.<TPreEmployeeProject>query()
									.lambda().eq(TPreEmployeeProject::getPreMainId, empMain.getId()));
							if (Optional.ofNullable(preEmployeeProject).isPresent()) {
								preEmployeeProject.setContractType(null == tempStr ? "" : tempStr);
								preEmployeeProject.setWorkingHours(contractInfo.getWorkingHours());
								preEmployeeProject.setPost(contractInfo.getPost());
								preEmployeeProject.setEnjoinDate(contractInfo.getContractStart());
								preEmployeeProject.setTryPeriod(contractInfo.getTryPeriod());
								preEmployeeProjectMapper.updateById(preEmployeeProject);
							}
						}
					}
				} else {
					//是否同步终止合同、减项、减档为是的时候 单独写逻辑
					if (EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation())
							&& Common.isNotNull(contractInfo.getChangeContractAndEmployee())
							&& CommonConstants.ZERO_STRING.equals(contractInfo.getChangeContractAndEmployee())) {
						changeStatus(contractInfo, user);
					} else {
						//baseMapper.updateInUseStatusById(contractInfo.getEmpId(), contractInfo.getSettleDomain(), contractInfo.getId(), CommonConstants.ONE_STRING)
						if (Common.isNotNull(contractInfo.getOldContractId())) {
							TEmployeeContractInfo old = this.getById(contractInfo.getOldContractId());
							if (old != null && Common.isNotNull(old.getId())) {
								if (!CommonConstants.ZERO_STRING.equals(old.getInUse())) {
									return R.failed("关联的原合同已不在用");
								} else {
									old.setInUse(CommonConstants.ONE_STRING);
									this.updateById(old);
								}
							} else {
								return R.failed("未找到关联的原合同");
							}
						} else {
							return R.failed("未找到关联的原合同");
						}
						doZhongZhiContract(contractInfo, user);
						// 作废、终止审核通过：
						// 更新项目合同状态为（2不在用），档案状态要判断
						TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
								.lambda().eq(TEmployeeProject::getEmpId, contractInfo.getEmpId())
								.eq(TEmployeeProject::getDeptId, contractInfo.getSettleDomain())
								.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
								.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
								.last(CommonConstants.LAST_ONE_SQL));
						if (tEmployeeProject != null) {
							tEmployeeProject.setContractStatus(CommonConstants.TWO_INT);
							tEmployeeProjectService.updateById(tEmployeeProject);
						}

						// 更新档案、项目合同状态为（0无合同 1在用 2不在用）
						TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(contractInfo.getEmpId());
						if (tEmployeeInfo != null) {
							// 判断人员有无审核通过的其他合同
							TEmployeeContractInfo contractInfoInUse = this.getOne(Wrappers.<TEmployeeContractInfo>query()
									.lambda().eq(TEmployeeContractInfo::getEmpId, contractInfo.getEmpId())
									.and(obj -> obj.ge(TEmployeeContractInfo::getContractEnd, DateUtil.getThisDayByPatten("yyyy-MM-dd"))
											.or().isNull(TEmployeeContractInfo::getContractEnd))
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
									.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
									.last(CommonConstants.LAST_ONE_SQL));
							if (contractInfoInUse != null) {
								tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
							} else {
								tEmployeeInfo.setContractStatus(CommonConstants.TWO_INT);
							}
							tEmployeeInfoMapper.updateById(tEmployeeInfo);
						}
					}
				}
				if (!fascFlag) {
					//更新合同状态为4线下签待归档
					TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
							.eq(TEmployeeContractPre::getContractId, contractInfo.getId())
							.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(contractPre)) {
						contractPre.setProcessStatus(CommonConstants.FOUR_STRING);
						contractPreMapper.updateById(contractPre);
					}
					//更新续签待办续签状态为4线下签待归档
					TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
							.eq(TEmployeeContractPreNew::getId, contractInfo.getPreNewId())
							.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.TWO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(contractPreNew)) {
						contractPreNew.setProcessStatus(CommonConstants.FOUR_STRING);
						contractPreNewMapper.updateById(contractPreNew);
					}
				}
				//瓜子项目编码：皖A694302
				if (CommonConstants.GZ_DEPT_NO.equals(contractInfo.getDeptNo())) {
					//审核通过瓜子合同状态更新合同审核通过
					updateGzOfferStatus(contractInfo,CommonConstants.THIRTEEN_STRING,CommonConstants.EIGHT_STRING,user.getId(),user.getNickname());
				}

				if (EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation())) {
					// 合同终止，通知离职待办变更状态
					this.sendLeave(contractInfo.getId(), CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, tEmployeeContractInfo.getAuditRemark(), user);
				}
			}
			if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.dingleDigitIntArray[3]) {
				if (!fascFlag) {
					//更新合同状态为3线下签审核不通过
					TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
							.eq(TEmployeeContractPre::getContractId, contractInfo.getId())
							.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(contractPre)) {
						contractPre.setProcessStatus(CommonConstants.THREE_STRING);
						contractPreMapper.updateById(contractPre);
					}
					//更新续签待办的续签状态为3线下签审核不通过
					TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
							.eq(TEmployeeContractPreNew::getId, contractInfo.getPreNewId())
							.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.TWO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(contractPreNew)) {
						contractPreNew.setProcessStatus(CommonConstants.THREE_STRING);
						contractPreNew.setErrorInfo(tEmployeeContractInfo.getAuditRemark());
						contractPreNew.setErrorTime(new Date());
						contractPreNewMapper.updateById(contractPreNew);
						//更新合同提醒办理状态
						LambdaUpdateWrapper<TEmpContractAlert> updateWrapper = new LambdaUpdateWrapper<>();
						updateWrapper.eq(TEmpContractAlert::getContractId, contractPreNew.getContractId())
								.set(TEmpContractAlert::getHandleStatus, CommonConstants.ZERO_STRING);
						contractAlertMapper.update(null, updateWrapper);
					}
				}
				if (EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation())) {
					// 合同终止，通知离职待办变更状态
					this.sendLeave(contractInfo.getId(), CommonConstants.TEN_STRING, CommonConstants.ZERO_STRING, tEmployeeContractInfo.getAuditRemark(), user);
				}
			}
			tEmployeeContractInfo.setAuditUserName(user.getNickname());
			tEmployeeContractInfo.setContractNo(contractInfo.getContractNo());
			// 不是待提交，记录审核记录
			// 非法大大，要日志，法大大的签署完成，不要这个日志，有了其他的日志
			if (isNotFascLog) {
				this.setAuditInfo(tEmployeeContractInfo);
			}
			this.updateById(tEmployeeContractInfo);
			return R.ok();
		}
		return R.failed("参数不可为空");
	}

	@Override
	public R<String> deleteContract(@RequestParam String id) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		TEmployeeContractInfo contractInfo = this.getById(id);
		if (contractInfo == null) {
			return R.failed("未找到记录");
		} else {
			if (!user.getId().equals(contractInfo.getCreateBy())) {
				return R.failed(EmployeeContractConstants.NOT_CREATE_USER);
			}
			if (contractInfo.getAuditStatus() != CommonConstants.ZERO_INT
					&& contractInfo.getAuditStatus() != CommonConstants.dingleDigitIntArray[3]) {
				return R.failed(EmployeeContractConstants.NOT_AUDIT_STATUS);
			}
			contractInfo.setDeleteFlag(CommonConstants.ONE_INT);
			this.updateById(contractInfo);
		}
		return R.ok();
	}

	@Override
	public R<List<ErrorVO>> batchDeleteContract(List<String> idList) {
		if (idList == null || idList.isEmpty()) {
			return R.failed("请选择！");
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		List<ErrorVO> returnList = new ArrayList<>();
		TEmployeeContractInfo contractInfo;
		String id;
		ErrorVO errorVo;
		for (int i = 0; i < idList.size(); i++) {
			errorVo = new ErrorVO();
			errorVo.setResult(CommonConstants.ZERO_INT);
			errorVo.setLineNum(i + 1);
			id = idList.get(i);
			contractInfo = this.getById(id);
			if (contractInfo == null) {
				errorVo.setErrorInfo(EmployeeContractConstants.NO_INFO);
			} else {
				errorVo.setMainName(contractInfo.getApplyNo());
				if (!user.getId().equals(contractInfo.getCreateBy())) {
					errorVo.setErrorInfo(EmployeeContractConstants.NOT_CREATE_USER);
				} else if (contractInfo.getAuditStatus() != CommonConstants.ZERO_INT) {
					errorVo.setErrorInfo(EmployeeContractConstants.NOT_AUDIT_STATUS);
				} else {
					errorVo.setResult(CommonConstants.ONE_INT);
					contractInfo.setDeleteFlag(CommonConstants.ONE_INT);
					this.updateById(contractInfo);
				}
			}
			returnList.add(errorVo);
		}
		boolean isTrue = true;
		for (ErrorVO message : returnList) {
			if (CommonConstants.ZERO_INT == message.getResult()) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(returnList);
		}
	}

	@Override
	public R<String> filingContract(TEmployeeContractInfo tEmployeeContractInfo, YifuUser user) {

		if (tEmployeeContractInfo != null) {
			if ((Common.isNotNull(tEmployeeContractInfo.getContractNo()) && tEmployeeContractInfo.getContractNo().length() > 50)
					|| (Common.isNotNull(tEmployeeContractInfo.getFileCabinetNo()) && tEmployeeContractInfo.getFileCabinetNo().length() > 50)) {
				return R.failed("合同编号、档案柜号不可超过50字！");
			}
			//档案柜存在就自动归档
			if (Common.isNotNull(tEmployeeContractInfo.getAttaList())) {
				this.updateFileMainId(tEmployeeContractInfo);
				this.setFileInfo(tEmployeeContractInfo.getId(), "");
				tEmployeeContractInfo.setIsFile(CommonConstants.ZERO_STRING);
				//更新合同待签订数据状态为4线下签待归档
				TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
						.eq(TEmployeeContractPre::getContractId, tEmployeeContractInfo.getId())
						.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.FOUR_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPre)) {
					contractPre.setProcessStatus(CommonConstants.NINE_STRING);
					contractPreMapper.updateById(contractPre);
					//把关联的其他附件置空
					LambdaUpdateWrapper<TAttaInfo> updateWrapper = new LambdaUpdateWrapper<>();
					// 设置更新条件和新值
					updateWrapper.eq(TAttaInfo::getDomainId, contractPre.getId())
							.set(TAttaInfo::getDomainId, CommonConstants.EMPTY_STRING);
					// 执行更新操作，清空附件的ID
					tAttaInfoService.update(updateWrapper);
					//附件同步
					if (Common.isNotNull(tEmployeeContractInfo.getAttaList()) && !tEmployeeContractInfo.getAttaList().isEmpty()) {
						for (String id : tEmployeeContractInfo.getAttaList()) {
							//附件赋值
							TAttaInfo attaInfo = tAttaInfoService.getById(id);
							if (attaInfo != null) {
								TAttaInfo attaInfoPre = new TAttaInfo();
								BeanUtils.copyProperties(attaInfo, attaInfoPre);
								attaInfoPre.setDomainId(contractPre.getId());
								attaInfoPre.setId(null);
								tAttaInfoService.save(attaInfoPre);
							}
						}
					}
				}
				//更新续签待办合同待签订数据状态为4线下签待归档 为已归档
				TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
						.eq(TEmployeeContractPreNew::getId, tEmployeeContractInfo.getPreNewId())
						.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.FOUR_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPreNew)) {
					contractPreNew.setProcessStatus(CommonConstants.NINE_STRING);
					contractPreNewMapper.updateById(contractPreNew);
					//更新合同续签提醒办理状态为已完成
					LambdaUpdateWrapper<TEmpContractAlert> updateWrapperAlert = new LambdaUpdateWrapper<>();
					updateWrapperAlert.eq(TEmpContractAlert::getContractId, contractPreNew.getContractId())
							.set(TEmpContractAlert::getHandleStatus, CommonConstants.TWO_INT);
					contractAlertMapper.update(null, updateWrapperAlert);
					//把关联的其他附件置空
					LambdaUpdateWrapper<TAttaInfo> updateWrapper = new LambdaUpdateWrapper<>();
					// 设置更新条件和新值
					updateWrapper.eq(TAttaInfo::getDomainId, contractPreNew.getId())
							.set(TAttaInfo::getDomainId, CommonConstants.EMPTY_STRING);
					// 执行更新操作，清空附件的ID
					tAttaInfoService.update(updateWrapper);
					//附件同步
					if (Common.isNotNull(tEmployeeContractInfo.getAttaList()) && !tEmployeeContractInfo.getAttaList().isEmpty()) {
						for (String id : tEmployeeContractInfo.getAttaList()) {
							//附件赋值
							TAttaInfo attaInfo = tAttaInfoService.getById(id);
							if (attaInfo != null) {
								TAttaInfo attaInfoPre = new TAttaInfo();
								BeanUtils.copyProperties(attaInfo, attaInfoPre);
								attaInfoPre.setDomainId(contractPreNew.getId());
								attaInfoPre.setId(null);
								tAttaInfoService.save(attaInfoPre);
							}
						}
					}
				}
				//瓜子项目编码：皖A694302
				if (CommonConstants.GZ_DEPT_NO.equals(tEmployeeContractInfo.getDeptNo())) {
					//合同归档瓜子合同状态更新已归档
					updateGzOfferStatus(tEmployeeContractInfo,CommonConstants.EIGHT_STRING,CommonConstants.NINETY_NINE,user.getId(),user.getNickname());
				}
			} else {
				this.setFileInfo(tEmployeeContractInfo.getId(), "");
				tEmployeeContractInfo.setIsFile(CommonConstants.ONE_STRING);
			}
			this.updateById(tEmployeeContractInfo);
			return R.ok();
		}
		return R.failed("参数不可为空");
	}

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

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

				@Override
				public void invoke(EmployeeContractUpdateVO 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());
					if (!cachedDataList.isEmpty()) {
						updateContract(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);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	/**
	 * @Author hgw
	 * @Description 批量导入
	 * @Date 2022-7-1 18:48:01
	 **/
	@Transactional
	public void updateContract(List<EmployeeContractUpdateVO> excelVOList, List<ErrorMessage> errorMessageList) {
		/// 个性化校验逻辑
		EmployeeContractUpdateVO excel;
		TEmployeeContractInfo contractInfo;
		TEmployeeContractInfo newContractInfo;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if (excel != null) {
				if (Common.isNotNull(excel.getContractNo()) || Common.isNotNull(excel.getFileCabinetNo())) {
					if (Common.isNotNull(excel.getApplyNo())) {
						// 存储
						contractInfo = baseMapper.getOneContractByApplyNo(excel.getApplyNo());
						if (contractInfo != null && Common.isNotNull(contractInfo.getId())) {
							if (CommonConstants.dingleDigitIntArray[2] != contractInfo.getAuditStatus()) {
								errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeContractConstants.NOT_AUDIT));
							} else if (EmployeeConstants.SITUATION_SIX.equals(contractInfo.getSituation())
									|| EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation())) {
								errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeContractConstants.INVALID));
							} else {
								newContractInfo = new TEmployeeContractInfo();
								newContractInfo.setId(contractInfo.getId());
								newContractInfo.setContractNo(excel.getContractNo());
								newContractInfo.setFileCabinetNo(excel.getFileCabinetNo());
								this.updateById(newContractInfo);
								// 记录变更日志
								tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[3], contractInfo.getId(), "", contractInfo, newContractInfo);
								errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
							}
						} else {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeContractConstants.NO_INFO));
						}
					}
				} else {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeContractConstants.NO_CONTRACT_FILE_CABINET));
				}
			} else {
				errorMessageList.add(new ErrorMessage(CommonConstants.ZERO_INT, EmployeeContractConstants.NO_INFO));
			}
		}
	}

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

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

				@Override
				public void invoke(EmployeeContractVO 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());
					if (!cachedDataList.isEmpty()) {
						importContract(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);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	@Override
	public BaseSearchListVO leaveToReduceContract(BaseSearchListVO paramVo) {
		List<String> idList = new ArrayList<>();
		List<BaseSearchVO> listParam = paramVo.getListParam();
		String userName = paramVo.getUserName();
		Map<String, BaseSearchVO> paramMap = new HashMap<>();
		for (BaseSearchVO param : listParam) {
			idList.add(param.getSearchKey());
			paramMap.put(param.getSearchKey(), param);
		}
		// 合同ID，离职待办ID
		List<EmployeeContractVO> excelVOList = baseMapper.getLeaveContractList(idList);
		BaseSearchListVO baseSearchListVO = new BaseSearchListVO();
		BaseSearchVO baseSearchVO;
		if (excelVOList != null && !excelVOList.isEmpty()) {
			Map<Integer, String> rowLeaveMap = new HashMap<>();
			int i=0;
			String leaveId;
			String leaveDate;
			String leaveReason;
			for (EmployeeContractVO vo : excelVOList) {
				i++;
				vo.setRowIndex(i);
				vo.setLeaveName(userName);
				baseSearchVO = paramMap.get(vo.getContractId());
				leaveId = null;
				if (baseSearchVO != null) {
					leaveId = baseSearchVO.getResultIdOne();
					leaveDate = baseSearchVO.getResultIdTwo();
					leaveReason = baseSearchVO.getResultIdThree();
					vo.setLeaveDate(leaveDate);
					vo.setReduceReason(leaveReason);
					vo.setChangeContractAndEmployee(CommonConstants.ONE_STRING);
				}
				if (Common.isNotNull(leaveId)) {
					rowLeaveMap.put(i, leaveId);
					vo.setLeaveId(leaveId);
				}
			}
			List<ErrorMessage> errorMessageList = new ArrayList<>();
			// 调用原导入方法
			this.importContract(excelVOList, errorMessageList);
			// 组装对应关系，key是原id，name是新ID
			if (!errorMessageList.isEmpty()) {
				for (ErrorMessage message : errorMessageList) {
					if (Common.isNotNull(message.getLineNum())) {
						message.setKey(rowLeaveMap.get(message.getLineNum()));
					}
				}
			}
			baseSearchListVO.setErrorMessageList(errorMessageList);
		}
		return baseSearchListVO;

	}

	/**
	 * @Author hgw
	 * @Description 批量导入
	 * @Date 2022-7-1 18:48:01
	 **/
	@Transactional
	public void importContract(List<EmployeeContractVO> excelVOList, List<ErrorMessage> errorMessageList) {
		/// 个性化校验逻辑
		EmployeeContractVO excel;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			// 存储
			this.insertExcel(excel, errorMessageList);
		}
	}

	/**
	 * 插入excel education
	 */
	private void insertExcel(EmployeeContractVO excel, List<ErrorMessage> errorMessageList) {
		TEmployeeContractInfo insert = new TEmployeeContractInfo();
		BeanUtil.copyProperties(excel, insert);

		try {
			StringBuilder errorInfo = new StringBuilder();
			if (EmployeeConstants.OTHERS.equals(insert.getContractName()) && Common.isEmpty(insert.getContractSubName())) {
				errorInfo.append(EmployeeConstants.SUB_MUST);
			}
			if (Common.isEmpty(insert.getEmpIdcard()) || Common.isEmpty(insert.getDeptNo())) {
				errorInfo.append(EmployeeConstants.EMPID_NOT_EMPTY);
			} else {
				//签订类型为 新签 试用期必填
				if (EmployeeConstants.SITUATION_ONE.equals(insert.getSituation()) && Common.isEmpty(insert.getTryPeriod())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeConstants.CONTRACT_TRY_PERIOD_EMPTY));
					return;
				}
				//签订类型不是终止的把是否同步终止合同、减项、减档设为空
				if (!EmployeeConstants.SITUATION_SEVEN.equals(insert.getSituation())) {
					insert.setChangeContractAndEmployee(null);
				}
				if (EmployeeConstants.SITUATION_SIX.equals(insert.getSituation())
						|| EmployeeConstants.SITUATION_SEVEN.equals(insert.getSituation())) {
					// 终止  离职日期 和减少原因必填
					if (EmployeeConstants.SITUATION_SEVEN.equals(insert.getSituation())) {
						if (Common.isEmpty(insert.getReduceReason()) || Common.isEmpty(insert.getLeaveDate()) || Common.isEmpty(insert.getChangeContractAndEmployee())) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeConstants.CONTRACT_REDUCE_INFO_NOT_EMPTY));
							return;
						}
						if (EmployeeConstants.OTHERS.equals(insert.getReduceReason()) &&
								Common.isEmpty(insert.getReason())) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeConstants.CONTRACT_REDUCE_REASON_NOT_EMPTY));
							return;
						}
					}
					TEmployeeContractInfo contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, insert.getEmpIdcard())
							.eq(TEmployeeContractInfo::getDeptNo, insert.getDeptNo())
							.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).last(CommonConstants.LAST_ONE_SQL));
					if (contractInfo == null) {
						errorInfo.append(EmployeeConstants.CONTRACT_NO_IN_USE);
					} else {
						insert.setOldContractId(contractInfo.getId());
						insert.setContractName(contractInfo.getContractName());
						insert.setContractSubName(contractInfo.getContractSubName());
						insert.setSubjectUnit(contractInfo.getSubjectUnit());
						insert.setContractParty(contractInfo.getContractParty());
						insert.setContractType(contractInfo.getContractType());
						insert.setContractStart(contractInfo.getContractStart());
						insert.setContractEnd(contractInfo.getContractEnd());
					}
				} else {
					TSettleDomain settleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
							.eq(TSettleDomain::getDepartNo, insert.getDeptNo())
							.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
							.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
					if (Common.isEmpty(settleDomain)) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EmployeeConstants.EMP_DISPATCH_SETTLEDOMAIN_STOP));
						return;
					}
					// 2022-9-28 16:59:57 徐梅说产品在验收时，业务说已完成一定任务的也不必填
					if (EmployeeConstants.CONTRACT_TYPE_ONE.equals(insert.getContractType())
							&& Common.isEmpty(insert.getContractEnd())) {
						errorInfo.append(EmployeeConstants.CONTRACT_END_MUST);
					}
					if (Common.isEmpty(insert.getContractName())) {
						errorInfo.append(EmployeeConstants.CONTRACT_NAME_EMPTY);
					}
					if (Common.isEmpty(insert.getContractParty())) {
						errorInfo.append(EmployeeConstants.CONTRACT_PARTY_EMPTY);
					}
					if (Common.isEmpty(insert.getContractType())) {
						errorInfo.append(EmployeeConstants.CONTRACT_TYPE_EMPTY);
					}
					if (Common.isEmpty(insert.getContractStart())) {
						errorInfo.append(EmployeeConstants.CONTRACT_START_EMPTY);
					}
					if (Common.isEmpty(insert.getPost())) {
						errorInfo.append(EmployeeConstants.POST_EMPTY);
					}
					if (Common.isEmpty(insert.getWorkingHours())) {
						errorInfo.append(EmployeeConstants.WORKING_HOURS_EMPTY);
					}
				}
				TEmployeeContractInfo contractInfo;
				if (!EmployeeConstants.SITUATION_SEVEN.equals(insert.getSituation()) && !EmployeeConstants.SITUATION_SIX.equals(insert.getSituation())) {
					if (CommonConstants.CONTRACT_TYPE_TWO.equals(insert.getContractType()) || CommonConstants.CONTRACT_TYPE_ZERO.equals(insert.getContractType())) {
						contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
								.eq(TEmployeeContractInfo::getEmpIdcard, insert.getEmpIdcard())
								.eq(TEmployeeContractInfo::getContractStart, insert.getContractStart())
								.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
								.and(obj -> obj.eq(TEmployeeContractInfo::getContractType, CommonConstants.TWO_STRING)
										.or()
										.eq(TEmployeeContractInfo::getContractType, CommonConstants.ZERO_STRING)
								)
								.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
										.or()
										.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
										.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
								)
								.last(CommonConstants.LAST_ONE_SQL));
						if (contractInfo != null) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该员工已存在相同起始日期的合同，禁止重复添加！"));
							return;

						}
					} else {
						contractInfo = this.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
								.eq(TEmployeeContractInfo::getEmpIdcard, insert.getEmpIdcard())
								.eq(TEmployeeContractInfo::getContractStart, insert.getContractStart())
								.eq(TEmployeeContractInfo::getContractEnd, insert.getContractEnd())
								.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
								.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
										.or()
										.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
										.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
								)
								.last(CommonConstants.LAST_ONE_SQL));
						if (contractInfo != null) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该员工已存在相同起始和截止日期的合同，禁止重复添加"));
							return;
						}
					}
				}

			}

			if (Common.isEmpty(errorInfo.toString())) {
				TEmployeeProject project = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getEmpIdcard, insert.getEmpIdcard())
						.eq(TEmployeeProject::getDeptNo, insert.getDeptNo())
						.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
						.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT).last(CommonConstants.LAST_ONE_SQL));
				if (project == null) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), EMPINFO_IS_NOT_EXITS_BYID));
				} else {
					insert.setEmpId(project.getEmpId());
					insert.setSettleDomain(project.getDeptId());
					// 批量直接待审核
					insert.setAuditStatus(CommonConstants.ONE_INT);
					if (Common.isEmpty(insert.getContractTerm())
							&& Common.isNotNull(insert.getContractStart())
							&& Common.isNotNull(insert.getContractEnd())) {
						//1.9.12合同年限优化
						long daysDiff = DateUtil.getDaysDiff(insert.getContractStart(), insert.getContractEnd());
						if (daysDiff < 0) {
							insert.setContractTerm("0.0");
						} else {
							double years = daysDiff / 365.25; // 考虑闰年因素
							BigDecimal b = BigDecimal.valueOf(years).setScale(2, RoundingMode.HALF_UP);
							insert.setContractTerm(b.toString());
						}
//						int monthDiff = DateUtil.getMonthDiff(insert.getContractStart(), insert.getContractEnd());
//						BigDecimal b = new BigDecimal(String.valueOf(monthDiff / 12.0));
//						b = b.setScale(1, BigDecimal.ROUND_HALF_UP);
//						insert.setContractTerm(String.valueOf(b));
					}
					// 处理signType字段
					if (Common.isNotNull(excel.getSignType())) {
						insert.setSignType(excel.getSignType());
					}
					
					// 核心保存
					R<List<ErrorMessage>> info = this.setBaseInfo(insert, project);
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), info.getMsg(), CommonConstants.ZERO_STRING, insert.getId()));
				}
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorInfo.toString()));
			}
		} catch (Exception e) {
			log.error("员工合同保存异常：" + e.getMessage());
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_FAILED));
		}
	}

	/**
	 * @Description: 标准合同、劳动派遣合同、其他。————社保公积金都派减，自动审核通过,
	 * 判断同项目的社保公积金都已派减，则无需审核
	 * @Author: hgw
	 * @Date: 2022/11/28 10:05
	 * @return: void
	 **/


	private void judgeAuditStatus(TEmployeeContractInfo insert, YifuUser user) {
		if (insert.getAuditStatus() == CommonConstants.ONE_INT
				&& (EmployeeConstants.CONTRACT_NAME[0].equals(insert.getContractName())
				|| EmployeeConstants.CONTRACT_NAME[1].equals(insert.getContractName())
				|| EmployeeConstants.CONTRACT_NAME[2].equals(insert.getContractName()))) {
			TSocialFundInfo sf = new TSocialFundInfo();
			sf.setEmpIdcard(insert.getEmpIdcard());
			sf.setSettleDomain(insert.getSettleDomain());
			if (!("合同未到期重新签订").equals(insert.getSituation())&&!("正常续签").equals(insert.getSituation())
					&&!("离职再入职").equals(insert.getSituation()) &&!("商务合同更改").equals(insert.getSituation())
					&&!("正常签订").equals(insert.getSituation())) {
				R<Integer> socialFundR = HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
					, "/tsocialfundinfo/inner/selectSocialFoundByContract", sf, Integer.class, SecurityConstants.FROM_IN);
				if (socialFundR != null && socialFundR.getData() != null && socialFundR.getData() > 0) {
					insert.setAuditStatus(CommonConstants.TWO_INT);
					insert.setAuditUserName(user.getNickname());
					if (EmployeeConstants.SITUATION_SEVEN.equals(insert.getSituation())
							&& Common.isNotNull(insert.getChangeContractAndEmployee())
							&& CommonConstants.ZERO_STRING.equals(insert.getChangeContractAndEmployee())) {
						changeStatus(insert, user);
					}
				}
			}
		}
	}

	/**
	 * 导出
	 */
	@Override
	public void exportContractInfo(TEmployeeContractInfo contractInfo, HttpServletResponse response) {
		if (contractInfo != null && contractInfo.getExportFields() != null && !contractInfo.getExportFields().isEmpty()) {
			String fileName = "员工合同批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
			//获取要导出的列表
			List<EmployeeContractExportVO> list = new ArrayList<>();
			ServletOutputStream out = null;
			Integer count = baseMapper.selectCountContractExport(contractInfo);
			try {
				ExcelUtil<EmployeeContractExportVO> util = new ExcelUtil<>(EmployeeContractExportVO.class);
				out = response.getOutputStream();
				response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
				response.setCharacterEncoding(CommonConstants.UTF8);
				response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
				// 获取所有字典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, EmployeeContractExportVO.class)
						.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
						.includeColumnFieldNames(contractInfo.getExportFields()).build();
				int index = 0;
				if (count > CommonConstants.ZERO_INT) {
					WriteSheet writeSheet;
					for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
						// 获取实际记录
						contractInfo.setLimitStart(i);
						contractInfo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
						list = baseMapper.getTEmployeeContractExport(contractInfo);
						if (Common.isNotNull(list)) {
							for (EmployeeContractExportVO ll : list) {
								if (ll.getRemark() != null) {
									if (!ll.getRemark().contains("派增审核")) {
										if (ll.getAuditStatus().contains("审核不通过") && null != ll.getRemark()) {
											if(!ll.getRemark().contains("-")&&!ll.getRemark().contains(":")){
												ll.setNoPassReason(ll.getRemark());
												ll.setRemark("");
											}
											if (ll.getRemark().contains(":")) {
												String a = ll.getRemark().substring(0, ll.getRemark().indexOf(":", 1));
												String b = ll.getRemark().substring(ll.getRemark().indexOf(":", 1) + 1);
												ll.setNoPassReason(a);
												ll.setRemark(b);
											}
										}
									}
									if (ll.getRemark().contains("派增审核")) {
									        if (ll.getRemark().contains("：")&&!ll.getRemark().contains(":")){
                                                 if(ll.getRemark().split("：").length==2){
													 int indexOne = ll.getRemark().indexOf("：");
													 String after1 = ll.getRemark().substring(indexOne + 1);
													 ll.setNoPassReason(after1);
													 ll.setRemark("");
												 }

											}
										if (ll.getRemark().contains("-")) {
											String c = ll.getRemark().substring(0, ll.getRemark().indexOf("-", 1));
											String d = ll.getRemark().substring(ll.getRemark().indexOf("-", 1) + 1);
											ll.setNoPassReason(c);
											ll.setRemark(d);
										}
									}

								}
							}
							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);
				}
				out.flush();
				excelWriter.finish();
			} catch (Exception e) {
				log.error("员工合同导出异常：", e);
			} finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					log.error("员工合同导出异常：", e);
				}
			}
		}
	}

	/**
	 * 导出历史合并
	 */
	@Override
	public void exportContractInfoHistory(TEmployeeContractInfo contractInfo, HttpServletResponse response) {
		if (contractInfo != null && contractInfo.getExportFields() != null && !contractInfo.getExportFields().isEmpty()) {
			String fileName = "员工合同批量导出【合并历史】" + DateUtil.getThisTime() + CommonConstants.XLSX;
			//获取要导出的列表
			List<EmployeeContractExportVO> list = new ArrayList<>();
			ServletOutputStream out = null;
			Integer count = baseMapper.selectCountHistoryContractExport(contractInfo);
			try {
				ExcelUtil<EmployeeContractExportVO> util = new ExcelUtil<>(EmployeeContractExportVO.class);
				out = response.getOutputStream();
				response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
				response.setCharacterEncoding(CommonConstants.UTF8);
				response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
				// 获取所有字典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, EmployeeContractExportVO.class)
						.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
						.includeColumnFieldNames(contractInfo.getExportFields()).build();
				int index = 0;
				if (count > CommonConstants.ZERO_INT) {
					WriteSheet writeSheet;
					for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
						// 获取实际记录
						contractInfo.setLimitStart(i);
						contractInfo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
						list = baseMapper.getTEmployeeContractExportHistory(contractInfo);
						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);
				}
				out.flush();
				excelWriter.finish();
			} catch (Exception e) {
				log.error(EmployeeConstants.CONCART_ALL_EXPORT_EXCEPTION, e);
			} finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					log.error(EmployeeConstants.CONCART_ALL_EXPORT_EXCEPTION, e);
				}
			}

		}
	}

	@Override
	public void exportAuditContractInfo(TEmployeeContractSearchVo searchVo, HttpServletResponse response) {
		String fileName = "合同审核批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<EmployeeContractExportAuditVO> list = new ArrayList<>();
		//获取要导出的列表
		searchVo.setAuditStatus(CommonConstants.ONE_INT);
		searchVo.setIdList(Common.getList(searchVo.getIds()));
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			//EasyExcel.write(out, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
			ExcelWriter excelWriter = EasyExcel.write(out, EmployeeContractExportAuditVO.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				Field[] allFields = EmployeeContractExportAuditVO.class.getDeclaredFields();
				WriteSheet writeSheet;
				ExcelUtil<EmployeeContractExportAuditVO> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(EmployeeContractExportAuditVO.class);
						for (EmployeeContractExportAuditVO vo : list) {
							util.convertEntityAsso(vo, null, null, null, allFields);
						}
					}
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcel.writerSheet("合同审核批量导出" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("合同审核批量导出" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	private List<EmployeeContractExportAuditVO> noPageDiy(TEmployeeContractSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo);
	}

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

	// 审核或办理，更新离职待办
	// isSuccess 0：失败；1：成功
	private void sendLeave(String id, String doStatus, String isSuccess, String failRemark, YifuUser user) {
		BaseServiceParamListVO updateVo = new BaseServiceParamListVO();
		List<String> idList = new ArrayList<>();
		idList.add(id);
		updateVo.setListParam(idList);
		updateVo.setDoType(CommonConstants.FOUR_STRING);
		updateVo.setDoStatus(doStatus);
		updateVo.setIsSuccess(isSuccess);
		if (Common.isNotNull(isSuccess) && CommonConstants.ZERO_STRING.equals(isSuccess)) {
			updateVo.setRemark(failRemark);
			if (user != null && Common.isNotNull(user.getNickname())) {
				updateVo.setUserName(user.getNickname());
			}
		}
		cspDaprUtil.reduceHandleToLeave(updateVo);
	}

	/**
	 * @Author fxj
	 * @Description 批量审核合同
	 * @Date 16:45 2022/12/12
	 **/
	@Override
	public R<List<ErrorMessage>> auditContractBatch(EmpContractAuditVo contractAuditVo, YifuUser user) {
		List<TEmployeeContractInfo> contractInfos = baseMapper.selectBatchIds(contractAuditVo.getIds());
		if (Common.isEmpty(contractInfos)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}

		List<ErrorMessage> errorMessages = new ArrayList<>();
		TEmployeeContractInfo tEmployeeContractInfo;
		TEmployeeContractInfo contractInfoInUse;
		TEmployeeProject tEmployeeProject;
		TEmployeeInfo tEmployeeInfo;
		int i = 1;
		int errorCount = 0;

		List<TEmployeeContractInfo> contractInfoList;
		List<TEmployeeContractInfo> contractInfoListZt;
		TWorkHandlerInfo handlerInfo;

		// 渲染字典值
		Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
				CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "personnel_type");

		String auditRemark = contractAuditVo.getAuditRemark();
		for (TEmployeeContractInfo contract : contractInfos) {
			i++;
			if (contract.getAuditStatus() != CommonConstants.ONE_INT) {
				errorMessages.add(new ErrorMessage(i, "不是待审核状态！", CommonConstants.RED, contract.getApplyNo()));
				errorCount++;
				continue;
			}
			tEmployeeContractInfo = new TEmployeeContractInfo();
			tEmployeeContractInfo.setAuditRemark(contractAuditVo.getAuditRemark());
			tEmployeeContractInfo.setAuditStatus(contractAuditVo.getAuditStatus());
			tEmployeeContractInfo.setContractNo(contract.getContractNo());
			tEmployeeContractInfo.setAuditUserName(user.getNickname());
			tEmployeeContractInfo.setId(contract.getId());

			if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.dingleDigitIntArray[2]) {
				// 非作废、终止，本条变为在用
				if (Common.isEmpty(contract.getSituation())
						|| (!EmployeeConstants.SITUATION_SIX.equals(contract.getSituation())
						&& !EmployeeConstants.SITUATION_SEVEN.equals(contract.getSituation()))) {
					// 其他变为不在用
					baseMapper.updateInUseStatusById(contract.getEmpId(), contract.getDeptNo(), contract.getId(), CommonConstants.ONE_STRING);
					tEmployeeContractInfo.setAuditTimeLast(LocalDateTime.now());
					tEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);
					// 更新档案、项目合同状态为（1可用）
					String tempStr = null;
					for (Map.Entry<String,String> entry:dicObj.entrySet()){
						if (Common.isNotNull(entry.getValue()) && entry.getValue().equals(contract.getContractName())){
							tempStr = entry.getKey();
							break;
						}
					}
					tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
							.lambda().eq(TEmployeeProject::getEmpId, contract.getEmpId())
							.eq(TEmployeeProject::getDeptId, contract.getSettleDomain())
							.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
							.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
							.last(CommonConstants.LAST_ONE_SQL));
					if (tEmployeeProject != null) {
						tEmployeeProject.setContractStatus(CommonConstants.ONE_INT);
						//签订类型正常签订的时候更新项目档案信息
						if (EmployeeConstants.SITUATION_ONE.equals(contract.getSituation())) {
							tEmployeeProject.setContractType(null == tempStr? "":tempStr);
							tEmployeeProject.setWorkingHours(contract.getWorkingHours());
							tEmployeeProject.setPost(contract.getPost());
							tEmployeeProject.setEnjoinDate(contract.getContractStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
							tEmployeeProject.setTryPeriod(contract.getTryPeriod());
						}
						tEmployeeProjectService.updateById(tEmployeeProject);
					}
					// 更新档案、项目合同状态为（1在用）
					tEmployeeInfo = tEmployeeInfoMapper.selectById(contract.getEmpId());
					if (tEmployeeInfo != null) {
						tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
						tEmployeeInfoMapper.updateById(tEmployeeInfo);
					}
					//签订类型正常签订的时候更新预入职列表
					if (EmployeeConstants.SITUATION_ONE.equals(contract.getSituation())) {
						//根据项目编码和身份证号查询预入职列表
						TPreEmpMain empMain = preEmpMainMapper.selectOne(Wrappers.<TPreEmpMain>query()
								.lambda().eq(TPreEmpMain::getEmpIdcard, contract.getEmpIdcard())
								.eq(TPreEmpMain::getDeptNo, contract.getDeptNo())
								.ne(TPreEmpMain::getStatus, CommonConstants.FIVE_STRING)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Optional.ofNullable(empMain).isPresent()) {
							//查询预入职项目档案表
							TPreEmployeeProject preEmployeeProject = preEmployeeProjectMapper.selectOne(Wrappers.<TPreEmployeeProject>query()
									.lambda().eq(TPreEmployeeProject::getPreMainId, empMain.getId()));
							if (Optional.ofNullable(preEmployeeProject).isPresent()) {
								preEmployeeProject.setContractType(null == tempStr? "":tempStr);
								preEmployeeProject.setWorkingHours(contract.getWorkingHours());
								preEmployeeProject.setPost(contract.getPost());
								preEmployeeProject.setEnjoinDate(contract.getContractStart());
								preEmployeeProject.setTryPeriod(contract.getTryPeriod());
								preEmployeeProjectMapper.updateById(preEmployeeProject);
							}
						}
					}

				} else {
					//是否同步终止合同、减项、减档为是的时候 单独写逻辑
					if (EmployeeConstants.SITUATION_SEVEN.equals(contract.getSituation())
							&& CommonConstants.ZERO_STRING.equals(contract.getChangeContractAndEmployee())) {
						//同步任务处理清单执行详情
						StringBuilder workInfo = new StringBuilder();
						StringBuilder failueInfo = new StringBuilder();
						workInfo.append("合同终止成功,");
						//该项目下其他在用的合同统一更新成不在用
						doOtherContract(contract, user);
						//在途的合同更新为审核不通过
						contractInfoListZt = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
								.lambda().eq(TEmployeeContractInfo::getEmpId, contract.getEmpId())
								.eq(TEmployeeContractInfo::getSettleDomain, contract.getSettleDomain())
								.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
										.or().eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ZERO_INT))
								.ne(TEmployeeContractInfo::getId, contract.getId())
								.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT));
						if (Common.isNotNull(contractInfoListZt)) {
							for (TEmployeeContractInfo contractInfo1 : contractInfoListZt) {
								contractInfo1.setAuditStatus(CommonConstants.THREE_INT);
								contractInfo1.setAuditUserName(user.getNickname());
								baseMapper.updateById(contractInfo1);
								//增加审核记录
								this.setAuditInfoNew(contractInfo1);
							}
						}
						//项目档案处理
						tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
								.lambda().eq(TEmployeeProject::getEmpId, contract.getEmpId())
								.eq(TEmployeeProject::getDeptId, contract.getSettleDomain())
								.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
								.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
								.last(CommonConstants.LAST_ONE_SQL));
						if (null != tEmployeeProject) {
							TEmployeeProject tEmployeeProjectOld = tEmployeeProjectService.getById(tEmployeeProject.getId());
							tEmployeeProject.setContractStatus(CommonConstants.TWO_INT);
							//如果该项目仍有社保、公积金的数据不同步减项，如正常减项，记录项目档案操作记录
							if ((tEmployeeProject.getSocialStatus() == CommonConstants.ZERO_INT
									|| tEmployeeProject.getSocialStatus() == CommonConstants.FOUR_INT) &&
									( tEmployeeProject.getFundStatus() == CommonConstants.ZERO_INT
									|| tEmployeeProject.getFundStatus() == CommonConstants.THREE_INT)) {
								tEmployeeProject.setProjectStatus(CommonConstants.ONE_INT);
								tEmployeeProject.setLeaveRemark("终止合同联动减项");
								tEmployeeProject.setLeaveTime(LocalDateTime.now());
								tEmployeeProject.setLeaveUser(user.getNickname());

								// 减-同步处理CSP入离职申请为已处理，加日志
								tEmployeeProjectService.doSaveBelongDept(tEmployeeProject, CommonConstants.TWO_STRING);

								workInfo.append("减项成功,");
							} else {
								failueInfo.append("存在社保/公积金，无法减项");
							}
							tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
									tEmployeeProject.getId(), tEmployeeProjectOld, tEmployeeProject);
							tEmployeeProjectService.updateById(tEmployeeProject);
							//如果项目档案已减项，如果人员存在多个项目不处理，反之则减档
							tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
							if (Common.isNotNull(tEmployeeInfo)) {
								TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());
								// 判断人员有无审核通过的其他合同
								contractInfoInUse = this.getOne(Wrappers.<TEmployeeContractInfo>query()
										.lambda().eq(TEmployeeContractInfo::getEmpId, contract.getEmpId())
										.and(obj -> obj.ge(TEmployeeContractInfo::getContractEnd, DateUtil.getThisDayByPatten("yyyy-MM-dd"))
												.or().isNull(TEmployeeContractInfo::getContractEnd))
										.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
										.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
										.last(CommonConstants.LAST_ONE_SQL));
								if (contractInfoInUse != null) {
									tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
								} else {
									tEmployeeInfo.setContractStatus(CommonConstants.TWO_INT);
								}
								if (tEmployeeProject.getProjectStatus() == CommonConstants.ONE_INT) {
									tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() - CommonConstants.ONE_INT);
									//减项成功把人员档案现存项目数减一
									if (tEmployeeInfo.getProjectNum() == CommonConstants.ZERO_INT) {
										//减档
										tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[1]);
										tEmployeeInfo.setLeaveRemark("社保派减联动减档");
										tEmployeeInfo.setLeaveTime(DateUtil.getCurrentDateTime());
										tEmployeeInfo.setLeaveUser(user.getId());
										tEmployeeInfo.setLeaveUserName(user.getNickname());
										workInfo.append("减档成功,");
									} else {
										failueInfo.append("存在其他项目，无法减档");
									}
								}
								tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], tEmployeeInfo.getId(),
										"", tEmployeeInfoOld, tEmployeeInfo);
								tEmployeeInfoMapper.updateById(tEmployeeInfo);
							}
						}
						//更新任务处理情况数据
						handlerInfo = workHandlerInfoService.getOne(Wrappers.<TWorkHandlerInfo>query()
								.lambda().eq(TWorkHandlerInfo::getDetailId, contract.getId())
								.last(CommonConstants.LAST_ONE_SQL));
						if (Common.isNotNull(handlerInfo)) {
							handlerInfo.setOperInfo(workInfo.substring(0, workInfo.length() - 1));
							handlerInfo.setReason(failueInfo.length() > 1 ? failueInfo.toString() : "");
							handlerInfo.setOperResult(failueInfo.length() > 1 ? "1" : "2");
							workHandlerInfoService.updateById(handlerInfo);
						}
					} else{
						//先停用项目内的其他的员工合同————不要这个逻辑了
						// 2022-7-22 16:54:12 产品倩倩与测试说，作废终止审核通过，仅将原先选择的合同不在用即可
						if (Common.isNotNull(contract.getOldContractId())) {
							TEmployeeContractInfo old = this.getById(contract.getOldContractId());
							if (old != null && Common.isNotNull(old.getId())) {
								if (!CommonConstants.ZERO_STRING.equals(old.getInUse())) {
									errorMessages.add(new ErrorMessage(i, "关联的原合同已不在用！", CommonConstants.RED, contract.getApplyNo()));
									errorCount++;
									continue;
								} else {
									old.setInUse(CommonConstants.ONE_STRING);
									this.updateById(old);
								}
							} else {
								errorMessages.add(new ErrorMessage(i, "未找到关联的原合同！", CommonConstants.RED, contract.getApplyNo()));
								errorCount++;
								continue;
							}
						} else {
							errorMessages.add(new ErrorMessage(i, "未找到关联的原合同！", CommonConstants.RED, contract.getApplyNo()));
							errorCount++;
							continue;
						}

						//该项目下其他在用的合同统一更新成不在用
						doZhongZhiContract(contract, user);

						// 作废、终止审核通过：
						// 更新项目合同状态为（2不在用），档案状态要判断
						tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
								.lambda().eq(TEmployeeProject::getEmpId, contract.getEmpId())
								.eq(TEmployeeProject::getDeptId, contract.getSettleDomain())
								.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
								.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
								.last(CommonConstants.LAST_ONE_SQL));
						if (tEmployeeProject != null) {
							tEmployeeProject.setContractStatus(CommonConstants.TWO_INT);
							tEmployeeProjectService.updateById(tEmployeeProject);
						}

						// 更新档案、项目合同状态为（0无合同 1在用 2不在用）
						tEmployeeInfo = tEmployeeInfoMapper.selectById(contract.getEmpId());
						if (tEmployeeInfo != null) {
							// 判断人员有无审核通过的其他合同
							contractInfoInUse = this.getOne(Wrappers.<TEmployeeContractInfo>query()
									.lambda().eq(TEmployeeContractInfo::getEmpId, contract.getEmpId())
									.and(obj -> obj.ge(TEmployeeContractInfo::getContractEnd, DateUtil.getThisDayByPatten("yyyy-MM-dd"))
											.or().isNull(TEmployeeContractInfo::getContractEnd))
									.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
									.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
									.last(CommonConstants.LAST_ONE_SQL));
							if (contractInfoInUse != null) {
								tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
							} else {
								tEmployeeInfo.setContractStatus(CommonConstants.TWO_INT);
							}
							tEmployeeInfoMapper.updateById(tEmployeeInfo);
						}
					}
				}
				//更新合同状态为4线下签待归档
				TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
						.eq(TEmployeeContractPre::getContractId, contract.getId())
						.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPre)) {
					contractPre.setProcessStatus(CommonConstants.FOUR_STRING);
					contractPreMapper.updateById(contractPre);
				}
				//续签待办：更新续签状态为4线下签待归档
				TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
						.eq(TEmployeeContractPreNew::getId, contract.getPreNewId())
						.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.TWO_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPreNew)) {
					contractPreNew.setProcessStatus(CommonConstants.FOUR_STRING);
					contractPreNewMapper.updateById(contractPreNew);
				}
				//瓜子项目编码：皖A694302
				if (CommonConstants.GZ_DEPT_NO.equals(contract.getDeptNo())) {
					//审核通过瓜子合同状态更新成合同审核通过
					updateGzOfferStatus(contract,CommonConstants.THIRTEEN_STRING,CommonConstants.EIGHT_STRING,user.getId(),user.getNickname());
				}

				if (EmployeeConstants.SITUATION_SEVEN.equals(contract.getSituation())) {
					this.sendLeave(contract.getId(), CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, auditRemark, user);
				}
			}
			if (tEmployeeContractInfo.getAuditStatus() == CommonConstants.dingleDigitIntArray[3]) {
				//更新合同状态为3线下签审核不通过
				TEmployeeContractPre contractPre = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
						.eq(TEmployeeContractPre::getContractId, contract.getId())
						.eq(TEmployeeContractPre::getProcessStatus, CommonConstants.TWO_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPre)) {
					contractPre.setProcessStatus(CommonConstants.THREE_STRING);
					contractPreMapper.updateById(contractPre);
				}
				if (EmployeeConstants.SITUATION_SEVEN.equals(contract.getSituation())) {
					this.sendLeave(contract.getId(), CommonConstants.TEN_STRING, CommonConstants.ZERO_STRING, auditRemark, user);
				}
				//续签待办：更新合同状态为3线下签审核不通过，合同续签提醒更新为待处理
				TEmployeeContractPreNew contractPreNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
						.eq(TEmployeeContractPreNew::getId, contract.getPreNewId())
						.eq(TEmployeeContractPreNew::getProcessStatus, CommonConstants.TWO_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractPreNew)) {
					contractPreNew.setProcessStatus(CommonConstants.THREE_STRING);
					contractPreNew.setErrorInfo(tEmployeeContractInfo.getAuditRemark());
					contractPreNew.setErrorTime(new Date());
					contractPreNewMapper.updateById(contractPreNew);
					//更新合同提醒办理状态为待处理
					LambdaUpdateWrapper<TEmpContractAlert> updateWrapper = new LambdaUpdateWrapper<>();
					updateWrapper.eq(TEmpContractAlert::getContractId, contractPreNew.getContractId())
							.set(TEmpContractAlert::getHandleStatus, CommonConstants.ZERO_INT);
					contractAlertMapper.update(null, updateWrapper);
				}
			}
			// 不是待提交，记录审核记录
			this.setAuditInfo(tEmployeeContractInfo);
			this.updateById(tEmployeeContractInfo);
			errorMessages.add(new ErrorMessage(i, "审核成功！", CommonConstants.GREEN, contract.getApplyNo()));
		}
		if (errorCount == CommonConstants.ZERO_INT) {
			return R.ok();
		}
		return R.ok(errorMessages);
	}

	/**
	 * B端合同列表查询接口
	 *
	 * @param page
	 * @param contractBusinessPageVo
	 * @param flag                   0 按3个月内到期提醒  1 不安提醒查询
	 * @return
	 * @Author fxj
	 * @Date 2020-08-25
	 **/
	@Override
	public IPage<EmpContractBusinessPageVo> getContractBusinessPage(Page<EmpContractBusinessPageVo> page, EmpContractBusinessPageVo contractBusinessPageVo, List<String> settleDomainIds, Integer flag) {
		IPage<EmpContractBusinessPageVo> pageVoList = baseMapper.getContractBusinessPage(page, contractBusinessPageVo, settleDomainIds, flag);
		List<EmpContractBusinessPageVo> voList = pageVoList.getRecords();
		List<TEmployeeContractInfo> contractInfoList = null;
		List<String> empIds = new ArrayList<>();
		if (Common.isNotNull(voList)) {
			for (EmpContractBusinessPageVo vo : voList) {
				empIds.add(vo.getEmpId());
			}
		}
		if (Common.isNotNull(empIds)) {
			contractInfoList = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
					.eq(TEmployeeContractInfo::getIsObsolete, CommonConstants.ZERO_STRING)
					.in(TEmployeeContractInfo::getEmpId, empIds));
		}
		HashMap<String, Integer> countMap = new HashMap<>();
		if (Common.isNotNull(contractInfoList)) {
			Integer count;
			for (TEmployeeContractInfo contractInfo : contractInfoList) {
				count = countMap.get(contractInfo.getEmpId());
				count = null == count ? 1 : (count + 1);
				countMap.put(contractInfo.getEmpId(), count);
			}
		}
		if (Common.isNotNull(voList)) {
			for (EmpContractBusinessPageVo pageVo : voList) {
				pageVo.setRenewCount(countMap.get(pageVo.getEmpId()));
			}
		}
		pageVoList.setRecords(voList);
		return pageVoList;
	}

	/**
	 * B端查询合同到期提醒数（查询3个月内到期的合同）
	 *
	 * @param
	 * @return
	 * @Author fxj
	 * @Date 2020-08-25
	 **/
	@Override
	public Integer getContractBusinessAlertCount(List<String> settleDomainIds) {
		EmpContractBusinessPageVo contractBusinessPageVo = new EmpContractBusinessPageVo();
		contractBusinessPageVo.setInUse(CommonConstants.ZERO_STRING);
		contractBusinessPageVo.setIsObsolete(CommonConstants.ZERO_STRING);
		return baseMapper.getContractBusinessAlertCount(contractBusinessPageVo, settleDomainIds, CommonConstants.THREE_INT);
	}

	/**
	 * B端查询对应员工指定合同ID之外的其他合同信息
	 *
	 * @param empId
	 * @param contractId
	 * @return
	 * @Author fxj
	 * @Date 2020-08-25
	 **/
	@Override
	public List<EmpContractBusinessPageVo> getOtherContractBusinessInfo(String empId, String contractId) {
		return baseMapper.getOtherContractBusinessInfo(empId, contractId);
	}

	@Override
	public R<String> getContractByEmpIdCardAndDeptId(String empIdCard, String deptId) {
		String contractStart = baseMapper.getContractByEmpIdCardAndDeptId(empIdCard, deptId);
		if (Common.isNotNull(contractStart)) {
			return R.ok(contractStart);
		} else {
			return R.failed("未找到合同");
		}
	}

	@Override
	public String getContractByEmpIdCardAndDeptNo(String empIdCard, String deptNo) {
		return baseMapper.getContractByEmpIdCardAndDeptNo(empIdCard, deptNo);
	}
	@Override
	public String getContractByEmpIdCardAndDeptNoByEnd(String empIdCard, String deptNo) {
		return baseMapper.getContractByEmpIdCardAndDeptNoByEnd(empIdCard, deptNo);
	}

	@Override
	public String getMinDateByCardAndDeptId(IdNameNoVo vo) {
		return baseMapper.getMinDateByCardAndDeptId(vo);
	}

	@Override
	public Boolean selectExitEmpCopntract(TEmployeeAutoRegistCheckVo cardVo) {
		if (Common.isNotNull(cardVo) && Common.isNotNull(cardVo.getEmpIdcard()) && Common.isNotNull(cardVo.getDeptNo())) {
			return baseMapper.selectCount(Wrappers.<TEmployeeContractInfo>query().lambda()
					.eq(TEmployeeContractInfo::getEmpIdcard, cardVo.getEmpIdcard())
					.eq(TEmployeeContractInfo::getDeptNo, cardVo.getDeptNo())
					.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
							.or()
							.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
					)
					.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL)) > 0;
		} else {
			return false;
		}
	}

	@Override
	public R selectExitEmpCopntractNew(TEmployeeAutoRegistCheckVo cardVo) {
		if (Common.isNotNull(cardVo) && Common.isNotNull(cardVo.getEmpIdcard()) && Common.isNotNull(cardVo.getDeptNo())) {
			return R.ok(baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
					.eq(TEmployeeContractInfo::getEmpIdcard, cardVo.getEmpIdcard())
					.eq(TEmployeeContractInfo::getDeptNo, cardVo.getDeptNo())
					.isNull(TEmployeeContractInfo::getSignType)
					.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
							.or()
							.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
					)
					.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)));
		} else {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
	}

	//是否同步终止合同、减项、减档为是的时候 单独写逻辑
	public void changeStatus(TEmployeeContractInfo contractInfo,YifuUser user) {
		//同步任务处理清单执行详情
		StringBuilder workInfo = new StringBuilder();
		StringBuilder failueInfo = new StringBuilder();
		workInfo.append("合同终止成功,");
		//该项目下其他在用的合同统一更新成不在用
		doOtherContract(contractInfo, user);
		//在途的合同更新为审核不通过
		List<TEmployeeContractInfo> contractInfoListZt = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getEmpId, contractInfo.getEmpId())
				.eq(TEmployeeContractInfo::getSettleDomain, contractInfo.getSettleDomain())
				.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
						.or().eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ZERO_INT))
				.ne(TEmployeeContractInfo::getId, contractInfo.getId())
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT));
		if (Common.isNotNull(contractInfoListZt)) {
			for (TEmployeeContractInfo contractInfo1 : contractInfoListZt) {
				contractInfo1.setAuditStatus(CommonConstants.THREE_INT);
				contractInfo1.setAuditUserName(user.getNickname());
				baseMapper.updateById(contractInfo1);
				//增加审核记录
				this.setAuditInfoNew(contractInfo1);
			}
		}
		//项目档案处理
		TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query()
				.lambda().eq(TEmployeeProject::getEmpId, contractInfo.getEmpId())
				.eq(TEmployeeProject::getDeptId, contractInfo.getSettleDomain())
				.eq(TEmployeeProject::getProjectStatus, CommonConstants.ZERO_INT)
				.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL)
				.last(CommonConstants.LAST_ONE_SQL));
		if (tEmployeeProject != null) {
			TEmployeeProject tEmployeeProjectOld = tEmployeeProjectService.getById(tEmployeeProject.getId());
			tEmployeeProject.setContractStatus(CommonConstants.TWO_INT);
			//如果该项目仍有社保、公积金的数据不同步减项，如正常减项，记录项目档案操作记录
			if ((tEmployeeProject.getSocialStatus() == CommonConstants.ZERO_INT
					|| tEmployeeProject.getSocialStatus() == CommonConstants.FOUR_INT)
					&& (tEmployeeProject.getFundStatus() == CommonConstants.ZERO_INT
					|| tEmployeeProject.getFundStatus() == CommonConstants.THREE_INT)) {
				tEmployeeProject.setProjectStatus(CommonConstants.ONE_INT);
				tEmployeeProject.setLeaveRemark("终止合同联动减项");
				tEmployeeProject.setLeaveTime(LocalDateTime.now());
				workInfo.append("减项成功,");
			} else {
				failueInfo.append("存在社保/公积金，无法减项");
			}
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "",
					tEmployeeProject.getId(), tEmployeeProjectOld, tEmployeeProject);
			tEmployeeProjectService.updateById(tEmployeeProject);
			//如果项目档案已减项，如果人员存在多个项目不处理，反之则减档
			TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
			if (Common.isNotNull(tEmployeeInfo)) {
				TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
				// 判断人员有无审核通过的其他合同
				TEmployeeContractInfo contractInfoInUse = this.getOne(Wrappers.<TEmployeeContractInfo>query()
						.lambda().eq(TEmployeeContractInfo::getEmpId, contractInfo.getEmpId())
						.and(obj -> obj.ge(TEmployeeContractInfo::getContractEnd, DateUtil.getThisDayByPatten("yyyy-MM-dd"))
								.or().isNull(TEmployeeContractInfo::getContractEnd))
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_INT)
						.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL));
				if (contractInfoInUse != null) {
					tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
				} else {
					tEmployeeInfo.setContractStatus(CommonConstants.TWO_INT);
				}
				if (tEmployeeProject.getProjectStatus() == CommonConstants.ONE_INT) {
					tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() - CommonConstants.ONE_INT);
					//减项成功把人员档案现存项目数减一
					if (tEmployeeInfo.getProjectNum() == CommonConstants.ZERO_INT) {
						//减档
						tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[1]);
						tEmployeeInfo.setLeaveRemark(tEmployeeProject.getLeaveRemark());
						tEmployeeInfo.setLeaveTime(DateUtil.getCurrentDateTime());
						tEmployeeInfo.setLeaveUser(user.getId());
						tEmployeeInfo.setLeaveUserName(user.getNickname());
						workInfo.append("减档成功,");
					} else {
						failueInfo.append("存在其他项目，无法减档");
					}
				}
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0], tEmployeeInfo.getId(),
						"", tEmployeeInfoOld, tEmployeeInfo);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
			}
		}
		//更新任务处理情况数据
		TWorkHandlerInfo handlerInfo1 = workHandlerInfoService.getOne(Wrappers.<TWorkHandlerInfo>query()
				.lambda().eq(TWorkHandlerInfo::getDetailId, contractInfo.getId())
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(handlerInfo1)) {
			handlerInfo1.setOperInfo(workInfo.substring(0, workInfo.length() - 1));
			handlerInfo1.setReason(failueInfo.length() > 1 ? failueInfo.toString() : "");
			handlerInfo1.setOperResult(failueInfo.length() > 1 ? "1" : "2");
			workHandlerInfoService.updateById(handlerInfo1);
		} else {
			TWorkHandlerInfo handlerInfo = new TWorkHandlerInfo();
			handlerInfo.setEmpIdcard(contractInfo.getEmpIdcard());
			handlerInfo.setEmpName(contractInfo.getEmpName());
			handlerInfo.setDepartName(contractInfo.getSubjectDepart());
			handlerInfo.setDepartNo(contractInfo.getDeptNo());
			handlerInfo.setInfoFrom("合同终止");
			handlerInfo.setOperUser(user.getNickname());
			handlerInfo.setOperTime(LocalDateTime.now());
			handlerInfo.setDetailId(contractInfo.getId());
			handlerInfo.setOperInfo(workInfo.substring(0, workInfo.length() - 1));
			handlerInfo.setReason(failueInfo.length() > 1 ? failueInfo.toString() : "");
			handlerInfo.setOperResult(failueInfo.length() > 1 ? "1" : "2");
			workHandlerInfoService.save(handlerInfo);
		}
	}

	// 同步处理其他合同
	private void doOtherContract(TEmployeeContractInfo contract, YifuUser user) {
		List<TEmployeeContractInfo> contractInfoList = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getEmpId, contract.getEmpId())
				.eq(TEmployeeContractInfo::getSettleDomain, contract.getSettleDomain())
				.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
				.ne(TEmployeeContractInfo::getId, contract.getId()));
		if (Common.isNotNull(contractInfoList)) {
			for (TEmployeeContractInfo contractInfo1 : contractInfoList) {
				contractInfo1.setInUse(CommonConstants.ONE_STRING);
				contractInfo1.setAuditUserName(user.getNickname());
				baseMapper.updateById(contractInfo1);
				//增加审核记录
				this.setAuditInfoNew(contractInfo1);
			}
		}
	}

	// 同步处理终止合同（2026-01-29 倩倩：作废、终止的合同审核通过后，将待审核的终止的合同处理为审核不通过，以使得 自动化离职的合同 变为无需处理。未处理作废的合同，后续有需要再追加）
	private void doZhongZhiContract(TEmployeeContractInfo contractInfo, YifuUser user) {
		// 1将待审核的变为审核不通过且不在用
		List<TEmployeeContractInfo> contractInfoList = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getEmpIdcard, contractInfo.getEmpIdcard())
				.eq(TEmployeeContractInfo::getSettleDomain, contractInfo.getSettleDomain())
				.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_STRING)
				.eq(TEmployeeContractInfo::getSituation, EmployeeConstants.SITUATION_SEVEN)
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
				.ne(TEmployeeContractInfo::getId, contractInfo.getId()));
		if (Common.isNotNull(contractInfoList)) {
			for (TEmployeeContractInfo contractInfo1 : contractInfoList) {
				contractInfo1.setInUse(CommonConstants.ONE_STRING);
				contractInfo1.setAuditStatus(CommonConstants.THREE_INT);
				contractInfo1.setAuditUserName(user.getNickname());
				baseMapper.updateById(contractInfo1);
				//增加审核记录
				this.setAuditInfoNew(contractInfo1);
				//this.sendLeave(contractInfo1.getId(), CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, "终止合同联动", user);
			}
		}
	}

	//更新瓜子offer状态
	@Override
	public void updateGzOfferStatus(TEmployeeContractInfo contractInfo,String preStatus,String updStatus, String userId, String nickname) {
		if(Common.isEmpty(contractInfo)){
			return;
		}
		TGzOfferInfo gzOfferInfo = gzOfferInfoMapper.selectOne(Wrappers.<TGzOfferInfo>query()
				.lambda().eq(TGzOfferInfo::getNationalId, contractInfo.getEmpIdcard())
				.eq(TGzOfferInfo::getOfferStatus, preStatus)
				.eq(TGzOfferInfo::getDelFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(gzOfferInfo)) {
			// updStatus == 13：待签署 更新 入职日期为合同开始时间
			if(CommonConstants.THIRTEEN_STRING.equals(updStatus)){
				gzOfferInfo.setExpEntryDate(contractInfo.getContractStart());
			}
			gzOfferInfo.setOfferStatus(updStatus);
			gzOfferInfo.setUpdateBy(userId);
			gzOfferInfo.setUpdateTime(LocalDateTime.now());
			gzOfferInfoMapper.updateById(gzOfferInfo);

			// updStatus == 8：合同审核通过 生成瓜子档案里的合同信息
			if(CommonConstants.EIGHT_STRING.equals(updStatus)){
				tGzContractService.saveContractInfoToGzEmpInfo(contractInfo, gzOfferInfo.getId(), gzOfferInfo.getWorkLocation(),gzOfferInfo.getWorkLocationDescr());
			}

			// 1.7.13: updStatus == 99：存合同附件到瓜子档案里
			if(CommonConstants.NINETY_NINE.equals(updStatus)){
				// 查档案ID
				TGzEmpInfo gzEmpInfo = tGzEmpInfoMapper.getInfoByOfferId(gzOfferInfo.getId());
				if(Common.isNotNull(gzEmpInfo)){
					// 获取合同归档附件
					List<TAttaInfo> contractAttas = tAttaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId,contractInfo.getId()));
					if (Common.isNotNull(contractAttas)) {
						for (TAttaInfo attaInfo : contractAttas) {
							// 附件赋值
							TAttaInfo gzContractAtta = new TAttaInfo();
							BeanUtils.copyProperties(attaInfo, gzContractAtta);
							gzContractAtta.setDomainId(gzEmpInfo.getId());
							gzContractAtta.setRelationType("CONTRACT");
							gzContractAtta.setId(null);
							gzContractAtta.setCreateBy(userId);
							gzContractAtta.setCreateName(nickname);
							gzContractAtta.setCreateTime(LocalDateTime.now());
							tAttaInfoService.save(gzContractAtta);
						}
					}
				}

			}

			// 瓜子状态变更增加操作日志
			// 13：待签署，8：合同审核通过，99：已归档
			// 9：发起合同申请10：合同审核通过；11：合同归档；
			String recordFrom = "";

			switch (updStatus) {
				case "13":
					recordFrom = "9";
					break;
				case "8":
					recordFrom = "10";
					break;
				default:
					recordFrom = "11";
					break;
			}

			// 1.7.13： 推送瓜子
			TGzPushEntry tGzPushEntry = new TGzPushEntry();
			tGzPushEntry.setCreateBy(userId);
			tGzPushEntry.setCreateName(nickname);
			tGzPushEntry.setBizId(gzOfferInfo.getBizId());
			tGzPushEntry.setTaskType(updStatus);
			tGzPushEntry.setName(gzOfferInfo.getName());
			tGzPushEntry.setNationalId(gzOfferInfo.getNationalId());
			tGzPushEntryService.addPushEntry(tGzPushEntry);

			LGuaziOfferRecordVo lGuaziOfferRecordVo = new LGuaziOfferRecordVo();
			// 存变更前后的状态到 状态数组里
			List<String> changeStatusList = new ArrayList<>();
			changeStatusList.add(preStatus);
			changeStatusList.add(updStatus);

			if(changeStatusList.size() > 0){
				lGuaziOfferRecordVo.setOfferId(gzOfferInfo.getId());
				// 记录来源
				lGuaziOfferRecordVo.setRecordFrom(recordFrom);
				lGuaziOfferRecordVo.setChangeStatusList(changeStatusList);
				lGuaziOfferRecordVo.setCreateBy(userId);
				lGuaziOfferRecordVo.setCreateName(nickname);
				lGuaziOfferRecordService.saveRecordOne(lGuaziOfferRecordVo, null);
			}

		}
	}

	private YifuUser getNewYifuUser(String leaveName) {
		if (Common.isEmpty(leaveName)) {
			leaveName = "自动化派单";
		}
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new YifuUser("6", 1L, "", leaveName,
				leaveName, "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null,null);
	}

}
