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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCustomerInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmpChangeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpChangeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TSettleDomainMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TCustomerInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpChangeInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TEmpChangeInfoNewVO;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TEmpChangeInfoVO;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.vo.UpdateSocialFoundVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 档案划转日志表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@Service
@RequiredArgsConstructor
public class TEmpChangeInfoServiceImpl extends ServiceImpl<TEmpChangeInfoMapper, TEmpChangeInfo> implements TEmpChangeInfoService {

	private final TEmployeeProjectService tEmployeeProjectService;

	private final TCustomerInfoService tCustomerInfoService;

	private final TSettleDomainMapper tSettleDomainMapper;

	private final TEmployeeLogServiceImpl tEmployeeLogService;

	private final TEmployeeContractInfoMapper contractInfoMapper;

	@Autowired
	private final SocialDaprUtils socialDaprUtils;

	public static final Pattern PATTERN = Pattern.compile("^[-\\+]?[\\d]*$");

	/**
	 * @Author huyc
	 * @Description  档案划转
	 * @Date 2022/6/22
	 **/
	@Override
	public R changeEmpProArc(TEmpChangeInfo tEmpChangeInfo) {

		//待划转员工已在目标项目下不可划转
		TEmployeeProject tEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, tEmpChangeInfo.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,tEmpChangeInfo.getDeptNo())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
		if (Common.isNotNull(tEmployeeProject)) {
			return R.failed("待划转员工已在目标项目下不可划转");
		}
		//划转+已产生未结算金额划转，并且选择了划转月份
		//社保公积金派单处需要直接修改为最新的项目
		//社保预估库、缴费库、对比库、代理差额库，需要同步修改未结算（并且满足这个条件：数据 生成月≥此处划转起始月）的数据，已结算数据不变更；
		//划转,更新项目信息
		TEmployeeProject updateTEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, tEmpChangeInfo.getEmpIdcard()).eq(TEmployeeProject::getDeptName,tEmpChangeInfo.getOldSettle())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL).eq(TEmployeeProject::getProjectStatus,CommonConstants.ZERO_INT));
		if (Common.isNotNull(updateTEmployeeProject)) {

			if (updateTEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[1] ||
					updateTEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[1]) {
				return R.failed("人员在原项目中存在在途的服务，请先终止后，再进行划转");
			}

			TSettleDomain tSettleDomain = tSettleDomainMapper.selectOne(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDepartNo, tEmpChangeInfo.getDeptNo()).eq(TSettleDomain::getDepartName, tEmpChangeInfo.getNewSettle())
					.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING).eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
			if (Common.isEmpty(tSettleDomain)) {
				return R.failed("对应项目编码的项目已停止合作");
			}
			TEmployeeProject tEmployeeProjectOld = tEmployeeProjectService.getById(updateTEmployeeProject.getId());
			updateTEmployeeProject.setDeptNo(tEmpChangeInfo.getDeptNo());
			updateTEmployeeProject.setDeptId(tEmpChangeInfo.getDeptId());
			updateTEmployeeProject.setDeptName(tEmpChangeInfo.getNewSettle());
			updateTEmployeeProject.setUnitId(tEmpChangeInfo.getUnitId());
			updateTEmployeeProject.setUnitNo(tEmpChangeInfo.getUnitNo());
			updateTEmployeeProject.setUnitName(tEmpChangeInfo.getNewDept());
			updateTEmployeeProject.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
			updateTEmployeeProject.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
			updateTEmployeeProject.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
			// 记录变更日志
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "", updateTEmployeeProject.getId(), tEmployeeProjectOld, updateTEmployeeProject);
			updateTEmployeeProject.setOdlDeptId(tEmployeeProjectOld.getDeptId());
			updateTEmployeeProject.setOldDeptNo(tEmployeeProjectOld.getDeptNo());
			tEmployeeProjectService.updateById(updateTEmployeeProject);
			tEmpChangeInfo.setProId(updateTEmployeeProject.getId());

			UpdateSocialFoundVo updateSocialFoundVo = new UpdateSocialFoundVo();
			updateSocialFoundVo.setOldDeptId(updateTEmployeeProject.getOdlDeptId());
			updateSocialFoundVo.setEmpIdcard(updateTEmployeeProject.getEmpIdcard());
			updateSocialFoundVo.setSettleDomainCode(updateTEmployeeProject.getDeptNo());
			updateSocialFoundVo.setSettleDomainId(updateTEmployeeProject.getDeptId());
			updateSocialFoundVo.setSettleDomainName(updateTEmployeeProject.getDeptName());
			updateSocialFoundVo.setUnitId(updateTEmployeeProject.getUnitId());
			updateSocialFoundVo.setUnitName(updateTEmployeeProject.getUnitName());
			if (CommonConstants.ONE_STRING.equals(tEmpChangeInfo.getUnsettleDeal())) {
				updateSocialFoundVo.setSocialCreateMonth(tEmpChangeInfo.getChangeStartMonth().replace("-",""));
				socialDaprUtils.updatePaymentSocialAndFound(updateSocialFoundVo);
				socialDaprUtils.updateForSocialAndFound(updateSocialFoundVo);
			}
			if (CommonConstants.ZERO_INT != updateTEmployeeProject.getSocialStatus()) {
				updateSocialFoundVo.setFlag(CommonConstants.ZERO_STRING);
				socialDaprUtils.updateSocialAndFoundInfo(updateSocialFoundVo);
			}
			if (CommonConstants.ZERO_INT != updateTEmployeeProject.getFundStatus()) {
				updateSocialFoundVo.setFlag(CommonConstants.ONE_STRING);
				socialDaprUtils.updateSocialAndFoundInfo(updateSocialFoundVo);
			}
			// 合同同步划转---只划转在用合同 fxj 2023-03-06
			contractInfoMapper.updateContractChange(updateTEmployeeProject.getEmpIdcard(),updateTEmployeeProject.getDeptNo(),updateTEmployeeProject.getOldDeptNo());
		}

		//保存档案划转记录
		this.save(tEmpChangeInfo);
		return R.ok();
	}

	@Override
	public R<List<ErrorMessage>> batchChangeArc(List<TEmpChangeInfoVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		Map<Long,ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorMessageList)){
			errorMessageList.forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(),errorMessage));
		}

		// 老项目已减项，划转后将删除 hgw 2023-8-22 10:47:41
		List<TEmployeeProject> oldUpdateList = new ArrayList<>();
		List<TEmployeeProject> updateList = new ArrayList<>();
		Set<String> errorMsg;
		//对象声明
		TEmpChangeInfoVO excel;
		TSettleDomain tSettleDomain;
		TEmployeeProject employeeProject;
		TEmployeeProject updateTEmployeePro;
		TEmployeeProject tEmployeeProjectOld;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get((long)i+2))){
				continue;
			}
			errorMsg = new HashSet<>();
			excel = excelVOList.get(i);
			excel.setUnsettleDeal(CommonConstants.IS_NO_CHANGE);
			if (Common.isNotNull(excel.getChangeStartMonth()) && excel.getChangeStartMonth().length() > CommonConstants.dingleDigitIntArray[6]) {
				errorMsg.add("划转起始月长度不能超过6位");
			}
			if (!Common.isEmpty(excel.getChangeStartMonth()) && !PATTERN.matcher(excel.getChangeStartMonth()).matches()) {
				errorMsg.add("划转起始月格式错误");
			}
			if (excel.getUnsettleDeal().equals(CommonConstants.IS_CHANGE)) {
				if (Common.isEmpty(excel.getChangeStartMonth())) {
					errorMsg.add("划转起始月不能为空");
				} else if (PATTERN.matcher(excel.getChangeStartMonth()).matches() &&
						Integer.parseInt(excel.getChangeStartMonth()) > Integer.parseInt(DateUtil.getThisMonth())) {
						errorMsg.add("划转起始月要小于等于当前月");
				}
			}

			//项目编码校验
			tSettleDomain = tSettleDomainMapper.selectOne(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDepartNo, excel.getNewSettleCode())
					.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING)
					.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING));
			if (Common.isEmpty(tSettleDomain)) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.PROJECT_SEARCH_NOT_EXIST, excel.getNewSettleCode()));
			}

			//待划转员工已在目标项目下不可划转
			employeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,excel.getNewSettleCode())
					.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
			if (Common.isNotNull(employeeProject)) {
				if (CommonConstants.ZERO_INT == employeeProject.getProjectStatus()) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_CHANGE_EMP_PROJECT, excel.getNewSettleCode()));
				} else {
					employeeProject.setDeleteFlag(CommonConstants.STATUS_DEL);
					oldUpdateList.add(employeeProject);
				}
			}
			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				//划转,更新项目信息
				updateTEmployeePro = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,excel.getOldSettleCode())
						.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
				if (Common.isNotNull(updateTEmployeePro)) {
					if (updateTEmployeePro.getSocialStatus() == CommonConstants.dingleDigitIntArray[1] ||
							updateTEmployeePro.getFundStatus() == CommonConstants.dingleDigitIntArray[1]) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.QT_PROJECT_CHANGE_NOT_EXIST, excel.getOldSettleCode()));
					}
					if (CommonConstants.ONE_INT == updateTEmployeePro.getProjectStatus()) {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.PROJECT_PERSON_DELETE_EXIT, excel.getOldSettleCode()));
					} else if (Common.isNotNull(tSettleDomain)) {
						tEmployeeProjectOld = tEmployeeProjectService.getById(updateTEmployeePro.getId());
						updateTEmployeePro.setDeptNo(tSettleDomain.getDepartNo());
						updateTEmployeePro.setDeptId(tSettleDomain.getId());
						updateTEmployeePro.setDeptName(tSettleDomain.getDepartName());
						updateTEmployeePro.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
						updateTEmployeePro.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
						updateTEmployeePro.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
						updateTEmployeePro.setUnitId(tSettleDomain.getCustomerId());
						updateTEmployeePro.setUnitNo(tSettleDomain.getCustomerNo());
						updateTEmployeePro.setUnitName(tSettleDomain.getCustomerName());
						updateTEmployeePro.setChangeStartMonth(excel.getChangeStartMonth());
						updateTEmployeePro.setUnsettleDeal(CommonConstants.IS_NO_CHANGE);
						// 记录变更日志
						tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "", updateTEmployeePro.getId(), tEmployeeProjectOld, updateTEmployeePro);
						updateTEmployeePro.setOdlDeptId(tEmployeeProjectOld.getDeptId());
						updateTEmployeePro.setOldDeptNo(tEmployeeProjectOld.getDeptNo());
						updateList.add(updateTEmployeePro);
					}
				} else {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.PROJECT_PERSON_SEARCH_EXIT, excel.getOldSettleCode()));
				}
			}
			if (!CollUtil.isEmpty(errorMsg)) {
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}

		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		} else {
			// 将已减项的目标项目删除，免得出现两条同项目在项
			if (!oldUpdateList.isEmpty()) {
				tEmployeeProjectService.updateBatchById(oldUpdateList);
			}
			tEmployeeProjectService.updateBatchById(updateList);
			// 循环里的申明
			UpdateSocialFoundVo updateSocialFoundVo;
			for (TEmployeeProject tEmployeeProject: updateList) {
				updateSocialFoundVo = new UpdateSocialFoundVo();
				updateSocialFoundVo.setOldDeptId(tEmployeeProject.getOdlDeptId());
				updateSocialFoundVo.setEmpIdcard(tEmployeeProject.getEmpIdcard());
				updateSocialFoundVo.setSettleDomainCode(tEmployeeProject.getDeptNo());
				updateSocialFoundVo.setSettleDomainId(tEmployeeProject.getDeptId());
				updateSocialFoundVo.setUnitId(tEmployeeProject.getUnitId());
				updateSocialFoundVo.setUnitName(tEmployeeProject.getUnitName());
				updateSocialFoundVo.setSettleDomainName(tEmployeeProject.getDeptName());
				if (CommonConstants.IS_CHANGE.equals(tEmployeeProject.getUnsettleDeal())) {
					updateSocialFoundVo.setSocialCreateMonth(tEmployeeProject.getChangeStartMonth());
					socialDaprUtils.updatePaymentSocialAndFound(updateSocialFoundVo);
					socialDaprUtils.updateForSocialAndFound(updateSocialFoundVo);
				}
				if (CommonConstants.ZERO_INT != tEmployeeProject.getSocialStatus()) {
					updateSocialFoundVo.setFlag(CommonConstants.ZERO_STRING);
					socialDaprUtils.updateSocialAndFoundInfo(updateSocialFoundVo);
				}
				if (CommonConstants.ZERO_INT != tEmployeeProject.getFundStatus()) {
					updateSocialFoundVo.setFlag(CommonConstants.ONE_STRING);
					socialDaprUtils.updateSocialAndFoundInfo(updateSocialFoundVo);
				}
				// 合同同步划转---只划转在用合同 fxj 2023-03-06
				contractInfoMapper.updateContractChange(tEmployeeProject.getEmpIdcard(),tEmployeeProject.getDeptNo(),tEmployeeProject.getOldDeptNo());
			}
		}
		return R.ok();
	}

	/**
	 * 获取所有项目名称
	 * @return R
	 * @Author huyc
	 * @Date 2022-06-22
	 * @param customerName
	 */
	@Override
	public R<List<TSettleDomain>> getAllDept(String customerName) {
		List<TSettleDomain> list;
		if (Common.isNotNull(customerName)){
			list = tSettleDomainMapper.selectList(Wrappers.<TSettleDomain>query().lambda().eq(TSettleDomain::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.eq(TSettleDomain::getStopFlag,CommonConstants.STATUS_NORMAL).eq(TSettleDomain::getCustomerName,customerName));
		}else {
			list = tSettleDomainMapper.selectList(Wrappers.<TSettleDomain>query().lambda().eq(TSettleDomain::getDeleteFlag, CommonConstants.STATUS_NORMAL)
					.eq(TSettleDomain::getStopFlag,CommonConstants.STATUS_NORMAL));
		}
		return R.ok(list);
	}

	/**
	 * 获取所有单位名称
	 * @return R
	 * @Author huyc
	 * @Date 2022-06-22
	 * @param customerName
	 */
	@Override
	public R<List<TCustomerInfo>> getAllUint(String customerName) {
		List<TCustomerInfo> list = tCustomerInfoService.getAllUnit(customerName);
		return R.ok(list);
	}

	/**
	 * 分页获取项目名称缩小可见范围
	 *
	 * @author wzb
	 * @param page
	 * @param departName
	 * @param nameOrNo
	 * @param customerId
	 * @param flag
	 * @return {@link IPage< TSettleDomain>}
	 */
	@Override
	public IPage<TSettleDomain> getAllDeptPagePermission(Page page, String departName, String nameOrNo, String customerId,String flag) {
		YifuUser user = SecurityUtils.getUser();
		String userId=user.getId();
		// SSC开发组-1668092146875969537L  超管1
		long roleId = 1668092146875969537L;
		boolean isSsc =	this.haveRole(user, roleId);
		if (!isSsc) {
			isSsc =	this.haveRole(user, 1L);
		}
		if (isSsc) {
			userId = "-999";
		}
		return tSettleDomainMapper.getPagePerMission(page, userId, departName, nameOrNo, customerId, flag);

	}

	/**
	 * @Description:  检测是否有某个角色权限
	 * @Author: hgw
	 * @Date: 2023/6/12 11:09
	 * @return: boolean
	 **/
	private boolean haveRole(YifuUser user, long roleId) {
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 分页获取所有项目名称
	 * @return R
	 * @Author huyc
	 * @Date 2022-07-26
	 */
	@Override
	public IPage<TSettleDomain> getAllDeptPage(Page page, String deptName, String nameOrNo, String customerId,String flag) {
		LambdaQueryWrapper<TSettleDomain> wrapper = buildQueryWrapper(deptName, nameOrNo, customerId,flag);
		return tSettleDomainMapper.selectPage(page,wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(String deptName, String nameOrNo, String customerId,String flag) {
		LambdaQueryWrapper<TSettleDomain> wrapper = Wrappers.lambdaQuery();
		if (Common.isNotNull(deptName)) {
			wrapper.like(TSettleDomain::getDepartName, deptName);
		}
		if (Common.isNotNull(nameOrNo)) {
			wrapper.and(obj->obj.like(TSettleDomain::getDepartName, nameOrNo)
							.or()
							.like(TSettleDomain::getDepartNo, nameOrNo));
		}
		if (Common.isNotNull(customerId)) {
			wrapper.eq(TSettleDomain::getCustomerId, customerId);
		}
		wrapper.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING);
		if (Common.isEmpty(flag)) {
			wrapper.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING);
		}
		return wrapper;
	}

	/**
	 * @Author huyc
	 * @Description  档案划转
	 * @Date 2022/6/22
	 **/
	@Transactional
	@Override
	public R<Boolean> changeEmpProArcNew(TEmpChangeInfoNewVO vo) {
		if (Common.isEmpty(vo)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		if (Common.isEmpty(vo.getChangeItems())){
			return R.failed("划转项不可为空！");
		}
		StringBuilder resStr = new StringBuilder();
		//待划转员工已在目标项目下不可划转
		TEmployeeProject newEmpProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, vo.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,vo.getNewDeptNo())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
		// hgw 2023-8-24 16:07:01 值为3，表示什么服务都没有，加提示语：项目档案，划转成功
		int isNoService = 0;
		if (Common.isNotNull(newEmpProject)
				&& Common.isNotNull(newEmpProject.getProjectStatus())
				&& newEmpProject.getProjectStatus().intValue() == CommonConstants.ONE_INT){
			//isSubtraction = true
			return R.failed("目标项目档案已减项，请复项后重新划转！");
		}
		//社保公积金派单处需要直接修改为最新的项目
		//社保预估库、缴费库、对比库、代理差额库，需要同步修改未结算（并且满足这个条件：数据 生成月≥此处划转起始月）的数据，已结算数据不变更；
		//划转,更新项目信息
		TEmployeeProject updateTEmployeeProject = tEmployeeProjectService.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard, vo.getEmpIdcard()).eq(TEmployeeProject::getDeptNo,vo.getOldDepartNo())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL).eq(TEmployeeProject::getProjectStatus,CommonConstants.ZERO_INT));
		if (Common.isNotNull(updateTEmployeeProject)) {

			if (updateTEmployeeProject.getSocialStatus() == CommonConstants.dingleDigitIntArray[1]
					&& vo.getChangeItems().indexOf(CommonConstants.ONE_STRING) >= CommonConstants.ZERO_INT) {
				return R.failed("人员在原项目中存在在途的社保，请先终止后，再进行划转");
			}
			if (updateTEmployeeProject.getFundStatus() == CommonConstants.dingleDigitIntArray[1]
					&& vo.getChangeItems().indexOf(CommonConstants.TWO_STRING) >= CommonConstants.ZERO_INT){
				return R.failed("人员在原项目中存在在途的公积金，请先终止后，再进行划转");
			}
			TSettleDomain tSettleDomain = tSettleDomainMapper.selectOne(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDepartNo, vo.getNewDeptNo())
					.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
					.eq(TSettleDomain::getStopFlag, CommonConstants.ZERO_STRING));
			if (Common.isEmpty(tSettleDomain)) {
				return R.failed("对应项目编码的项目已停止合作");
			}
			TEmployeeProject oldEmpProject = tEmployeeProjectService.getById(updateTEmployeeProject.getId());
			if (Common.isEmpty(newEmpProject)){
				newEmpProject = new TEmployeeProject();
				BeanUtil.copyProperties(oldEmpProject,newEmpProject);
				newEmpProject.setId(null);
				newEmpProject.setEmpNo(tEmployeeProjectService.getEmpNo(newEmpProject.getDeptNo()));
				newEmpProject.setDeptId(vo.getNewDeptId());
				newEmpProject.setDeptName(vo.getNewDeptName());
				newEmpProject.setDeptNo(vo.getNewDeptNo());
				newEmpProject.setUnitNo(vo.getNewUnitNo());
				newEmpProject.setUnitId(vo.getNewUnitId());
				newEmpProject.setUnitName(vo.getNewUnitName());
				newEmpProject.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
				newEmpProject.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
				newEmpProject.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
				newEmpProject.setInsuranceStatus(null);
				newEmpProject.setSocialStatus(null);
				newEmpProject.setSocialProvince(null);
				newEmpProject.setSocialCity(null);
				newEmpProject.setSocialTown(null);
				newEmpProject.setFundStatus(null);
				newEmpProject.setContractStatus(null);
				newEmpProject.setContractType(null);
			}
			updateTEmployeeProject.setDeptName(vo.getNewDeptName());
			updateTEmployeeProject.setDeptNo(vo.getNewDeptNo());
			updateTEmployeeProject.setDeptId(vo.getNewDeptId());
			updateTEmployeeProject.setUnitNo(vo.getNewUnitNo());
			updateTEmployeeProject.setUnitId(vo.getNewUnitId());
			updateTEmployeeProject.setUnitName(vo.getNewUnitName());
			updateTEmployeeProject.setBusinessPrimaryType(tSettleDomain.getBusinessPrimaryType());
			updateTEmployeeProject.setBusinessSecondType(tSettleDomain.getBusinessSecondType());
			updateTEmployeeProject.setBusinessThirdType(tSettleDomain.getBusinessThirdType());
			// 记录变更日志
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1], "", updateTEmployeeProject.getId(), oldEmpProject, updateTEmployeeProject);
			updateTEmployeeProject.setOdlDeptId(oldEmpProject.getDeptId());
			updateTEmployeeProject.setOldDeptNo(oldEmpProject.getDeptNo());

			UpdateSocialFoundVo updatesf = new UpdateSocialFoundVo();
			updatesf.setOldDeptId(updateTEmployeeProject.getOdlDeptId());
			updatesf.setEmpIdcard(updateTEmployeeProject.getEmpIdcard());
			updatesf.setSettleDomainCode(updateTEmployeeProject.getDeptNo());
			updatesf.setSettleDomainId(updateTEmployeeProject.getDeptId());
			updatesf.setSettleDomainName(updateTEmployeeProject.getDeptName());
			updatesf.setUnitId(updateTEmployeeProject.getUnitId());
			updatesf.setUnitName(updateTEmployeeProject.getUnitName());
			// 处理社保  目标项目档案已有项目档案不做处理
			if (vo.getChangeItems().indexOf(CommonConstants.ONE_STRING) >= CommonConstants.ZERO_INT) {
				if (Common.isEmpty(oldEmpProject.getSocialStatus())
						|| CommonConstants.ZERO_INT == oldEmpProject.getSocialStatus()){
					isNoService++;
					resStr.append("社保项不存在，无法划转! <br>");
				}else {
					if (Common.isEmpty(newEmpProject.getSocialStatus())
							|| CommonConstants.ZERO_INT == newEmpProject.getSocialStatus()
							|| CommonConstants.FOUR_INT == newEmpProject.getSocialStatus()){
						newEmpProject.setSocialStatus(oldEmpProject.getSocialStatus());
						newEmpProject.setSocialProvince(oldEmpProject.getSocialProvince());
						newEmpProject.setSocialCity(oldEmpProject.getSocialCity());
						newEmpProject.setSocialTown(oldEmpProject.getSocialTown());
						updatesf.setFlag(CommonConstants.ZERO_STRING);
						socialDaprUtils.updateSocialAndFoundInfo(updatesf);
						oldEmpProject.setSocialStatus(CommonConstants.ZERO_INT);
						oldEmpProject.setSocialProvince(null);
						oldEmpProject.setSocialCity(null);
						oldEmpProject.setSocialTown(null);
						resStr.append("社保划转成功! <br>");
					}else {
						resStr.append("目标项目档案存在社保数据，社保划转失败! <br>");
					}
				}
			}
			// 处理公积金 如果目标项目档案已存在公积金 不划转
			if (vo.getChangeItems().indexOf(CommonConstants.TWO_STRING) >= CommonConstants.ZERO_INT) {
				if (Common.isEmpty(oldEmpProject.getFundStatus())
						|| CommonConstants.ZERO_INT == oldEmpProject.getFundStatus()){
					isNoService++;
					resStr.append("公积金项不存在，无法划转! <br>");
				}else{
					if (Common.isEmpty(newEmpProject.getFundStatus())
							|| CommonConstants.ZERO_INT == newEmpProject.getFundStatus()
							|| CommonConstants.THREE_INT == newEmpProject.getFundStatus()){
						newEmpProject.setFundStatus(oldEmpProject.getFundStatus());
						updatesf.setFlag(CommonConstants.ONE_STRING);
						socialDaprUtils.updateSocialAndFoundInfo(updatesf);
						oldEmpProject.setFundStatus(CommonConstants.ZERO_INT);
						resStr.append("公积金划转成功! <br>");
					} else {
						resStr.append("目标项目档案存在公积金数据，公积金划转失败! <br>");
					}
				}
			}
			// 处理員工合同  目标 已有合同状态 不在处理合同划转
			if (vo.getChangeItems().indexOf(CommonConstants.ZERO_STRING) >= CommonConstants.ZERO_INT){
				if (Common.isEmpty(oldEmpProject.getContractStatus())
						|| CommonConstants.ZERO_INT == oldEmpProject.getContractStatus()){
					isNoService++;
					resStr.append("员工合同不存在，无法划转! <br>");
				}else {
					if (Common.isEmpty(newEmpProject.getContractStatus())
							|| CommonConstants.ZERO_INT == newEmpProject.getContractStatus()){
						newEmpProject.setContractStatus(oldEmpProject.getContractStatus());
						newEmpProject.setContractType(oldEmpProject.getContractType());
						// 合同同步划转---只划转在用合同 fxj 2023-03-06
						contractInfoMapper.updateContractChange(updateTEmployeeProject.getEmpIdcard(),updateTEmployeeProject.getDeptNo(),updateTEmployeeProject.getOldDeptNo());
						oldEmpProject.setContractStatus(CommonConstants.ZERO_INT);
						resStr.append("员工合同划转成功! <br>");
					}else {
						resStr.append("目标项目档案存在员工合同数据，员工合同划转失败! <br>");
					}
				}
			}
			if (isNoService == 3) {
				resStr.append("项目档案，划转成功! <br>");
			}
			// 变更老的项目档案
			tEmployeeProjectService.updateChangeById(oldEmpProject);
			//新增或变更新的项目档案
			tEmployeeProjectService.saveOrUpdate(newEmpProject);
			//同步减项老项目档案
			if (CommonConstants.ONE_STRING.equals(vo.getChangeType())){
				oldEmpProject.setIsLeaveEmployee(CommonConstants.ZERO_INT);
				R res  = tEmployeeProjectService.deleteEmpPro(oldEmpProject);
				resStr.append(res.getMsg());
			}
		}
		//保存变更记录
		saveChangeInfo(newEmpProject, updateTEmployeeProject);
		return R.ok(null,resStr.toString());
	}

	private void saveChangeInfo(TEmployeeProject newEmpProject, TEmployeeProject updateTEmployeeProject) {
		TEmpChangeInfo changeInfo= new TEmpChangeInfo();
		changeInfo.setProId(updateTEmployeeProject.getId());
		changeInfo.setEmpName(updateTEmployeeProject.getEmpName());
		changeInfo.setEmpIdcard(updateTEmployeeProject.getEmpIdcard());
		changeInfo.setOldDept(updateTEmployeeProject.getUnitName());
		changeInfo.setNewDept(newEmpProject.getUnitName());
		changeInfo.setOldSettle(updateTEmployeeProject.getDeptName());
		changeInfo.setNewSettle(newEmpProject.getDeptName());
		changeInfo.setUnsettleDeal(CommonConstants.ONE_STRING);
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(user)){
			changeInfo.setCreateBy(user.getId());
			changeInfo.setUpdateBy(user.getId());
			changeInfo.setCreateName(user.getNickname());
		}
		//保存档案划转记录
		this.save(changeInfo);
	}
}
