/*
 *    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.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.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.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.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSocialProperties;
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.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.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.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工合同
 *
 * @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 TCustomerInfoService tCustomerInfoService;
	private final TAttaInfoService tAttaInfoService;
	private final TEmployeeContractAuditService tEmployeeContractAuditService;
	private final TEmployeeLogService tEmployeeLogService;
	private final TWorkHandlerInfoService workHandlerInfoService;
	@Autowired
	private DaprSocialProperties socialProperties;
	// 缓存信息
	private final CacheManager cacheManager;

	/**
	 * 员工合同信息表简单分页查询
	 *
	 * @param tEmployeeContractInfo 员工合同信息表
	 * @return
	 */
	@Override
	public IPage<TEmployeeContractInfo> getTEmployeeContractInfoPage(Page<TEmployeeContractInfo> page, TEmployeeContractInfo tEmployeeContractInfo) {
		return baseMapper.getTEmployeeContractInfoPage(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())) {
			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());
				}
				if (null != settleDomain.getCustomerId() && Common.isEmpty(tEmployeeContractInfo.getSubjectUnit())) {
					TCustomerInfo customerInfo = tCustomerInfoService.getById(settleDomain.getCustomerId());
					if (null != customerInfo) {
						tEmployeeContractInfo.setSubjectUnit(customerInfo.getCustomerName());
						tEmployeeContractInfo.setUnitNo(customerInfo.getCustomerCode());
					}
				}
			}
		}
		//初始化审核类型  审核类型:0派增-社保派单、1派增-无社保新签、2派增-续签、3派减-作废、4派减-终止
		initType(tEmployeeContractInfo);

		// 标准合同、劳动派遣合同、其他。————社保公积金都派减，自动审核通过
		this.judgeAuditStatus(tEmployeeContractInfo, user);
		if (Common.isEmpty(tEmployeeContractInfo.getId())) {
			// 针对编码再做一次重复性校验
			String isCur = baseMapper.getContractByApplyNo(tEmployeeContractInfo.getApplyNo());
			if (Common.isNotNull(isCur)) {
				String code = this.getCode(true);
				tEmployeeContractInfo.setApplyNo(code);
			}
			baseMapper.insert(tEmployeeContractInfo);
			//如果是否同步终止合同、减项、减档为是则生成同步任务处理清单
			//增加任务处理情况查询表数据
			if (Common.isNotNull(tEmployeeContractInfo.getChangeContractAndEmployee())
					&& CommonConstants.ZERO_STRING.equals(tEmployeeContractInfo.getChangeContractAndEmployee())) {
				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);
			}
		} else {
			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);
		}
		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);
		}
	}

	/**
	 * @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()) {
				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);
			tEmployeeContractAuditService.save(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);
		tEmployeeContractAuditService.save(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);
		tEmployeeContractAuditService.save(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) {
		if (tEmployeeContractInfo != null) {
			if (Common.isEmpty(tEmployeeContractInfo.getId()) || Common.isEmpty(tEmployeeContractInfo.getAuditStatus())) {
				return R.failed("id、意见必填");
			}
			TEmployeeContractInfo contractInfo = this.getById(tEmployeeContractInfo.getId());
			if (contractInfo.getAuditStatus() != CommonConstants.ONE_INT) {
				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));
					if (tEmployeeProject != null) {
						tEmployeeProject.setContractStatus(CommonConstants.ONE_INT);
						tEmployeeProjectService.updateById(tEmployeeProject);
					}
					// 更新档案、项目合同状态为（1在用）
					TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(contractInfo.getEmpId());
					if (tEmployeeInfo != null) {
						tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
						tEmployeeInfoMapper.updateById(tEmployeeInfo);
					}
				} else {
					//是否同步终止合同、减项、减档为是的时候 单独写逻辑
					if (EmployeeConstants.SITUATION_SEVEN.equals(contractInfo.getSituation())
							&& Common.isNotNull(contractInfo.getChangeContractAndEmployee())
							&& CommonConstants.ZERO_STRING.equals(contractInfo.getChangeContractAndEmployee())) {
						//同步任务处理清单执行详情
						StringBuilder workInfo = new StringBuilder();
						StringBuilder failueInfo = new StringBuilder();
						workInfo.append("合同终止成功,");
						//该项目下其他在用的合同统一更新成不在用
						List<TEmployeeContractInfo> contractInfoList = baseMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
								.lambda().eq(TEmployeeContractInfo::getEmpId, contractInfo.getEmpId())
								.eq(TEmployeeContractInfo::getSettleDomain, contractInfo.getSettleDomain())
								.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
								.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
								.ne(TEmployeeContractInfo::getId, tEmployeeContractInfo.getId()));
						if (Common.isNotNull(contractInfoList)) {
							for (TEmployeeContractInfo contractInfo1:contractInfoList) {
								contractInfo1.setInUse(CommonConstants.ONE_STRING);
								contractInfo1.setAuditUserName(user.getNickname());
								baseMapper.updateById(contractInfo1);
								//增加审核记录
								this.setAuditInfoNew(contractInfo1);
							}
						}
						//在途的合同更新为审核不通过
						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))
								.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.FOUR_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 (tEmployeeProject.getProjectStatus() == CommonConstants.ONE_INT && Common.isNotNull(tEmployeeInfo)) {
								TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());
								tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() - CommonConstants.ONE_INT);
								// 判断人员有无审核通过的其他合同
								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 (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 handlerInfo = workHandlerInfoService.getOne(Wrappers.<TWorkHandlerInfo>query()
								.lambda().eq(TWorkHandlerInfo::getDetailId, contractInfo.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 产品倩倩与测试说，作废终止审核通过，仅将原先选择的合同不在用即可
						//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("未找到关联的原合同");
						}
						// 作废、终止审核通过：
						// 更新项目合同状态为（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);
						}
					}
				}
			}
			tEmployeeContractInfo.setAuditUserName(user.getNickname());
			tEmployeeContractInfo.setContractNo(contractInfo.getContractNo());
			// 不是待提交，记录审核记录
			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) {
		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);
			} 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);
		}
	}

	/**
	 * @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_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())) {
						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));
					}
					// 核心保存
					R<List<ErrorMessage>> info = this.setBaseInfo(insert, project);
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), info.getMsg()));
				}
			} 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())) {
			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());
				}
			}


			}
	}

	/**
	 * 导出
	 */
	@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(":")) {
												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("-")) {
											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);
	}

	/**
	 * @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;
		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可用）
					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);
						tEmployeeProjectService.updateById(tEmployeeProject);
					}
					// 更新档案、项目合同状态为（1在用）
					tEmployeeInfo = tEmployeeInfoMapper.selectById(contract.getEmpId());
					if (tEmployeeInfo != null) {
						tEmployeeInfo.setContractStatus(CommonConstants.ONE_INT);
						tEmployeeInfoMapper.updateById(tEmployeeInfo);
					}
				} else {
					//是否同步终止合同、减项、减档为是的时候 单独写逻辑
					if (EmployeeConstants.SITUATION_SEVEN.equals(contract.getSituation())
							&& CommonConstants.ZERO_STRING.equals(contract.getChangeContractAndEmployee())) {
						//同步任务处理清单执行详情
						StringBuilder workInfo = new StringBuilder();
						StringBuilder failueInfo = new StringBuilder();
						workInfo.append("合同终止成功,");
						//该项目下其他在用的合同统一更新成不在用
						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);
								baseMapper.updateById(contractInfo1);
								//增加审核记录
								this.setAuditInfoNew(contractInfo1);
							}
						}
						//在途的合同更新为审核不通过
						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))
								.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT));
						if (Common.isNotNull(contractInfoListZt)) {
							for (TEmployeeContractInfo contractInfo1 : contractInfoListZt) {
								contractInfo1.setAuditStatus(CommonConstants.THREE_INT);
								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.FOUR_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 = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
							if (tEmployeeProject.getProjectStatus() == CommonConstants.ONE_INT && Common.isNotNull(tEmployeeInfo)) {
								TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeInfo.getId());
								tEmployeeInfo.setProjectNum(tEmployeeInfo.getProjectNum() - CommonConstants.ONE_INT);
								// 判断人员有无审核通过的其他合同
								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 (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("减档成功,");
									tEmployeeInfoMapper.updateById(tEmployeeInfo);
								} 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;
						}
						// 作废、终止审核通过：
						// 更新项目合同状态为（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);
						}
					}
				}
			}
			// 不是待提交，记录审核记录
			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 mpIdCard, String deptId) {
		String contractStart = baseMapper.getContractByEmpIdCardAndDeptId(mpIdCard, deptId);
		if (Common.isNotNull(contractStart)) {
			return R.ok(contractStart);
		} else {
			return R.failed("未找到合同");
		}
	}

}
