/*
 *    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.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
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.EmployeeConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.FddContractAttachInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.util.IdCardUtil;
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.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.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 法大大合同附属信息表
 *
 * @author fxj
 * @date 2022-06-28 16:24:12
 */
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(DaprUpmsProperties.class)
@Log4j2
public class FddContractAttachInfoServiceImpl extends ServiceImpl<FddContractAttachInfoMapper, FddContractAttachInfo> implements FddContractAttachInfoService {

	@Autowired
	private FddPersonAccountService fddPersonAccountService;

	@Autowired
	private FddContractInfoService fddContractInfoService;

	@Autowired
	private TEmployeeInfoMapper tEmployeeInfoMapper;

	@Autowired
	private TEmployeeProjectMapper tEmployeeProjectMapper;

	@Autowired
	private TEmployeeContractInfoService employeeContractInfoService;

	@Autowired
	private TSettleDomainService tSettleDomainService;

	@Autowired
	private TCustomerInfoService tCustomerInfoService;

	@Autowired
	private FddContractTemplateService fddContractTemplateService;

	@Autowired
	private DaprUpmsProperties daprUpmsProperties;

	@Autowired
	private TEmployeeInfoService employeeInfoService;

	@Autowired
	private TEmployeeProjectMapper employeeProjectMapper;

	@Autowired
	private TEmployeeLogService tEmployeeLogService;

	// 缓存信息
	@Autowired
	private CacheManager cacheManager;

	ExecutorService executorService = Executors.newFixedThreadPool(10);

	public static final String NO_VALID_CONTRACT_FOUND = "未获取到有效在用合同，请确认存在对应姓名、身份证、合同起始时间的合同数据";

	/**
	 * 法大大合同附属信息表简单分页查询
	 * @param fddContractAttachInfo 法大大合同附属信息表
	 * @return
	 */
	@Override
	public IPage<FddContractAttachInfo> getFddContractAttachInfoPage(Page<FddContractAttachInfo> page, FddContractAttachInfo fddContractAttachInfo) {
		return baseMapper.getFddContractAttachInfoPage(page, fddContractAttachInfo);
	}

	/**
	 * 获取有附属信息但是没有法大大电子合同的数据
	 * @param empIdcard
	 * @return
	 */
	@Override
	public List<FddContractAttachInfo> getListByNoInfoByEmpIdcard(@Param("empIdcard") String empIdcard) {
		return baseMapper.getListByNoInfoByEmpIdcard(empIdcard);
	}

	@Override
	public List<ErrorMessage> sendTask(List<FddContractAttachInfo> entityList) {
		List<ErrorMessage> errorList = new ArrayList<>();
		int i = 1;
		YifuUser user = SecurityUtils.getUser();
		for (FddContractAttachInfo attachInfo : entityList) {
			//保存合同数据
			attachInfo.setContractId(CommonConstants.EMPTY_STRING);

			R<String> employeeParamR;
			//新签
			employeeParamR = fddContractInfoService.generalEmployeeParam(attachInfo, false);
			if (CommonConstants.FAIL == employeeParamR.getCode()) {
				errorList.add(new ErrorMessage(i, employeeParamR.getMsg(), CommonConstants.RED));
				continue;
			}
			//保存数据
			this.save(attachInfo);
			attachInfo.setContractId(attachInfo.getId());
			this.updateById(attachInfo);
			//判断员工是否有实名数据，如果没有插入是实名数据
			long fddPersonCount = fddPersonAccountService.count(Wrappers.<FddPersonAccount>query().lambda().eq(FddPersonAccount::getMoblie, attachInfo.getEmpPhone())
					.eq(FddPersonAccount::getIdCard, attachInfo.getEmpIdcard()).eq(FddPersonAccount::getName, attachInfo.getEmpName())
					.eq(FddPersonAccount::getSystemFlag, CommonConstants.ONE_STRING));
			if (fddPersonCount == CommonConstants.ZERO_INT) {
				FddPersonAccount fddPersonAccount = new FddPersonAccount();
				fddPersonAccount.setMoblie(attachInfo.getEmpPhone());
				fddPersonAccount.setName(attachInfo.getEmpName());
				fddPersonAccount.setIdCard(attachInfo.getEmpIdcard());
				fddPersonAccount.setSystemFlag(CommonConstants.ONE_STRING);
				fddPersonAccount.setRealStatus(CommonConstants.ZERO_STRING);
				fddPersonAccountService.save(fddPersonAccount);
				executorService.submit(() -> {
					try {
						fddPersonAccountService.sendAuthMessage(fddPersonAccount.getId());
					} catch (Exception e) {
						log.error("执行异常", e);
					}
				});
			} else {
				executorService.submit(() -> {
					try {
						//如果已经实名发送电子合同
						FddContractAttachInfo fddContractAttachInfo = this.getById(attachInfo.getId());
						R<String> returnR = fddContractInfoService.saveEmpContract(fddContractAttachInfo,user);
						if (returnR != null) {
							//记录返回信息
							if (returnR.getCode() == CommonConstants.SUCCESS) {
								fddContractAttachInfo.setRemark("成功");
							} else {
								fddContractAttachInfo.setRemark(returnR.getMsg());
							}
							this.updateById(fddContractAttachInfo);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}
			i++;
			errorList.add(new ErrorMessage(i, "保存成功", CommonConstants.GREEN));
		}
		return errorList;
	}

	/**
	 *
	 * @Author hyc
	 * @Date 2022-06-02
	 * @param fddContractInfo
	 * @return R
	 **/
	@Override
	@Transactional
	public R<String> saveEmpAndAttarch(FddContractInfo fddContractInfo) {
		try {
			FddContractAttachInfo fddContractAttachInfo = this.getOne(Wrappers.<FddContractAttachInfo>query().lambda().eq(FddContractAttachInfo::getContractId, fddContractInfo.getContractId()));
			if (fddContractAttachInfo != null && fddContractAttachInfo.getContractId().equals(fddContractAttachInfo.getId())) {
				FddContractTemplate fddContractTemplate = fddContractTemplateService.getOne(Wrappers.<FddContractTemplate>query().lambda()
						.eq(FddContractTemplate::getId, fddContractInfo.getFddTemplateId()));
				TSettleDomain settleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda().eq(TSettleDomain::getDepartNo, fddContractAttachInfo.getDepartNo()));
				TCustomerInfo tCustomerInfo = tCustomerInfoService.getOne(Wrappers.<TCustomerInfo>query().lambda().eq(TCustomerInfo::getId, settleDomain.getCustomerId()));
				//查询项目档案
				TEmployeeProject tEmployeeProject = employeeProjectMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda().eq(TEmployeeProject::getDeptId, settleDomain.getId())
						.eq(TEmployeeProject::getDeptNo,settleDomain.getDepartNo())
						.eq(TEmployeeProject::getEmpIdcard, fddContractAttachInfo.getEmpIdcard()).eq(TEmployeeProject::getDeleteFlag, CommonConstants.ZERO_STRING));

				//查询人员档案
				TEmployeeInfo tEmployeeInfo = employeeInfoService.getOne(Wrappers.<TEmployeeInfo>query().lambda().eq(TEmployeeInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
						.eq(TEmployeeInfo::getEmpIdcard, fddContractAttachInfo.getEmpIdcard()));

				//该人员该结算主体有项目档案
				if (null != tEmployeeProject) {
					//如果是减项状态就复项
					TEmployeeProject tEmployeeProjectCompare = employeeProjectMapper.selectById(tEmployeeProject.getId());
					if (CommonConstants.ONE_INT == tEmployeeProject.getProjectStatus()) {
						tEmployeeProject.setProjectStatus(CommonConstants.ZERO_INT);
					}

					//判断人员档案的状态，如果是减档状态就复档
					TEmployeeInfo tEmployeeInfoCompare = employeeInfoService.getById(tEmployeeProject.getEmpId());
					if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus()) {
						tEmployeeInfo.setFileStatus(CommonConstants.ZERO_INT);
					}

					//更新项目档案
					tEmployeeProject.setEmpNatrue(fddContractTemplate.getType());
					tEmployeeProject.setPost(fddContractAttachInfo.getPost());
					employeeProjectMapper.updateById(tEmployeeProject);
					//保存操作记录
					tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],"",tEmployeeProject.getId(),tEmployeeProjectCompare,tEmployeeProject);

					//更新人员档案
					tEmployeeInfo.setEmpPhone(fddContractAttachInfo.getEmpPhone());
					tEmployeeInfo.setEmpNatrue(fddContractTemplate.getType());
					employeeInfoService.updateById(tEmployeeInfo);
					//保存操作记录
					tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],tEmployeeProject.getId(),"",tEmployeeInfoCompare,tEmployeeInfo);


					TEmployeeContractInfo employeeContractInfo = employeeContractInfoService.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpIdcard, fddContractAttachInfo.getEmpIdcard()).eq(TEmployeeContractInfo::getSettleDomain, settleDomain.getId())
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING));
					//无可用合同
					if (null == employeeContractInfo) {
						//新增合同
						TEmployeeContractInfo newEmployeeContractInfo = new TEmployeeContractInfo();
						saveTEmployeeContractInfo(newEmployeeContractInfo, fddContractAttachInfo, settleDomain, fddContractTemplate, tEmployeeInfo,tCustomerInfo, tEmployeeProject);
						//更新合同id
						updateContractId(fddContractInfo, fddContractAttachInfo, newEmployeeContractInfo);
					} else {
						//已有合同设置状态为不在用
						employeeContractInfo.setInUse(CommonConstants.ONE_STRING);
						employeeContractInfoService.updateById(employeeContractInfo);
						//新增合同
						TEmployeeContractInfo newEmployeeContractInfo2 = new TEmployeeContractInfo();
						saveTEmployeeContractInfo(newEmployeeContractInfo2, fddContractAttachInfo, settleDomain, fddContractTemplate, tEmployeeInfo,tCustomerInfo, tEmployeeProject);
						//更新合同id
						updateContractId(fddContractInfo, fddContractAttachInfo, newEmployeeContractInfo2);
					}
				} else {
					//判断人员档案是否存在，不存在就新增人员档案，存在则判断档案状态，如果是减档就复档
					if (Common.isNotNull(tEmployeeInfo)) {
						TEmployeeInfo employeeInfoCompare = employeeInfoService.getById(tEmployeeProject.getEmpId());
						if (CommonConstants.ONE_INT == tEmployeeInfo.getFileStatus()) {
							tEmployeeInfo.setFileStatus(CommonConstants.ZERO_INT);
						}
						//更新人员档案
						tEmployeeInfo.setEmpPhone(fddContractAttachInfo.getEmpPhone());
						tEmployeeInfo.setEmpNatrue(fddContractTemplate.getType());
						tEmployeeInfo.setProjectNum(CommonConstants.ONE_INT + employeeInfoCompare.getProjectNum());
						employeeInfoService.updateById(tEmployeeInfo);
						//保存操作记录
						tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],tEmployeeProject.getId(),"",employeeInfoCompare,tEmployeeInfo);
						//新增项目档案
						TEmployeeProject project = new TEmployeeProject();
						saveEmployeeproject(fddContractAttachInfo, settleDomain, fddContractTemplate, tEmployeeInfo,tCustomerInfo, project);
					} else {
						//新增人员档案
						TEmployeeInfo newEmployeeInfo = new TEmployeeInfo();
						newEmployeeInfo.setEmpName(fddContractAttachInfo.getEmpName());
						newEmployeeInfo.setEmpIdcard(fddContractAttachInfo.getEmpIdcard());
						newEmployeeInfo.setEmpPhone(fddContractAttachInfo.getEmpPhone());
						newEmployeeInfo.setEmpNatrue(fddContractTemplate.getType());
						newEmployeeInfo.setEmpCode(getCode());
						newEmployeeInfo.setFileStatus(CommonConstants.ZERO_INT);
						newEmployeeInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
						newEmployeeInfo.setStatus(CommonConstants.ZERO_INT);
						newEmployeeInfo.setProjectNum(CommonConstants.ONE_INT);
						newEmployeeInfo.setFileSource(CommonConstants.dingleDigitStrArray[4]);
						Date date = IdCardUtil.getBirthdate(fddContractAttachInfo.getEmpIdcard());

						if (null != date) {
							//初始化年龄
							newEmployeeInfo.setEmpAge(IdCardUtil.IdNOToAge(fddContractAttachInfo.getEmpIdcard()));
							newEmployeeInfo.setEmpBirthday(date);
						}
						newEmployeeInfo.setEmpSex(IdCardUtil.getSex(fddContractAttachInfo.getEmpIdcard()));
						tEmployeeInfoMapper.insert(newEmployeeInfo);

						//新增项目档案
						TEmployeeProject newTEmpProject = new TEmployeeProject();
						saveEmployeeproject(fddContractAttachInfo, settleDomain, fddContractTemplate, newEmployeeInfo,tCustomerInfo, tEmployeeProject);

						//新增合同
						TEmployeeContractInfo newEmployeeContractInfo1 = new TEmployeeContractInfo();
						saveTEmployeeContractInfo(newEmployeeContractInfo1, fddContractAttachInfo, settleDomain, fddContractTemplate, tEmployeeInfo,tCustomerInfo,newTEmpProject);
						//更新合同id
						updateContractId(fddContractInfo, fddContractAttachInfo, newEmployeeContractInfo1);
					}
				}
			}
		}catch (Exception e) {
			log.error("保存异常：" + e.getMessage());
			return R.failed("保存异常：" + e.getMessage());
		}
		return R.ok();
	}

	@Override
	public List<ErrorMessage> batchAdd(List<FddContractAttachInfo> entityList) {
		List<ErrorMessage> errorList = new ArrayList<>();
		Set<String> errorMsg;
		YifuUser user = SecurityUtils.getUser();

		Map<String, Integer> sameCheck = new HashMap<>();
		int i = 1;
		try {
			if (null != entityList && !entityList.isEmpty()) {
				for (FddContractAttachInfo attachInfo : entityList) {
					errorMsg = new HashSet<>();
					i++;

					String sameInfo = attachInfo.getEmpNatrue() + "_" + attachInfo.getDepartNo()
							+ "_" + attachInfo.getFddTemplateId() + "_" + attachInfo.getContractStart()
							+ "_" + attachInfo.getContractEnd();
					if (sameCheck.get(sameInfo) != null) {
						errorMsg.add("第" + (i) + "行与第" + sameCheck.get(sameInfo) + "行重复！");
					} else {
						sameCheck.put(sameInfo, i);
					}
					//判断计时计件工资必填
					if (CommonConstants.ONE_STRING.equals(attachInfo.getSalaryType()) && Common.isEmpty(attachInfo.getSalaryStandardPerHour())) {
						errorMsg.add("计时工资不能为空");
					}
					if (CommonConstants.TWO_STRING.equals(attachInfo.getSalaryType()) && Common.isEmpty(attachInfo.getSalaryStandardPerPiece())) {
						errorMsg.add("计件工资不能为空");
					}
					//结算主体编码是否准确
					TSettleDomain settleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda().eq(TSettleDomain::getDepartNo, attachInfo.getDepartNo())
							.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING).eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
					if (Common.isEmpty(settleDomain)) {
						errorMsg.add("项目编码有误");
					} else {
						//查询员工合同
						TEmployeeContractInfo employeeContractInfo = employeeContractInfoService.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
								.eq(TEmployeeContractInfo::getEmpIdcard, attachInfo.getEmpIdcard()).eq(TEmployeeContractInfo::getSettleDomain, settleDomain.getId())
								.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_STRING));
						if (employeeContractInfo != null) {
							long count = this.count(Wrappers.<FddContractAttachInfo>query().lambda().eq(FddContractAttachInfo::getContractId, employeeContractInfo.getId()));
							if (count > CommonConstants.ZERO_INT && attachInfo.getContractStart().before(employeeContractInfo.getContractEnd())) {
								errorMsg.add("已导入合同相关基础数据");
							}

							List<FddContractTemplate> fddContractTemplateList = fddContractTemplateService.list(Wrappers.<FddContractTemplate>query().lambda()
									.eq(FddContractTemplate::getFddTemplateId, attachInfo.getFddTemplateId())
									.eq(FddContractTemplate::getModifyUploadStatus, CommonConstants.dingleDigitStrArray[1]));
							//如果模板存在则生成法大大电子合同数据
							if (fddContractTemplateList.size() == CommonConstants.ZERO_INT) {
								errorMsg.add("未获取到有效的合同模板");
							}
							if (fddContractTemplateList.size() != CommonConstants.ONE_INT) {
								errorMsg.add("法大大合同有效合同模板存在多条");
							} else {
								errorMsg.add("存在“在用”的合同");
							}
						}
					}

					//校验数据
					R<String> employeeParamR;
					//新签
					employeeParamR = fddContractInfoService.generalEmployeeParam(attachInfo, false);
					if (CommonConstants.FAIL == employeeParamR.getCode()) {
						errorMsg.add(employeeParamR.getMsg());
					}
					// 数据合法情况
					if (!CollUtil.isEmpty(errorMsg)) {
						// 数据不合法
						errorList.add(new ErrorMessage(i, errorMsg));
					} else {

						//保存合同数据
						attachInfo.setContractId(CommonConstants.EMPTY_STRING);
						attachInfo.setCreateTime(LocalDateTime.now());
						//保存数据
						this.save(attachInfo);
						attachInfo.setContractId(attachInfo.getId());
						this.updateById(attachInfo);
						//判断员工是否有实名数据，如果没有插入是实名数据
						long fddPersonCount = fddPersonAccountService.count(Wrappers.<FddPersonAccount>query().lambda().eq(FddPersonAccount::getMoblie, attachInfo.getEmpPhone())
								.eq(FddPersonAccount::getIdCard, attachInfo.getEmpIdcard()).eq(FddPersonAccount::getName, attachInfo.getEmpName())
								.eq(FddPersonAccount::getSystemFlag, CommonConstants.ONE_STRING));
						if (fddPersonCount == CommonConstants.ZERO_INT) {
							FddPersonAccount fddPersonAccount = new FddPersonAccount();
							fddPersonAccount.setMoblie(attachInfo.getEmpPhone());
							fddPersonAccount.setName(attachInfo.getEmpName());
							fddPersonAccount.setIdCard(attachInfo.getEmpIdcard());
							fddPersonAccount.setSystemFlag(CommonConstants.ONE_STRING);
							fddPersonAccount.setRealStatus(CommonConstants.ZERO_STRING);
							fddPersonAccountService.save(fddPersonAccount);
							executorService.submit(() -> {
								try {
									fddPersonAccountService.sendAuthMessage(fddPersonAccount.getId());
								} catch (Exception e) {
									log.error("执行异常", e);
								}
							});
						} else {
							executorService.submit(() -> {
								try {
									//如果已经实名发送电子合同
									FddContractAttachInfo fddContractAttachInfo = this.getById(attachInfo.getId());
									R<String> returnR = fddContractInfoService.saveEmpContract(fddContractAttachInfo, user);
									if (returnR != null) {
										//记录返回信息
										if (returnR.getCode() == CommonConstants.SUCCESS) {
											fddContractAttachInfo.setRemark("成功");
										} else {
											fddContractAttachInfo.setRemark(returnR.getMsg());
										}
										this.updateById(fddContractAttachInfo);
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							});
						}
						errorList.add(new ErrorMessage(i, "保存成功", CommonConstants.GREEN));
					}
				}
			} else {
				errorList.add(new ErrorMessage(i, "无数据保存"));
			}
		} catch (Exception e) {
			log.error("合同数据批量新增异常" + e.getMessage());
			return errorList;
		}
		return errorList;
	}

	@Override
	public List<ErrorMessage> batchUpdate(List<FddContractAttachInfo> entityList) {
		List<ErrorMessage> errorList = new ArrayList<>();
		int i = 1;
		try {
			if (null != entityList && !entityList.isEmpty()) {
				for (FddContractAttachInfo attachInfo : entityList) {
					//查询员工合同
					TEmployeeContractInfo employeeContractInfoValid = employeeContractInfoService.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpName, attachInfo.getEmpName()).eq(TEmployeeContractInfo::getEmpIdcard, attachInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING).eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
							.eq(TEmployeeContractInfo::getContractStart, attachInfo.getContractStart()));
					if(employeeContractInfoValid==null){
						errorList.add(new ErrorMessage(i, NO_VALID_CONTRACT_FOUND, CommonConstants.RED));
						continue;
					}
					if(StringUtils.equals(CommonConstants.ONE_STRING,employeeContractInfoValid.getContractType())){
						if(employeeContractInfoValid.getContractEnd()==null){
							errorList.add(new ErrorMessage(i, "员工合同结束时间为空", CommonConstants.RED));
							continue;
						}
					}
					//查询员工合同是否存在
					TEmployeeContractInfo employeeContractInfo = employeeContractInfoService.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
							.eq(TEmployeeContractInfo::getEmpName, attachInfo.getEmpName()).eq(TEmployeeContractInfo::getEmpIdcard, attachInfo.getEmpIdcard())
							.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
							.and(wrapper -> wrapper.and(wrapper2 -> wrapper2.eq(TEmployeeContractInfo::getContractStart, attachInfo.getContractStart())
											.eq(TEmployeeContractInfo::getContractEnd, attachInfo.getContractEnd()).eq(TEmployeeContractInfo::getContractType, CommonConstants.ONE_STRING))//有合同截止日期
									.or(wrapper1 -> wrapper1.eq(TEmployeeContractInfo::getContractStart, attachInfo.getContractStart()).in(TEmployeeContractInfo::getContractType, CommonConstants.ZERO_STRING, CommonConstants.TWO_STRING))//无合同截止时间
							));
					if (employeeContractInfo == null) {
						errorList.add(new ErrorMessage(i, NO_VALID_CONTRACT_FOUND, CommonConstants.RED));
						continue;
					}
					FddContractAttachInfo fddContractAttachInfo = this.getOne(Wrappers.<FddContractAttachInfo>query().lambda().eq(FddContractAttachInfo::getContractId, employeeContractInfo.getId()));
					if (fddContractAttachInfo == null) {
						errorList.add(new ErrorMessage(i, "为获取到电子合同数据", CommonConstants.RED));
						continue;
					}
					BeanUtils.copyProperties(attachInfo, fddContractAttachInfo);
					//保存合同数据
					this.updateById(fddContractAttachInfo);
					i++;
					errorList.add(new ErrorMessage(i, "更新成功", CommonConstants.GREEN));
				}
			} else {
				errorList.add(new ErrorMessage(i, EmployeeConstants.NO_DATA_UPDATE));
			}
		} catch (Exception e) {
			log.error("合同数据批量新增异常" + e.getMessage());
			return errorList;
		}
		return errorList;
	}

	/**
	 * @param fddContractInfo
	 * @param fddContractAttachInfo
	 * @param newEmployeeContractInfo
	 * @Author: huyc
	 * @Date: 2022/06/01
	 * @Description: 更新合同id
	 * @return:
	 **/
	public void updateContractId (FddContractInfo fddContractInfo, FddContractAttachInfo fddContractAttachInfo,TEmployeeContractInfo newEmployeeContractInfo) {
		//更新合同id
		fddContractAttachInfo.setContractId(newEmployeeContractInfo.getId());
		this.updateById(fddContractAttachInfo);
		//更新合同id
		fddContractInfo.setContractId(newEmployeeContractInfo.getId());
		fddContractInfoService.updateById(fddContractInfo);
	}

	/**
	 * @param newEmployeeContractInfo
	 * @param fddContractAttachInfo
	 * @param settleDomain
	 * @param fddContractTemplate
	 * @param tEmployeeInfo
	 * @param tEmployeeProject
	 * @Author: huyc
	 * @Date: 2022/06/01
	 * @Description: 新增合同
	 * @return:
	 **/
	public void saveTEmployeeContractInfo (TEmployeeContractInfo newEmployeeContractInfo, FddContractAttachInfo fddContractAttachInfo,TSettleDomain settleDomain,FddContractTemplate fddContractTemplate,
										   TEmployeeInfo tEmployeeInfo, TCustomerInfo tCustomerInfo, TEmployeeProject tEmployeeProject) {
		TEmployeeContractInfo employeeContractCount = employeeContractInfoService.getOne(Wrappers.<TEmployeeContractInfo>query().lambda()
				.eq(TEmployeeContractInfo::getEmpIdcard, fddContractAttachInfo.getEmpIdcard()).eq(TEmployeeContractInfo::getSettleDomain, settleDomain.getId())
				.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING));
		//合同表里没有在用的合同
		if (null == employeeContractCount) {
			newEmployeeContractInfo.setEmpName(fddContractAttachInfo.getEmpName());
			newEmployeeContractInfo.setEmpIdcard(fddContractAttachInfo.getEmpIdcard());
			newEmployeeContractInfo.setSettleDomain(settleDomain.getId());
			newEmployeeContractInfo.setSubjectDepart(settleDomain.getDepartName());
			newEmployeeContractInfo.setSubjectUnit(tCustomerInfo.getCustomerName());
			newEmployeeContractInfo.setContractType(CommonConstants.ONE_STRING);
			newEmployeeContractInfo.setContractStart(fddContractAttachInfo.getContractStart());
			newEmployeeContractInfo.setContractEnd(fddContractAttachInfo.getContractEnd());
			newEmployeeContractInfo.setPost(fddContractAttachInfo.getPost());
			newEmployeeContractInfo.setWorkingHours("");
			newEmployeeContractInfo.setSituation("正常签订");
			newEmployeeContractInfo.setIsObsolete(CommonConstants.ZERO_STRING);
			newEmployeeContractInfo.setEmpId(tEmployeeInfo.getId());
			newEmployeeContractInfo.setWorkFlag(CommonConstants.ZERO_STRING);
			newEmployeeContractInfo.setIsFile(CommonConstants.ONE_STRING);
			newEmployeeContractInfo.setEmpNo(tEmployeeProject.getEmpNo());
			newEmployeeContractInfo.setFileCity(tEmployeeInfo.getFileCity());
			newEmployeeContractInfo.setFileProvince(tEmployeeInfo.getFileProvince());
			newEmployeeContractInfo.setFileTown(tEmployeeInfo.getFileTown());
			newEmployeeContractInfo.setInUse(CommonConstants.ZERO_STRING);

			//远程接口传参
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("value",fddContractTemplate.getType());
			jsonObject.put("type","personnel_type");
			R<String> res = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
					, "/dict/inner/getLableFronValue", jsonObject, Map.class, SecurityConstants.FROM_IN);
			if (res != null) {
				//电子合同模板对应的“员工类型”
				newEmployeeContractInfo.setContractName(res.getData());
			} else {
				newEmployeeContractInfo.setContractName("");
			}
			//设置状态为在用
			newEmployeeContractInfo.setInUse(CommonConstants.ONE_STRING);
			employeeContractInfoService.save(newEmployeeContractInfo);
		}
	}

	/**
	 * @param fddContractAttachInfo
	 * @param settleDomain
	 * @param fddContractTemplate
	 * @param newEmployeeInfo
	 * @param tCustomerInfo
	 * @param newTEmpProject
	 * @Author: huyc
	 * @Date: 2022/06/01
	 * @Description: 新增项目档案
	 * @return:
	 **/
	public void saveEmployeeproject(FddContractAttachInfo fddContractAttachInfo,TSettleDomain settleDomain,FddContractTemplate fddContractTemplate,
									TEmployeeInfo newEmployeeInfo, TCustomerInfo tCustomerInfo, TEmployeeProject newTEmpProject) {
		//新增项目档案

		newTEmpProject.setEmpName(fddContractAttachInfo.getEmpName());
		newTEmpProject.setEmpIdcard(fddContractAttachInfo.getEmpIdcard());
		newTEmpProject.setEmpPhone(fddContractAttachInfo.getEmpPhone());
		newTEmpProject.setDeptId(settleDomain.getId());
		newTEmpProject.setDeptNo(settleDomain.getDepartNo());
		newTEmpProject.setDeptName(settleDomain.getDepartName());
		newTEmpProject.setPost(fddContractAttachInfo.getPost());
		newTEmpProject.setUnitId(tCustomerInfo.getId());
		newTEmpProject.setUnitName(tCustomerInfo.getCustomerName());
		newTEmpProject.setUnitNo(tCustomerInfo.getCustomerCode());
		newTEmpProject.setContractType(fddContractTemplate.getType());
		newTEmpProject.setStatus(CommonConstants.dingleDigitIntArray[0]);
		newTEmpProject.setPost(fddContractAttachInfo.getPost());
		newTEmpProject.setEmpNatrue(newEmployeeInfo.getEmpNatrue());
		newTEmpProject.setEmpCode(newEmployeeInfo.getEmpCode());
		String empNO = "";
		empNO = getEmpNo(newTEmpProject.getDeptNo());
		newTEmpProject.setEmpNo(empNO);
		//新增档案
		tEmployeeProjectMapper.insert(newTEmpProject);
	}

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

	//获取员工主码
	private synchronized String getCode() {
		String nowDay = DateUtil.getThisDay();
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_EMP_CODE);
		Object nowNumObj = cache.get(nowDay);
		int nowNums = 1;
		if (Common.isNotNull(nowNumObj)) {
			SimpleValueWrapper value = (SimpleValueWrapper) nowNumObj;
			nowNums = (Integer) value.get() + 1;
		}
		cache.put(nowDay, nowNums);
		return "ZM" + nowDay + this.getFiveNum(String.valueOf(nowNums));
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取五位字符型数字
	 * @Author: hgw
	 * @Date: 2022/6/21 17:35
	 * @return: 五位字符型数字
	 **/
	private String getFiveNum(String nowNums) {
		if (nowNums.length() >= 5) {
			return nowNums.substring(0, 5);
		}
		String[] zeroArr = {"0", "00", "000", "0000"};
		int num = 4 - nowNums.length();
		return zeroArr[num] + nowNums;
	}

}
