/*
 *    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.social.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.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.yifu.cloud.plus.v1.yifu.archives.constants.ArchivesConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeContractInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
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.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.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.CheckDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.social.constants.DispatchConstants;
import com.yifu.cloud.plus.v1.yifu.social.entity.*;
import com.yifu.cloud.plus.v1.yifu.social.mapper.*;
import com.yifu.cloud.plus.v1.yifu.social.service.TDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TForecastLibraryService;
import com.yifu.cloud.plus.v1.yifu.social.service.TIncomeDetailService;
import com.yifu.cloud.plus.v1.yifu.social.service.TIncomeService;
import com.yifu.cloud.plus.v1.yifu.social.util.ServiceUtil;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 派单信息记录表
 *
 * @author fxj
 * @date 2022-07-15 11:38:05
 */
@Log4j2
@RequiredArgsConstructor
@Service
public class TDispatchInfoServiceImpl extends ServiceImpl<TDispatchInfoMapper, TDispatchInfo> implements TDispatchInfoService {

	private final ArchivesDaprUtil archivesDaprUtil;

	private final TSocialFundInfoMapper socialFundMapper;

	private final SysBaseSetInfoMapper baseSetMapper;

	private final TSocialInfoMapper socialMapper;

	private final TProvidentFundMapper fundMapper;

	private final TAuditInfoMapper auditInfoMapper;

	@Autowired
	private CacheManager cacheManager;

	@Autowired
	private final CheckDaprUtil checkDaprUtil;

	private final TForecastLibraryService forecastLibraryService;

	private final TIncomeDetailService detailService;

	private final TIncomeService incomeService;

	/**
	 * 派单信息记录表简单分页查询
	 *
	 * @param tDispatchInfo 派单信息记录表
	 */
	@Override
	public IPage<TDispatchInfoPageVo> getTDispatchInfoPage(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		return baseMapper.getTDispatchInfoPage(page, tDispatchInfo);
	}

	/**
	 * 派单信息记录表简单分页查询
	 *
	 * @param tDispatchInfo 派单信息记录表
	 */
	@Override
	public IPage<TDispatchInfoPageVo> getTDispatchInfoPageAudit(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		return baseMapper.getTDispatchInfoPageAudit(page, tDispatchInfo);
	}

	/**
	 * 派单信息记录表批量导出
	 *
	 */
	@Override
	public void listExport(HttpServletResponse response, TDispatchInfoSearchVo searchVo) {
		String fileName = "派单批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchInfoExportVo> list = new ArrayList<>();
		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，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TDispatchInfoExportVo.class).includeColumnFiledNames(searchVo.getExportFields()).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = exportDispatch(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TDispatchInfoExportVo> util = new ExcelUtil<>(TDispatchInfoExportVo.class);
						for (TDispatchInfoExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet 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);
			}
		}
	}

	@Override
	public void listAuditExport(HttpServletResponse response, TDispatchInfoSearchVo searchVo) {
		String fileName = "派单审核导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchAuditExportVo> list = new ArrayList<>();
		long count = baseMapper.selectExportCount(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，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TDispatchAuditExportVo.class).includeColumnFiledNames(searchVo.getExportFields()).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = exportAuditDispatch(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TDispatchAuditExportVo> util = new ExcelUtil<>(TDispatchAuditExportVo.class);
						for (TDispatchAuditExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet 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);
			}
		}
	}

	@Override
	public List<TDispatchInfo> noPageDiy(TDispatchInfoSearchVo searchVo) {
		LambdaQueryWrapper<TDispatchInfo> wrapper = buildQueryWrapper(searchVo);
		List<String> idList;
		if (Common.isNotNull(searchVo.getIds())) {
			idList = Common.getList(searchVo.getIds());
			wrapper.in(TDispatchInfo::getId, idList);
		} else if (searchVo.getIdList() != null) {
			idList = searchVo.getIdList();
			wrapper.in(TDispatchInfo::getId, idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	private List<TDispatchInfoExportVo> exportDispatch(TDispatchInfoSearchVo searchVo) {
		if (Common.isNotNull(searchVo.getIds())) {
			List<String> idList = Common.getList(searchVo.getIds());
			searchVo.setIdList(idList);
		}
		return baseMapper.exportDispatch(searchVo);
	}

	private List<TDispatchAuditExportVo> exportAuditDispatch(TDispatchInfoSearchVo searchVo) {
		return baseMapper.exportAuditDispatch(searchVo);
	}

	private Long noPageCountDiy(TDispatchInfoSearchVo searchVo) {
		LambdaQueryWrapper<TDispatchInfo> wrapper = buildQueryWrapper(searchVo);
		List<String> idList;
		if (Common.isNotNull(searchVo.getIds())) {
			idList = Common.getList(searchVo.getIds());
			wrapper.in(TDispatchInfo::getId, idList);
		} else if (searchVo.getIdList() != null) {
			idList = searchVo.getIdList();
			wrapper.in(TDispatchInfo::getId, idList);
		}
		wrapper.eq(TDispatchInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL);
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TDispatchInfoSearchVo entity) {
		LambdaQueryWrapper<TDispatchInfo> wrapper = Wrappers.lambdaQuery();
		if (Common.isNotNull(entity.getCreateTimeStart())) {
			wrapper.ge(TDispatchInfo::getCreateTime, entity.getCreateTimeStart());
		}
		if (Common.isNotNull(entity.getCreateTimeEnd())) {
			wrapper.le(TDispatchInfo::getCreateTime, entity.getCreateTimeEnd());
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TDispatchInfo::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	public R<List<ErrorMessage>> importDiy(InputStream inputStream, String orderId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			R.failed(CommonConstants.USER_FAIL);
		}
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TDispatchImportVo> util1 = new ExcelUtil<>(TDispatchImportVo.class);
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TDispatchImportVo.class, new ReadListener<TDispatchImportVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TDispatchImportVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TDispatchImportVo 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());
					importTDispatchInfo(cachedDataList, errorMessageList,user,orderId);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}
	@Override
	public void importTDispatchInfo(List<TDispatchImportVo> excelVOList,
									List<ErrorMessage> errorMessageList,
									YifuUser user, String orderId) {
		if (!Common.isNotNull(excelVOList)){
			return;
		}
		Map<String,String> excelVOTemp = new HashMap<>();
		// 个性化校验逻辑
		List<String> idcards = new ArrayList<>();
		List<String> codes = new ArrayList<>();

		List<String> socialholds = new ArrayList<>();
		List<String> fundholds = new ArrayList<>();
		// 初始化参数
		initIdcardAndCode(excelVOList, idcards, codes, socialholds, fundholds);
		// 通过身份证和项目编码获取档案&项目档案&最新合同
		Map<String, DispatchEmpVo> empVoMap = getDispatchEmpVo(idcards, codes);
		// 通过身份证查询社保&公积金&社保公积金查询信息: 身份证维度唯一
		Map<String, TSocialFundInfo> socialFundMap = getSocialFundMap(idcards);
		// 获取项目编码数据 以供校验
		Map<String, ProjectSetInfoVo> projectVoMap = getProjectVoMap(codes);
		// 获取所有社保户和公积金户数据
		Map<String, SysBaseSetInfo> socialHoldMap = new HashMap<>();
		Map<String, SysBaseSetInfo> fundHoldMap = new HashMap<>();
		initHoldInfo(socialholds, fundholds, socialHoldMap, fundHoldMap);
		// 员工档案
		Map<String,EmpAddDispatchVo> empAddsMap = new HashMap<>();
		//员工合同
		Map<String,EmpContractDispatchVo> contractsMap = new HashMap<>();
		//员工项目档案
		Map<String,EmpProjectDispatchVo> projectsMap = new HashMap<>();
		//新增社保
		Map<String,TSocialInfo> socialsMap = new HashMap<>();
		//新增公积金
		Map<String,TProvidentFund> fundsMap = new HashMap<>();
		//新增派单信息
		Map<String,TDispatchInfo> dispatchMap = new HashMap<>();
		// 新增社保公积金查询
		Map<String,TSocialFundInfo> socialFundAddMap = new HashMap<>();
		DispatchEmpVo empVo;
		SysBaseSetInfo socialSet;
		SysBaseSetInfo fundSet;
		ProjectSetInfoVo setInfoVo = null;
		TSocialFundInfo socialFund;
		TDispatchImportVo excel;
		EmpDispatchAddVo addVo = new EmpDispatchAddVo();
		// 失败项派单
		boolean dispatchPart = false;
		// 兼职工伤
		boolean injury =false;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			dispatchPart = false;
			injury =false;
			empVo = null;
			excel = excelVOList.get(i);
			fundSet = fundHoldMap.get(excel.getProvidentHousehold());
			socialSet = socialHoldMap.get(excel.getSocialHousehold());
			socialFund = getSocialFund(socialFundMap,excel);
			setInfoVo = getSetInfoVo(projectVoMap,excel.getSettleDomainCode());
			if (Common.isNotNull(empVoMap)) {
				empVo = empVoMap.get(excel.getEmpIdcard());
			}
			if (Common.isNotNull(socialFund) 
					&& Common.isNotNull(socialFund.getSocialId()) 
					&& CommonConstants.FOUR_STRING.equals(socialFund.getSocialStatus())){
				// 部分失败
				dispatchPart = true;
			}
			if (Common.isNotNull(excel.getSocialHousehold())){
				if (Common.isNullOrZero(excel.getRecordBase())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_RECORD_BASE_NOT_EXIST)));
					excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
					continue;
				}
				if (Common.isEmpty(socialSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_HOLD_NOT_EXIST)));
					excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
					continue;
				}

				// 自定义 只有工伤数据 视为兼职工伤派单
				if (Common.isNotNull(excel) && CommonConstants.ONE_STRING.equals(excel.getPaymentType())){
					injury = Common.isEmpty(excel.getPensionStart())
							&& Common.isEmpty(excel.getMedicalStart())
							&& Common.isEmpty(excel.getBirthStart())
							&& Common.isEmpty(excel.getUnemployStart())
							&& Common.isEmpty(excel.getBigailmentStart())
							&& Common.isNotNull(excel.getWorkInjuryStart())
							&& (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(excel.getWorkInjuryCardinal())) < 0);
				}
				// 失败项社保派单 和已有派单户不一致
				if (dispatchPart && Common.isNotNull(socialFund)
						&& Common.isNotNull(socialFund.getSocialHouseholdName())
						&& Common.isNotNull(excel.getSocialHousehold())
						&& !socialFund.getSocialHouseholdName().equals(excel.getSocialHousehold())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_HOLD_NOT_SAME)));
					excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
					continue;
				}
				// 失败项重新派单的缴纳方式不一样
				if (dispatchPart && Common.isNotNull(socialFund)
						&& !socialFund.getPaymentType().equals(excel.getPaymentType())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_PAYMENT_TYPE_NOT_SAME)));
					excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
					continue;
				}
			}
			if (Common.isNotNull(excel.getProvidentHousehold())){
				if (Common.isEmpty(fundSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_HOLD_NOT_EXIST)));
					excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
					continue;
				}
			}
			if (Common.isNotNull(dispatchMap) && Common.isNotNull(dispatchMap.get(excel.getEmpIdcard()))){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EXIST)));
				excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
				continue;
			}
			// 数据合法情况
			if (validImport(errorMessageList, excel,setInfoVo,socialFund,empVo,socialSet,fundSet)) {
				excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
				continue;
			}
			// 是否可以派单： 派单状态、兼职工伤处理
			if (validDdispatchStatus(errorMessageList, socialFund, excel)) {
				excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
				continue;
			}
			// 初始化新增信息：档案、项目档案、员工合同
			initAddInfo(empAddsMap, contractsMap, projectsMap, empVo, excel,user,setInfoVo,socialSet);
			// 新增社保
			initSocialAddInfo(socialsMap, empVo, socialSet, excel,socialFundMap,dispatchPart);
			// 新增公积金
			if (initFundAddInfo(errorMessageList, fundsMap, empVo, fundSet, excel)){
				excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
				continue;
			}
			// 新增派单信息
			excel.setOrderId(orderId);
			initDispatchAddInfo(user, dispatchMap, empVo, socialSet, fundSet, excel,socialFund,injury);
			// 变更社保公积金查询
			initSocialFundAddInfo(socialFundAddMap, empVo, socialSet, fundSet, setInfoVo, socialFund, excel);
		}
		addVo.setEmpAddsMap(empAddsMap);
		addVo.setContractsMap(contractsMap);
		addVo.setProjectsMap(projectsMap);
		R<EmpDispatchAddVo> res = archivesDaprUtil.addDispatchInfo(addVo);
		// 开始插入各种数据了
		insertAllInfo(excelVOList, errorMessageList, res,socialsMap,fundsMap,socialFundAddMap,dispatchMap,excelVOTemp,dispatchPart,injury);
		// 清理map list 等数据
		Common.clear(excelVOList);
		Common.clear(empAddsMap);
		Common.clear(contractsMap);
		Common.clear(projectsMap);
		Common.clear(empVoMap);
		Common.clear(idcards);
		Common.clear(codes);
		Common.clear(socialholds);
		Common.clear(fundholds);
		Common.clear(socialsMap);
		Common.clear(fundsMap);
		Common.clear(dispatchMap);
		Common.clear(socialFundAddMap);
		Common.clear(socialHoldMap);
		Common.clear(fundHoldMap);
		Common.clear(excelVOTemp);
	}
	private ProjectSetInfoVo getSetInfoVo(Map<String, ProjectSetInfoVo> projectVoMap, String code) {
		return Common.isEmpty(projectVoMap)?null:projectVoMap.get(code);
	}

	private TSocialFundInfo getSocialFund(Map<String, TSocialFundInfo> socialFundMap, TDispatchImportVo excel) {
		return Common.isEmpty(socialFundMap)?null:socialFundMap.get(excel.getEmpIdcard());
	}

	private void insertAllInfo(List<TDispatchImportVo> excelVOList,
							   List<ErrorMessage> errorMessageList,
							   R<EmpDispatchAddVo> res,
							   Map<String, TSocialInfo> socialsMap,
							   Map<String, TProvidentFund> fundsMap,
							   Map<String, TSocialFundInfo> socialFundAddMap,
							   Map<String, TDispatchInfo> dispatchMap,
							   Map<String, String> excelVOTemp,
							   boolean dispatchPart, boolean injury) {
		Map<String, EmpAddDispatchVo> empAddsMap = null;
		Map<String, EmpContractDispatchVo> contractsMap = null;
		Map<String, EmpProjectDispatchVo> projectsMap = null;
		TDispatchImportVo excel;
		EmpContractDispatchVo contract;
		EmpProjectDispatchVo project;
		EmpAddDispatchVo emp = null;
		TSocialInfo social;
		TProvidentFund fund;
		TSocialFundInfo socialFund = null;
		TDispatchInfo dispatch = null;
		if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
			empAddsMap =  res.getData().getEmpAddsMap();
			contractsMap = res.getData().getContractsMap();
			projectsMap = res.getData().getProjectsMap();
		}
		for (int i = 0; i < excelVOList.size(); i++) {
			contract = null;
			social = null;
			project = null;
			fund = null;
			excel = excelVOList.get(i);
			if (Common.isNotNull(excelVOTemp) && Common.isNotNull(excelVOTemp.get(excel.getRowIndex().toString()))){
				continue;
			}
			// 验证档案是否插入成功  如果MAP 无数据直接不处理
			if (Common.isNotNull(empAddsMap)){
				emp = empAddsMap.get(excel.getEmpIdcard());
				if (Common.isNotNull(emp) && Common.isEmpty(emp.getId())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_ADD_EMP_ERROR)));
					continue;
				}
			}
			// 验证合同是否插入成功
			if (Common.isNotNull(contractsMap)){
				contract = contractsMap.get(excel.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+excel.getSettleDomainCode());
				if (Common.isNotNull(contract) && Common.isEmpty(contract.getId())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_ADD_CONTRACT_ERROR)));
					continue;
				}
			}
			// 验证项目档案是否插入成功
			if (Common.isNotNull(projectsMap)){
				project = projectsMap.get(excel.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+excel.getSettleDomainCode());
				if (Common.isNotNull(project) && Common.isEmpty(project.getId())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_ADD_PROJECT_ERROR)));
					continue;
				}
			}
			try {
				// 插入社保信息并封装社保公积金查询信息
				if (Common.isNotNull(socialsMap)){
					social = socialsMap.get(excel.getEmpIdcard());
					insertSocial(emp, social,project);
				}
				//  插入公积金信息并封装社保公积金查询信息
				if (Common.isNotNull(fundsMap)){
					fund = fundsMap.get(excel.getEmpIdcard());
					insertFund(emp, fund,project);
				}
				//  插入派单信息
				if (Common.isNotNull(dispatchMap)){
					dispatch = dispatchMap.get(excel.getEmpIdcard());
					if (Common.isNotNull(dispatch)){
						if (Common.isNotNull(social)){
							dispatch.setSocialId(social.getId());
							dispatch.setSocialHouseholdName(social.getSocialHouseholdName());
						}
						if (Common.isNotNull(fund)){
							dispatch.setFundId(fund.getId());
							dispatch.setProvidentHouseholdName(fund.getProvidentHouseholdName());
						}
						if (Common.isNotNull(contract)){
							dispatch.setContractId(contract.getId());
						}
						if (Common.isNotNull(project)){
							dispatch.setEmpNo(project.getEmpNo());
						}
					}
					dispatch.setFirstBuyMonthSocial(getFirstBuyMonthSocial(social));
					insertDispatch(emp, dispatch);
				}
				//  插入或更新社保公积金查询信息  大病在封装社保的时候已经算了 大病技术和金额了
				if (Common.isNotNull(socialFundAddMap)){
					socialFund = socialFundAddMap.get(excel.getEmpIdcard());
					if (Common.isNotNull(socialFund) && Common.isNotNull(dispatch)){
						socialFund.setDispatchId(dispatch.getId());
					}
					initSocialFundAndInsert(emp, social, fund, socialFund,project,dispatchPart,injury);
				}
				// 生成预付数据
				if (Common.isNotNull(socialFund) && Common.isNotNull(socialFund.getId())){
					forecastLibraryService.updateForecastLibaryByDispatch(socialFund);
				}
				// 同步更新人员档案和项目档案的社保公积金状态
				updateDocSocialFund(social, fund, socialFund);
			}catch (Exception e){
				log.error("派单新增异常：", e);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "派单新增异常："+e.getMessage()));
			}
		}
		// 清理map list 等数据
		Common.clear(empAddsMap);
		Common.clear(contractsMap);
		Common.clear(projectsMap);
	}

	private void updateDocSocialFund(TSocialInfo social, TProvidentFund fund, TSocialFundInfo socialFund) {
		UpProjectSocialFundVo vo = new UpProjectSocialFundVo();
		if (Common.isNotNull(social)){
			vo.setSocialStatus(CommonConstants.ONE_STRING);
			vo.setDepartNo(socialFund.getSettleDomainCode());
		}
		if (Common.isNotNull(fund)){
			vo.setFundStatus(CommonConstants.ONE_STRING);
			vo.setDepartNo(socialFund.getSettleDomainCodeFund());
		}
		// 有一个办理成功重新派单的 即为办理中
		boolean flagTemp = Common.isNotNull(socialFund) && Common.isNotNull(socialFund.getSocialId())
				&& (CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())
				|| CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())
				|| CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())
				|| CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())
				|| CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())
				|| (CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(socialFund.getIsIllness())))
				&& !(CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())
				&& CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())
				&& CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())
				&& CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())
				&& CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())
				&& (
				(CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
						&& CommonConstants.ZERO_STRING.equals(socialFund.getIsIllness()))
				||(CommonConstants.ONE_STRING.equals(socialFund.getIsIllness()))
				));
		if (Common.isNotNull(socialFund) && flagTemp){
			vo.setSocialStatus(CommonConstants.TWO_STRING);
		}

		vo.setEmpIdCard(socialFund.getEmpIdcard());
		R<Boolean> resUp = archivesDaprUtil.updateProjectSocialFund(vo);
		if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()){
			ServiceUtil.runTimeExceptionDiy(DispatchConstants.DISPATCH_SYN_DOC_EXE);
		}
	}

	private void insertSocial(EmpAddDispatchVo emp, TSocialInfo social, EmpProjectDispatchVo project) {
		if (Common.isNotNull(social) && Common.isEmpty(social.getId())){
			if (Common.isNotNull(emp)){
				social.setEmpId(emp.getId());
			}
			if (Common.isNotNull(project)){
				social.setEmpNo(project.getEmpNo());
			}
			socialMapper.insert(social);
		}
	}

	private void insertFund(EmpAddDispatchVo emp, TProvidentFund fund, EmpProjectDispatchVo project) {
		if (Common.isNotNull(fund)  && Common.isEmpty(fund.getId())){
			if (Common.isNotNull(emp)){
				fund.setEmpId(emp.getId());
			}
			if (Common.isNotNull(project)){
				fund.setEmpNo(project.getEmpNo());
			}
			fundMapper.insert(fund);
		}
	}

	private void insertDispatch(EmpAddDispatchVo emp, TDispatchInfo dispatch) {
		if (Common.isNotNull(dispatch)){
			if (Common.isNotNull(emp)){
				dispatch.setEmpId(emp.getId());
			}
			dispatch.setCreateTime(LocalDateTime.now());
			baseMapper.insert(dispatch);
		}
	}

	private void initSocialFundAndInsert(EmpAddDispatchVo emp,
										 TSocialInfo social,
										 TProvidentFund fund,
										 TSocialFundInfo socialFund,
										 EmpProjectDispatchVo project,
										 boolean dispatchPart,boolean injury) {
		if (Common.isNotNull(socialFund)){
			if (Common.isNotNull(project)){
				socialFund.setEmpNo(project.getEmpCode());
			}
			if (Common.isNotNull(emp)){
				socialFund.setEmpId(emp.getId());
				socialFund.setEmpName(emp.getEmpName());
				socialFund.setEmpIdcard(emp.getEmpIdcard());
				socialFund.setEmpType(emp.getEmpNatrue());
			}
			if (Common.isNotNull(social)){
				socialFund.setSocialStartDate(social.getSocialStartDate());
				socialFund.setSocialReduceDate(null);
				socialFund.setSocialReduceStatus(CommonConstants.ONE_STRING_NEGATE);
				socialFund.setSocialId(social.getId());
				if (Common.isEmpty(socialFund.getFirstBuyMonthSocial())){
					socialFund.setFirstBuyMonthSocial(getFirstBuyMonthSocial(social));
				}
				if (!CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
						&& CommonConstants.ZERO_STRING.equals(socialFund.getIsIllness())
						&& !dispatchPart){
					socialFund.setUnitBigailmentMoney(social.getUnitBigailmentMoney());
					socialFund.setPersonalBigailmentMoney(social.getPersonalBigailmentMoney());
				}
				// 处理部分失败项派单的 基数 比例 金额，再办理成功的时候才更新过来  顺序不要变 后面有合计
				if (!CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle()) && !dispatchPart){
					socialFund.setUnitPensionCardinal(social.getUnitPensionCardinal());
					socialFund.setPersonalPensionCardinal(social.getPersonalPensionCardinal());
					socialFund.setUnitPensionPer(social.getUnitPensionPer());
					socialFund.setPersonalPensionPer(social.getPersonalPensionPer());
					socialFund.setUnitPersionMoney(BigDecimalUtils.safeMultiply(social.getUnitPensionCardinal(), social.getUnitPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setPersonalPersionMoney(BigDecimalUtils.safeMultiply(social.getPersonalPensionCardinal(), social.getPersonalPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setPensionHandle(social.getPensionHandle());
					socialFund.setPensionStart(social.getPensionStart());
				}
				if (!CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle()) && !dispatchPart){
					socialFund.setUnitMedicalCardinal(social.getUnitMedicalCardinal());
					socialFund.setPersonalMedicalCardinal(social.getPersonalMedicalCardinal());
					socialFund.setUnitMedicalPer(social.getUnitMedicalPer());
					socialFund.setPersonalMedicalPer(social.getPersonalMedicalPer());
					socialFund.setUnitMedicalMoney(BigDecimalUtils.safeMultiply(social.getUnitMedicalCardinal(), social.getUnitMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setPersonalMedicalMoney(BigDecimalUtils.safeMultiply(social.getPersonalMedicalCardinal(), social.getPersonalMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setMedicalHandle(social.getMedicalHandle());
					socialFund.setMedicalStart(social.getMedicalStart());
				}

				if (!CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle()) && !dispatchPart){
					socialFund.setUnitUnemploymentCardinal(social.getUnitUnemploymentCardinal());
					socialFund.setPersonalUnemploymentCardinal(social.getPersonalUnemploymentCardinal());
					socialFund.setPersonalUnemploymentPer(social.getPersonalUnemploymentPer());
					socialFund.setUnitUnemploymentPer(social.getUnitUnemploymentPer());
					socialFund.setUnitUnemploymentMoney(BigDecimalUtils.safeMultiply(social.getUnitUnemploymentCardinal(), social.getUnitUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setPersonalUnemploymentMoney(BigDecimalUtils.safeMultiply(social.getPersonalUnemploymentCardinal(), social.getPersonalUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setUnemployHandle(social.getUnemployHandle());
					socialFund.setUnemployStart(social.getUnemployStart());
				}
				if (!CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
						&& CommonConstants.ZERO_STRING.equals(social.getIsIllness()) && !dispatchPart){
					socialFund.setUnitBigailmentCardinal(social.getUnitBigailmentCardinal());
					socialFund.setPersonalBigailmentCardinal(social.getPersonalBigailmentCardinal());
					socialFund.setUnitBigailmentPer(social.getUnitBigailmentPer());
					socialFund.setPersonalBigailmentPer(social.getPersonalBigailmentPer());
					socialFund.setUnitBigailmentMoney(social.getUnitBigailmentMoney());
					socialFund.setPersonalBigailmentMoney(social.getPersonalBigailmentMoney());
					socialFund.setBigailmentHandle(social.getBigailmentHandle());
					socialFund.setBigailmentStart(social.getBigailmentStart());
				}
				if (!CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle()) && !dispatchPart){
					socialFund.setUnitWorkInjuryCardinal(social.getUnitWorkInjuryCardinal());
					socialFund.setUnitWorkUnjuryPer(social.getUnitWorkUnjuryPer());
					socialFund.setUnitInjuryMoney(BigDecimalUtils.safeMultiply(social.getUnitWorkInjuryCardinal(), social.getUnitWorkUnjuryPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setWorkInjuryHandle(social.getWorkInjuryHandle());
					socialFund.setWorkInjuryStart(social.getWorkInjuryStart());
				}
				if (!CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle()) && !dispatchPart){
					socialFund.setUnitBirthCardinal(social.getUnitBirthCardinal());
					socialFund.setUnitBirthPer(social.getUnitBirthPer());
					socialFund.setUnitBirthMoney(BigDecimalUtils.safeMultiply(social.getUnitBirthCardinal(), social.getUnitBirthPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
					socialFund.setBirthHandle(social.getBirthHandle());
					socialFund.setBirthStart(social.getBirthStart());
				}
				socialFund.setCanOverpay(social.getCanOverpay());
				socialFund.setOverpayNumber(social.getOverpayNumber());
				socialFund.setHaveThisMonth(social.getHaveThisMonth());
				socialFund.setInsuranceBigailment(social.getInsuranceBigailment());
				socialFund.setInsuranceBirth(social.getInsuranceBirth());
				socialFund.setInsuranceInjury(social.getInsuranceInjury());
				socialFund.setInsuranceMedical(social.getInsuranceMedical());
				socialFund.setInsurancePension(social.getInsurancePension());
				socialFund.setInsuranceUnemployment(social.getInsuranceUnemployment());
				socialFund.setLatestCardinality(social.getInsuranceIsLatestCardinality());
				socialFund.setIsIllness(social.getIsIllness());
				socialFund.setCollectType(social.getCollectType());
				socialFund.setCollectMoth(social.getCollectMoth());
				socialFund.setValueType(social.getValueType());
				socialFund.setIsChargePersonal(social.getIsChargePersonal());
				socialFund.setRecordBase(social.getRecordBase());
				socialFund.setTrustRemark(social.getTrustRemark());
				socialFund.setPaymentType(social.getPaymentType());




				socialFund.setUnitSocialSum(BigDecimalUtils.safeAdd(socialFund.getUnitPersionMoney()
						, socialFund.getUnitMedicalMoney(), socialFund.getUnitBirthMoney()
						, socialFund.getUnitInjuryMoney()
						, socialFund.getUnitUnemploymentMoney()
						, socialFund.getUnitBigailmentMoney()));
				socialFund.setPersonalSocialSum(BigDecimalUtils.safeAdd(socialFund.getPersonalBigailmentMoney()
						, socialFund.getPersonalPersionMoney()
						, socialFund.getPersonalMedicalMoney()
						, socialFund.getPersonalUnemploymentMoney()));
			}
			if (Common.isNotNull(fund)){
				socialFund.setFundId(fund.getId());
				socialFund.setUnitProvidengCardinal(fund.getUnitProvidengCardinal());
				socialFund.setUnitProvidentPer(fund.getUnitProvidentPer());
				socialFund.setPersonalProvidentCardinal(fund.getPersonalProvidentCardinal());
				socialFund.setPersonalProvidentPer(fund.getPersonalProvidentPer());
				socialFund.setProvidentStart(fund.getProvidentStart());
				socialFund.setFundPayPoint(fund.getFundPayPoint());
				socialFund.setTrustRemarkFund(fund.getTrustRemark());
				socialFund.setCanOverpayFund(fund.getCanOverpay());
				socialFund.setOverpayNumberFund(fund.getOverpayNumber());
				if (Common.isEmpty(socialFund.getFirstBuyMothFund())){
					socialFund.setFirstBuyMothFund(fund.getProvidentStart());
				}
				socialFund.setHaveThisMonthFund(fund.getHaveThisMonth());
				// 设置公积金信息派增 派减状态
				socialFund.setLatestCardinalityFund(fund.getInsuranceIsLatestCardinality());
				socialFund.setFundReduceDate(null);
				socialFund.setFundReduceStatus(CommonConstants.ONE_STRING_NEGATE);
				//单边小数点处理逻辑
				if (Common.isNotNull(fund.getFundPayPoint())){
					socialFund.setUnitFundSum(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(fund.getUnitProvidengCardinal(), fund.getUnitProvidentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())),Integer.valueOf(fund.getFundPayPoint())));
					socialFund.setPersonalFundSum(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(fund.getPersonalProvidentCardinal(), fund.getPersonalProvidentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())),Integer.valueOf(fund.getFundPayPoint())));
				}
			}
			if (injury){
				socialFund.setUnitPensionCardinal(null);
				socialFund.setUnitPersionMoney(null);
				socialFund.setUnitPensionPer(null);
				socialFund.setPersonalPensionCardinal(null);
				socialFund.setPersonalPensionPer(null);
				socialFund.setPersonalPersionMoney(null);

				socialFund.setUnitMedicalCardinal(null);
				socialFund.setUnitMedicalPer(null);
				socialFund.setUnitMedicalMoney(null);
				socialFund.setPersonalMedicalCardinal(null);
				socialFund.setPersonalMedicalPer(null);
				socialFund.setPersonalMedicalMoney(null);

				socialFund.setUnitUnemploymentCardinal(null);
				socialFund.setUnitUnemploymentPer(null);
				socialFund.setUnitUnemploymentMoney(null);
				socialFund.setPersonalUnemploymentCardinal(null);
				socialFund.setPersonalUnemploymentPer(null);
				socialFund.setPersonalUnemploymentMoney(null);

				socialFund.setUnitBirthCardinal(null);
				socialFund.setUnitBirthPer(null);
				socialFund.setUnitBirthMoney(null);

				socialFund.setUnitBigailmentCardinal(null);
				socialFund.setUnitBigailmentPer(null);
				socialFund.setUnitBigailmentMoney(null);
				socialFund.setPersonalBigailmentCardinal(null);
				socialFund.setPersonalBigailmentPer(null);
				socialFund.setPersonalBigailmentMoney(null);

				socialFund.setSocialStartDate(social.getWorkInjuryStart());
			}
			if (Common.isNotNull(socialFund.getId())){
				socialFundMapper.updateById(socialFund);
			}else {
				socialFundMapper.insert(socialFund);
			}
		}
	}

	/**
	 * @Author fxj
	 * @Description 获取首次购买月份
	 * @Date 14:12 2022/8/17
	 * @Param
	 * @return
	**/
	private Date getFirstBuyMonthSocial(TSocialInfo social) {
		if (Common.isEmpty(social) || Common.isEmpty(social.getSocialStartDate())){
			return null;
		}
		if (Common.isNotNull(social.getPensionStart()) && social.getPensionStart().after(social.getSocialStartDate())){
			return social.getPensionStart();
		}
		if (Common.isNotNull(social.getMedicalStart()) && social.getMedicalStart().after(social.getSocialStartDate())){
			return social.getMedicalStart();
		}
		if (Common.isNotNull(social.getBirthStart()) && social.getBirthStart().after(social.getSocialStartDate())){
			return social.getBirthStart();
		}
		if (Common.isNotNull(social.getUnemployStart()) && social.getUnemployStart().after(social.getSocialStartDate())){
			return social.getUnemployStart();
		}
		if (Common.isNotNull(social.getWorkInjuryStart()) && social.getWorkInjuryStart().after(social.getSocialStartDate())){
			return social.getWorkInjuryStart();
		}
		if (Common.isNotNull(social.getBigailmentStart()) && social.getBigailmentStart().after(social.getSocialStartDate())){
			return social.getPensionStart();
		}
		return social.getSocialStartDate();
	}

	private void initSocialFundAddInfo(Map<String, TSocialFundInfo> socialFundAddMap,
									   DispatchEmpVo empVo,
									   SysBaseSetInfo socialSet,
									   SysBaseSetInfo fundSet,
									   ProjectSetInfoVo setInfoVo,
									   TSocialFundInfo socialFund,
									   TDispatchImportVo excel) {
		if (Common.isEmpty(socialFund)){
			socialFund = new TSocialFundInfo();
			if (Common.isNotNull(empVo)){
				socialFund.setEmpNo(empVo.getEmpNo());
				socialFund.setEmpName(empVo.getEmpName());
				socialFund.setEmpIdcard(empVo.getEmpIdcard());
				socialFund.setEmpId(empVo.getId());
				socialFund.setEmpType(excel.getEmpType());
			}
		}
		// 按社保公积金户判断具体封装那些信息，如果社保或公积金新增失败，后面就不会去更新或插入社保公积金查询了
		if (Common.isNotNull(setInfoVo)){
			if (Common.isNotNull(excel.getSocialHousehold())){
				socialFund.setSettleDomain(setInfoVo.getId());
				socialFund.setSettleDomainName(setInfoVo.getDepartName());
				socialFund.setSettleDomainCode(setInfoVo.getDepartNo());
				socialFund.setSettleDomainFund(setInfoVo.getId());
				socialFund.setSettleDomainNameFund(setInfoVo.getDepartName());
				socialFund.setSettleDomainCodeFund(setInfoVo.getDepartNo());
				socialFund.setUnitName(setInfoVo.getCustomerName());
				socialFund.setUnitId(setInfoVo.getCustomerId());
				socialFund.setUnitIdFund(setInfoVo.getCustomerId());
				socialFund.setUnitNameFund(setInfoVo.getCustomerName());
				socialFund.setSocialStatus(CommonConstants.ZERO_STRING);
				socialFund.setSocialAddStatus(CommonConstants.ZERO_STRING);
				socialFund.setSocialReduceStatus(CommonConstants.ONE_STRING_NEGATE);
				socialFund.setSocialReduceDate(null);
				socialFund.setSocialStartDate(excel.getPensionStart());
				if (Common.isNotNull(socialSet)){
					socialFund.setSocialHousehold(socialSet.getDepartId());
					socialFund.setSocialHouseholdName(socialSet.getDepartName());
					socialFund.setSocialProvince(Common.isNotNullToStr(socialSet.getProvince()));
					socialFund.setSocialCity(Common.isNotNullToStr(socialSet.getCity()));
					socialFund.setSocialTown(Common.isNotNullToStr(socialSet.getTown()));
					socialFund.setLowerLimit(socialSet.getLowerLimit());
					socialFund.setUpperLimit(socialSet.getUpperLimit());
					socialFund.setPayPolicy(socialSet.getPayPolicy());
					socialFund.setLatestCardinality(socialSet.getInsuranceIsLatestCardinality());
				}
			}
			if (Common.isNotNull(excel.getProvidentHousehold())){
				socialFund.setSettleDomainFund(setInfoVo.getId());
				socialFund.setSettleDomainNameFund(setInfoVo.getDepartName());
				socialFund.setSettleDomainCodeFund(setInfoVo.getDepartNo());
				socialFund.setUnitNameFund(setInfoVo.getCustomerName());
				socialFund.setUnitIdFund(setInfoVo.getCustomerId());
				socialFund.setFundStatus(CommonConstants.ZERO_STRING);
				socialFund.setFundAddStatus(CommonConstants.ZERO_STRING);
				socialFund.setProvidentStart(excel.getProvidentStart());
				socialFund.setFundReduceStatus(CommonConstants.ONE_STRING_NEGATE);
				socialFund.setFundReduceDate(null);
				if (Common.isNotNull(fundSet)){
					socialFund.setProvidentHousehold(fundSet.getDepartId());
					socialFund.setProvidentHouseholdName(fundSet.getDepartName());
					socialFund.setFundProvince(Common.isNotNullToStr(fundSet.getProvince()));
					socialFund.setFundCity(Common.isNotNullToStr(fundSet.getCity()));
					socialFund.setFundTown(Common.isNotNullToStr(fundSet.getTown()));
					socialFund.setLowerLimitFund(fundSet.getLowerLimit());
					socialFund.setUpperLimitFund(fundSet.getUpperLimit());
					socialFund.setPayPolicyFund(fundSet.getPayPolicy());
					socialFund.setFundPayPoint(Common.isNotNullToStr(fundSet.getFundPayPoint()));
					socialFund.setLatestCardinalityFund(fundSet.getInsuranceIsLatestCardinality());
				}
			}

		}
		socialFundAddMap.put(excel.getEmpIdcard(), socialFund);
	}

	private Map<String, ProjectSetInfoVo> getProjectVoMap(List<String> codes) {
		R<SetInfoVo> res = archivesDaprUtil.getSetInfoByCodes(codes);
		if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
			return res.getData().getProjectSetInfoVoMap();
		}
		return new HashMap<>();
	}
	/**
	 * @param
	 * @Description: 获取 申请编码
	 * @Author: fxj
	 * @Date: 2022-08-01 15:01
	 * @return: java.lang.String
	 **/
	private synchronized String getApplyCode() {
		String nowDay = DateUtil.getThisDay();
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_DISPATCH_CODE);
		Object nowNumObj = null;
		int nowNums = 1;
		if (Common.isNotNull(cache)){
			nowNumObj = null==nowDay?null:cache.get(nowDay);
			if (Common.isNotNull(nowNumObj)) {
				SimpleValueWrapper value = (SimpleValueWrapper) nowNumObj;
				if (Common.isNotNull(value)){
					nowNums = (Integer) value.get() + 1;
				}
			} else {
				String code = null;
				try {
					code = baseMapper.getMaxDispatchCode();
					nowNums = Integer.parseInt(code) + 1;
				} catch (NumberFormatException e) {
					log.error("获取申请编码当日最大编码时出错：" + code);
					nowNums = 1;
				}
			}
			cache.put(nowDay, nowNums);
		}
		return "PD" + nowDay + this.getFourNum(String.valueOf(nowNums));
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取四位字符型数字
	 * @Author: fxj
	 **/
	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;
	}
		private void initDispatchAddInfo(YifuUser user,
										 Map<String, TDispatchInfo> dispatchMap,
										 DispatchEmpVo empVo,
										 SysBaseSetInfo socialSet,
										 SysBaseSetInfo fundSet,
										 TDispatchImportVo excel,
										 TSocialFundInfo socialFund,
										 boolean injury) {
		TDispatchInfo dispatch = new TDispatchInfo();
		// 初始化派单项
		dispatch.setOrderId(excel.getOrderId());
		initAddHandleItem(excel, socialFund,dispatch,socialSet,injury);
		dispatch.setOrganName(user.getDeptName());
		dispatch.setCreateBy(user.getId());
		dispatch.setCreateTime(LocalDateTime.now());
		dispatch.setContractSubName(excel.getContractSubName());
		dispatch.setContractName(excel.getContractName());
		dispatch.setEmpIdcard(excel.getEmpIdcard());
		dispatch.setEmpName(excel.getEmpName());
		dispatch.setEmpNational(excel.getEmpNational());
		dispatch.setEmpType(excel.getEmpType());
		dispatch.setTryPeriod(excel.getTryPeriod());
		dispatch.setEmpMobile(excel.getEmpMobile());
		dispatch.setType(CommonConstants.ZERO_STRING);
		dispatch.setCurrentOperator(user.getNickname());
		dispatch.setTrustRemark(excel.getTrustRemark());
		dispatch.setBelongUnitName(excel.getCustomerName());
		dispatch.setBelongUnit(excel.getCustomerId());
		dispatch.setSettleDomainName(excel.getDepartName());
		dispatch.setSettleDomainCode(excel.getSettleDomainCode());
		dispatch.setSettleDomain(excel.getSettleDomainId());
		if (Common.isNotNull(excel.getSocialHousehold())){
			dispatch.setSocialHandleStatus(CommonConstants.ZERO_STRING);
		}
		if (Common.isNotNull(excel.getProvidentHousehold())){
			dispatch.setFundHandleStatus(CommonConstants.ZERO_STRING);
		}
		if (Common.isNotNull(socialSet)){
			dispatch.setSocialProvince(Common.isNotNullToStr(socialSet.getProvince()));
			dispatch.setSocialCity(Common.isNotNullToStr(socialSet.getCity()));
			dispatch.setSocialTown(Common.isNotNullToStr(socialSet.getTown()));
		}
		if (Common.isNotNull(fundSet)){
			dispatch.setFundProvince(Common.isNotNullToStr(fundSet.getProvince()));
			dispatch.setFundCity(Common.isNotNullToStr(fundSet.getCity()));
			dispatch.setFundTown(Common.isNotNullToStr(fundSet.getTown()));
		}
		// 默认待审核
		dispatch.setStatus(CommonConstants.ONE_STRING);
		dispatch.setDeleteFlag(CommonConstants.ZERO_STRING);
		// 封装项目客户信息
		dispatch.setBelongUnit(excel.getCustomerId());
		dispatch.setBelongUnitName(excel.getCustomerName());
		dispatch.setEducationName(excel.getEducationName());
		dispatch.setIdCardProvince(excel.getIdCardProvince());
		dispatch.setIdCardCity(excel.getIdCardCity());
		dispatch.setIdCardTown(excel.getIdCardTown());
		dispatch.setIdCardAddress(excel.getIdCardAddress());
		// 封装合同信息 默认取值派单的
		dispatch.setContractStart(excel.getContractStart());
		dispatch.setContractEnd(excel.getContractEnd());
		dispatch.setContractTerm(excel.getContractTerm());
		dispatch.setContractType(excel.getContractType());
		dispatch.setWorkingHours(excel.getWorkingHours());
		dispatch.setEmpRegisType(excel.getEmpRegisType());
		dispatch.setPost(excel.getPost());

		// 封装客户信息
		if (Common.isNotNull(empVo)){
			dispatch.setEmpId(empVo.getId());
			dispatch.setEmpNo(empVo.getEmpNo());
			dispatch.setEmpName(empVo.getEmpName());
			if (Common.isEmpty(dispatch.getEmpRegisType())){
				dispatch.setEmpRegisType(empVo.getEmpRegisType());
			}
			if (Common.isNotNull(dispatch.getPost())){
				dispatch.setPost(empVo.getPost());
			}
			// 封装合同信息 如果有合同取值实际合同信息
			if (Common.isNotNull(empVo.getContractStart())){
				dispatch.setContractStart(empVo.getContractStart());
				dispatch.setContractEnd(empVo.getContractEnd());
				dispatch.setContractTerm(empVo.getContractTerm());
				dispatch.setContractType(empVo.getContractType());
			}
			dispatch.setFileProvince(empVo.getFileProvince());
			dispatch.setFileCity(empVo.getFileCity());
			dispatch.setFileTown(empVo.getFileTown());
			dispatch.setContractId(empVo.getContractId());
			if (Common.isNotNull(empVo.getEmpNatrue())){
				dispatch.setEmpType(empVo.getEmpNatrue());
			}
			if (Common.isNotNull(empVo.getIdProvince())){
				dispatch.setIdCardProvince(Common.isNotNullToStr(empVo.getIdProvince()));
				dispatch.setIdCardCity(Common.isNotNullToStr(empVo.getIdCity()));
				dispatch.setIdCardTown(Common.isNotNullToStr(empVo.getIdTown()));
			}

		}
		// 生成申请编码
		dispatch.setApplyNo(getApplyCode());
		dispatchMap.put(excel.getEmpIdcard(),dispatch);
	}

	private void initAddHandleItem(TDispatchImportVo excel, TSocialFundInfo socialFund, TDispatchInfo dispatch, SysBaseSetInfo socialSet, boolean injury) {
		StringBuffer temp = new StringBuffer();
		if (Common.isEmpty(socialFund)){
			if (Common.isNotNull(excel.getSocialHousehold())){
				if (Common.isNotNull(excel.getPensionStart())){
					temp.append(DispatchConstants.DISPATCH_PENSION);
				}
				if (Common.isNotNull(excel.getMedicalStart())){
					temp.append(DispatchConstants.DISPATCH_MEDICAL);
				}
				if (Common.isNotNull(excel.getBirthStart())){
					temp.append(DispatchConstants.DISPATCH_BIRTH);
				}
				if (Common.isNotNull(excel.getWorkInjuryStart())){
					temp.append(DispatchConstants.DISPATCH_INJURY);
				}
				if (Common.isNotNull(excel.getUnemployStart())){
					temp.append(DispatchConstants.DISPATCH_UNEMP);
				}
				if (Common.isNotNull(excel.getBigailmentStart())
						&& CommonConstants.ZERO_STRING.equals(socialSet.getIsIllness())){
					temp.append(DispatchConstants.DISPATCH_BIGMAILMENT);
				}
			}
			if (Common.isNotNull(excel.getProvidentHousehold())){
				temp.append(DispatchConstants.DISPATCH_FUND);
			}
		}
		if (Common.isNotNull(socialFund)){
			if (Common.isNotNull(excel.getSocialHousehold())){
				// 兼职工伤派单只生成兼职工伤派单项
				if (injury){
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getWorkInjuryHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							||CommonConstants.TWO_STRING.equals(socialFund.getWorkInjuryHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getWorkInjuryHandle())
							|| Common.isEmpty(socialFund.getWorkInjuryHandle())){
						temp.append(DispatchConstants.DISPATCH_INJURY);
					}
					// 非兼职工伤派单 所有可派增的项目都再派单项中
				}else {
					// 办理失败或已派减  视为可派增
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getPensionHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							|| CommonConstants.TWO_STRING.equals(socialFund.getPensionHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getPensionHandle())
							|| Common.isEmpty(socialFund.getPensionHandle())){
						temp.append(DispatchConstants.DISPATCH_PENSION);
					}
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getMedicalHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							|| CommonConstants.TWO_STRING.equals(socialFund.getMedicalHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getMedicalHandle())
							|| Common.isEmpty(socialFund.getMedicalHandle())){
						temp.append(DispatchConstants.DISPATCH_MEDICAL);
					}
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getWorkInjuryHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							||CommonConstants.TWO_STRING.equals(socialFund.getWorkInjuryHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getWorkInjuryHandle())
							|| Common.isEmpty(socialFund.getWorkInjuryHandle())){
						temp.append(DispatchConstants.DISPATCH_INJURY);
					}
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getBirthHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							||CommonConstants.TWO_STRING.equals(socialFund.getBirthHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getBirthHandle())
							|| Common.isEmpty(socialFund.getBirthHandle())){
						temp.append(DispatchConstants.DISPATCH_BIRTH);
					}
					if ((CommonConstants.ZERO_STRING.equals(socialFund.getUnemployHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							||CommonConstants.TWO_STRING.equals(socialFund.getUnemployHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getUnemployHandle())
							|| Common.isEmpty(socialFund.getUnemployHandle())){
						temp.append(DispatchConstants.DISPATCH_UNEMP);
					}
					if (((CommonConstants.ZERO_STRING.equals(socialFund.getBigailmentHandle())
							&& CommonConstants.TEN_STRING.equals(socialFund.getSocialStatus()))
							|| CommonConstants.TWO_STRING.equals(socialFund.getBigailmentHandle())
							|| CommonConstants.THREE_STRING.equals(socialFund.getBigailmentHandle())
							|| Common.isEmpty(socialFund.getBigailmentHandle()))
							&& CommonConstants.ZERO_STRING.equals(socialSet.getIsIllness())){
						temp.append(DispatchConstants.DISPATCH_BIGMAILMENT);
					}
				}
			}
			//公积金状态：派增（0待审核、1待办理、3办理成功、4办理失败9 审核不通过）、派减（5待审核 6待办理 7 办理成功 8 办理失败 ）
			if (Common.isNotNull(excel.getProvidentHousehold())){
				temp.append(DispatchConstants.DISPATCH_FUND);
			}
		}
		if (Common.isNotNull(temp.toString())){
			temp.deleteCharAt(temp.length()-1);
		}
		dispatch.setDispatchItem(temp.toString());
	}

	private boolean initFundAddInfo(List<ErrorMessage> errorMessageList,
									Map<String, TProvidentFund> funds,
									DispatchEmpVo empVo, SysBaseSetInfo fundSet,
									TDispatchImportVo excel) {
		TProvidentFund fund;
		if (Common.isNotNull(excel.getProvidentHousehold())){
			fund = new TProvidentFund();
			fund.setAuditStatus(CommonConstants.ZERO_STRING);
			fund.setHandleStatus(CommonConstants.ZERO_STRING);
			fund.setDeleteFlag(CommonConstants.ZERO_STRING);
			fund.setBelongUnit(excel.getCustomerId());
			fund.setSettleDomain(excel.getSettleDomainId());
			if (Common.isNotNull(empVo)){
				fund.setEmpId(empVo.getId());
				fund.setEmpNo(empVo.getEmpNo());
				fund.setSettleDomain(empVo.getDeptId());
			}
			fund.setEmpIdcard(excel.getEmpIdcard());
			fund.setEmpName(excel.getEmpName());
			fund.setTrustRemark(excel.getTrustRemark());
			fund.setUnitProvidengCardinal(excel.getProvidentCardinal());
			fund.setPersonalProvidentCardinal(excel.getProvidentCardinal());
			fund.setPersonalProvidentPer(excel.getProvidentPer());
			fund.setUnitProvidentPer(excel.getProvidentPer());
			fund.setProvidentStart(excel.getProvidentStart());
			if (Common.isNotNull(fundSet)){
				fund.setProvidentHousehold(fundSet.getDepartId());
				fund.setProvidentHouseholdName(fundSet.getDepartName());
				if (!checkFundPer(fundSet.getFundProList(), excel)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_PERCENT_NOT_EXIST)));
					return true;
				}
				fund.setCanOverpay(fundSet.getCanOverpay());
				fund.setOverpayNumber(fundSet.getOverpayNumber());
				fund.setFundBaseSetId(fundSet.getId());
				fund.setPayPolicy(fundSet.getPayPolicy());
				fund.setLowerLimit(fundSet.getLowerLimit());
				fund.setUpperLimit(fundSet.getUpperLimit());
				fund.setInsuranceIsLatestCardinality(fundSet.getInsuranceIsLatestCardinality());
				if (Common.isNotNull(fundSet.getProvince())){
					fund.setFundProvince(Integer.toString(fundSet.getProvince()));
				}
				if (Common.isNotNull(fundSet.getCity())){
					fund.setFundCity(Integer.toString(fundSet.getCity()));
				}
				if (Common.isNotNull(fundSet.getTown())){
					fund.setFundTown(Integer.toString(fundSet.getTown()));
				}
				fund.setFundPayPoint(Common.isNotNullToStr(fundSet.getFundPayPoint()));
				fund.setHaveThisMonth(fundSet.getHaveThisMonth());
				//单边小数点处理逻辑
				if (Common.isNotNull(fund.getFundPayPoint())){
					fund.setUnitProvidentFee(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(fund.getUnitProvidengCardinal(), fund.getUnitProvidentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())),Integer.valueOf(fund.getFundPayPoint())));
					fund.setPersonalProvidentFee(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(fund.getPersonalProvidentCardinal(), fund.getPersonalProvidentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())),Integer.valueOf(fund.getFundPayPoint())));
				}
			}
			funds.put(excel.getEmpIdcard(),fund);
		}
		return false;
	}

	/**
	 * @author fxj
	 * @Deprecated  对比公积金比例，对应上true  false
	 **/
	private boolean checkFundPer(List<SysPayProportion> pays,TDispatchImportVo excel){
		if (Common.isNotNull(excel.getProvidentPer()) && Common.isNotNull(pays)){
			for (SysPayProportion per: pays){
				if (per.getCompanyPro().doubleValue()==excel.getProvidentPer().doubleValue()){
					return true;
				}
			}
		}
		return false;
	}

	private void initAddInfo(Map<String, EmpAddDispatchVo> empAdds,
							 Map<String, EmpContractDispatchVo> contracts,
							 Map<String, EmpProjectDispatchVo> projects,
							 DispatchEmpVo empVo, TDispatchImportVo excel,
							 YifuUser user, ProjectSetInfoVo setInfoVo, SysBaseSetInfo socialSet) {
		// 无档案无项目档案无合同无学历
		if (Common.isEmpty(empVo) || Common.isEmpty(empVo.getId())) {
			// 初始化档案
			initEmpAddInfo(empAdds, excel,user);
			// 初始化项目档案
			initProjectInfo(projects, excel, empVo,user,setInfoVo,socialSet);
			// 初始化合同
			initContractInfo(contracts, excel, empVo,setInfoVo,user);
		}
		// 有档案无项目档案无合同
		if (Common.isNotNull(empVo) && Common.isEmpty(empVo.getDeptNo())) {
			// 初始化项目档案
			initProjectInfo(projects, excel, empVo, user, setInfoVo, socialSet);
			// 初始化合同
			initContractInfo(contracts, excel, empVo, setInfoVo, user);
		}
		// 有档案有项目档案无合同
		if (Common.isNotNull(empVo)
				&& Common.isNotNull(empVo.getDeptNo())
				&& Common.isEmpty(empVo.getContractType())) {
			// 初始化合同
			initContractInfo(contracts, excel, empVo, setInfoVo, user);
		}
	}

	private void initSocialAddInfo(Map<String, TSocialInfo> socials,
								   DispatchEmpVo empVo,
								   SysBaseSetInfo socialSet,
								   TDispatchImportVo excel,
								   Map<String, TSocialFundInfo> socialFundMap, boolean dispatchPart) {
		TSocialInfo social;
		if (Common.isNotNull(excel.getSocialHousehold())) {
			social = new TSocialInfo();
			social.setAuditStatus(CommonConstants.ZERO_STRING);
			social.setHandleStatus(CommonConstants.ZERO_STRING);
			social.setDeleteFlag(CommonConstants.ZERO_STRING);
			social.setTrustRemark(excel.getTrustRemark());
			social.setSocialStartDate(excel.getPensionStart());
			//  封装单位信息 结算信息
			social.setBelongUnit(excel.getCustomerId());
			social.setSettleDomain(excel.getSettleDomainId());
			if (Common.isNotNull(empVo)){
				social.setEmpId(empVo.getId());
				social.setEmpName(empVo.getEmpName());
				social.setEmpIdcard(empVo.getEmpIdcard());
				social.setEmpNo(empVo.getEmpNo());
			}else {
				social.setEmpName(excel.getEmpName());
				social.setEmpIdcard(excel.getEmpIdcard());
			}
			social.setBirthHandle(CommonConstants.ZERO_STRING);
			social.setMedicalHandle(CommonConstants.ZERO_STRING);
			social.setPensionHandle(CommonConstants.ZERO_STRING);
			social.setWorkInjuryHandle(CommonConstants.ZERO_STRING);
			social.setUnemployHandle(CommonConstants.ZERO_STRING);
			social.setPaymentType(excel.getPaymentType());
			social.setRecordBase(excel.getRecordBase().toString());
			social.setPensionStart(excel.getPensionStart());
			social.setMedicalStart(ServiceUtil.ifNull(excel.getMedicalStart(), excel.getPensionStart()));
			social.setUnemployStart(ServiceUtil.ifNull(excel.getUnemployStart(), excel.getPensionStart()));
			social.setBigailmentStart(ServiceUtil.ifNull(excel.getBigailmentStart(), excel.getPensionStart()));
			social.setWorkInjuryStart(ServiceUtil.ifNull(excel.getWorkInjuryStart(), excel.getPensionStart()));
			social.setBirthStart(ServiceUtil.ifNull(excel.getBirthStart(), excel.getPensionStart()));
			if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())){
				// 自定义各个基数起缴时间初试化
				social.setPersonalPensionCardinal(excel.getPensionCardinal());
				social.setPersonalMedicalCardinal(ServiceUtil.ifNull(excel.getMedicalCardinal(), excel.getPensionCardinal()));
				social.setPersonalUnemploymentCardinal(ServiceUtil.ifNull(excel.getUnemploymentCardinal(), excel.getPensionCardinal()));

				social.setUnitPensionCardinal(excel.getPensionCardinal());
				social.setUnitMedicalCardinal(ServiceUtil.ifNull(excel.getMedicalCardinal(), excel.getPensionCardinal()));
				social.setUnitUnemploymentCardinal(ServiceUtil.ifNull(excel.getUnemploymentCardinal(), excel.getPensionCardinal()));
				social.setUnitWorkInjuryCardinal(ServiceUtil.ifNull(excel.getWorkInjuryCardinal(), excel.getPensionCardinal()));
				social.setUnitBirthCardinal(ServiceUtil.ifNull(excel.getBirthCardinal(), excel.getPensionCardinal()));
			}
			// 获取到政策后封装相关数据
			if (Common.isNotNull(socialSet)){
				social.setIsIllness(socialSet.getIsIllness());
				if (Common.isNotNull(socialSet.getProvince())){
					social.setSocialProvince(Integer.toString(socialSet.getProvince()));
				}
				if (Common.isNotNull(socialSet.getCity())){
					social.setSocialCity(Integer.toString(socialSet.getCity()));
				}
				if (Common.isNotNull(socialSet.getTown())){
					social.setSocialTown(Integer.toString(socialSet.getTown()));
				}
				social.setCanOverpay(socialSet.getCanOverpay());
				social.setCardinalId(socialSet.getId());
				social.setSocialHousehold(socialSet.getDepartId());
				social.setSocialHouseholdName(socialSet.getDepartName());
				social.setCollectMoth(socialSet.getCollectMoth());
				social.setCollectType(socialSet.getCollectType());
				social.setHaveThisMonth(socialSet.getHaveThisMonth());
				social.setInsuranceBirth(socialSet.getInsuranceBirth());
				social.setInsuranceInjury(socialSet.getInsuranceInjury());
				social.setInsuranceMedical(socialSet.getInsuranceMedical());
				social.setInsurancePension(socialSet.getInsurancePension());
				social.setInsuranceUnemployment(socialSet.getInsuranceUnemployment());
				social.setInsuranceIsLatestCardinality(socialSet.getInsuranceIsLatestCardinality());
				social.setIsChargePersonal(socialSet.getIsChargePersonal());
				social.setOverpayNumber(socialSet.getOverpayNumber());
				social.setValueType(socialSet.getValueType());
				social.setPayPolicy(socialSet.getPayPolicy());
				social.setLowerLimit(socialSet.getLowerLimit());
				social.setUpperLimit(socialSet.getUpperLimit());
				// 比例初始化
				social.setPersonalPensionPer(socialSet.getPersonalPersionPro());
				social.setPersonalMedicalPer(socialSet.getPersonalMedicalPro());
				social.setPersonalUnemploymentPer(socialSet.getPersonalUnemploymentPro());

				social.setUnitPensionPer(socialSet.getUnitPersionPro());
				social.setUnitMedicalPer(socialSet.getUnitMedicalPro());
				social.setUnitUnemploymentPer(socialSet.getUnitUnemploymentPro());
				social.setUnitWorkUnjuryPer(socialSet.getUnitInjuryPro());
				social.setUnitBirthPer(socialSet.getUnitBirthPro());
				//按最低
				if (CommonConstants.ZERO_STRING.equals(excel.getPaymentType())){
					social.setPersonalPensionCardinal(socialSet.getLowerLimit());
					social.setPersonalMedicalCardinal(socialSet.getLowerLimit());
					social.setPersonalUnemploymentCardinal(socialSet.getLowerLimit());

					social.setUnitPensionCardinal(socialSet.getLowerLimit());
					social.setUnitMedicalCardinal(socialSet.getLowerLimit());
					social.setUnitUnemploymentCardinal(socialSet.getLowerLimit());
					social.setUnitWorkInjuryCardinal(socialSet.getLowerLimit());
					social.setUnitBirthCardinal(socialSet.getLowerLimit());
					if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())){
						social.setUnitBigailmentCardinal(socialSet.getLowerLimit());
						social.setPersonalBigailmentCardinal(socialSet.getLowerLimit());
					}
				}
				//按最高
				if (CommonConstants.TWO_STRING.equals(excel.getPaymentType())){
					social.setPersonalPensionCardinal(socialSet.getUpperLimit());
					social.setPersonalMedicalCardinal(socialSet.getUpperLimit());
					social.setPersonalUnemploymentCardinal(socialSet.getUpperLimit());

					social.setUnitPensionCardinal(socialSet.getUpperLimit());
					social.setUnitMedicalCardinal(socialSet.getUpperLimit());
					social.setUnitUnemploymentCardinal(socialSet.getUpperLimit());
					social.setUnitWorkInjuryCardinal(socialSet.getUpperLimit());
					social.setUnitBirthCardinal(socialSet.getUpperLimit());
					if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())){
						social.setPersonalBigailmentCardinal(socialSet.getUpperLimit());
						social.setUnitBigailmentCardinal(socialSet.getUpperLimit());
					}
				}
				if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())){
					social.setInsuranceBigailment(socialSet.getInsuranceBigailment());
					social.setPersonalBigailmentCardinal(ServiceUtil.ifNull(social.getPersonalBigailmentCardinal(), excel.getPensionCardinal()));
					social.setUnitBigailmentCardinal(ServiceUtil.ifNull(social.getUnitBigailmentCardinal(), excel.getPensionCardinal()));
					social.setUnitBigailmentPer(socialSet.getPayCompanyPro());
					social.setPersonalBigailmentPer(socialSet.getPayPersonalPro());
					social.setBigailmentHandle(CommonConstants.ZERO_STRING);
					social.setBigailmentStart(excel.getBigailmentStart());
					social.setCollectMoth(socialSet.getCollectMoth());
				}else {
					social.setInsuranceBigailment(null);
					social.setPersonalBigailmentCardinal(null);
					social.setUnitBigailmentCardinal(null);
					social.setUnitBigailmentPer(null);
					social.setPersonalBigailmentPer(null);
					social.setBigailmentHandle(null);
					social.setBigailmentStart(null);
					social.setCollectMoth(null);
				}
			}

			social.setUnitPersionMoney(BigDecimalUtils.safeMultiply(social.getUnitPensionCardinal(), social.getUnitPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setUnitMedicalMoney(BigDecimalUtils.safeMultiply(social.getUnitMedicalCardinal(), social.getUnitMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setUnitBirthMoney(BigDecimalUtils.safeMultiply(social.getUnitBirthCardinal(), social.getUnitBirthPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setUnitInjuryMoney(BigDecimalUtils.safeMultiply(social.getUnitWorkInjuryCardinal(), social.getUnitWorkUnjuryPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setUnitUnemploymentMoney(BigDecimalUtils.safeMultiply(social.getUnitUnemploymentCardinal(), social.getUnitUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));

			social.setPersonalPersionMoney(BigDecimalUtils.safeMultiply(social.getPersonalPensionCardinal(), social.getPersonalPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setPersonalMedicalMoney(BigDecimalUtils.safeMultiply(social.getPersonalMedicalCardinal(), social.getPersonalMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
			social.setPersonalUnemploymentMoney(BigDecimalUtils.safeMultiply(social.getPersonalUnemploymentCardinal(), social.getPersonalUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));

			boolean flag = CommonConstants.ZERO_STRING.equals(social.getIsIllness()) && (CommonConstants.ZERO_STRING.equals(social.getCollectType())||CommonConstants.ONE_STRING.equals(social.getCollectType()));
			if (flag) {
				//收取方式按年 且为指定月份时产生数据
				if (CommonConstants.ZERO_STRING.equals(social.getCollectType()) && Common.isNotNull(socialSet)) {
					//按年收取大病方式按定值
					social.setUnitBigailmentMoney(socialSet.getPayCompany());
					social.setPersonalBigailmentMoney(socialSet.getPayPersonal());
					social.setUnitBigailmentCardinal(null);
					social.setUnitBigailmentPer(null);
					social.setPersonalBigailmentCardinal(null);
					social.setPersonalBigailmentPer(null);
				}else if (CommonConstants.ONE_STRING.equals(social.getCollectType())) {
					//收取方式按月
					if (CommonConstants.ZERO_STRING.equals(social.getValueType())) {
						//收取大病方式按定值
						social.setUnitBigailmentMoney(socialSet.getPayCompany());
						social.setPersonalBigailmentMoney(socialSet.getPayPersonal());
						social.setPersonalBigailmentCardinal(null);
						social.setPersonalBigailmentPer(null);
						social.setUnitBigailmentCardinal(null);
						social.setUnitBigailmentPer(null);
					} else if (CommonConstants.ONE_STRING.equals(social.getValueType()) && Common.isNotNull(socialSet)) {
						//收取大病按比例
						social.setUnitBigailmentMoney(BigDecimalUtils.safeMultiply(social.getUnitBigailmentCardinal(), socialSet.getPayCompanyPro(), BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
						social.setPersonalBigailmentMoney(BigDecimalUtils.safeMultiply(social.getPersonalBigailmentCardinal(), socialSet.getPayPersonalPro(), BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));

					}
				}
			}
			social.setUnitSocialSum(BigDecimalUtils.safeAdd(social.getUnitPersionMoney()
					, social.getUnitMedicalMoney(), social.getUnitBirthMoney()
					, social.getUnitInjuryMoney()
					, social.getUnitUnemploymentMoney()
					, social.getUnitBigailmentMoney()));
			social.setPersonalSocialSum(BigDecimalUtils.safeAdd(social.getPersonalBigailmentMoney()
					, social.getPersonalPersionMoney()
					, social.getPersonalMedicalMoney()
					, social.getPersonalUnemploymentMoney()));
			// 处理部分办理失败的情况
			initHandleStatus(excel, socialFundMap, social,dispatchPart);
			//单独处理工伤派增时对应的各种数据
			handleInjury(social);
			socials.put(excel.getEmpIdcard(),social);
		}
	}

	private void handleInjury(TSocialInfo social) {
		if (Common.isEmpty(social.getPensionStart())){
			social.setPensionHandle(null);
			social.setPersonalPensionCardinal(null);
			social.setPersonalPensionPer(null);
			social.setPersonalPersionMoney(null);
			social.setUnitPersionMoney(null);
			social.setUnitPensionPer(null);
			social.setUnitPensionCardinal(null);
		}
		if (Common.isEmpty(social.getMedicalStart())){
			social.setMedicalHandle(null);
			social.setPersonalMedicalCardinal(null);
			social.setPersonalMedicalPer(null);
			social.setPersonalMedicalMoney(null);
			social.setUnitMedicalMoney(null);
			social.setUnitMedicalPer(null);
			social.setUnitMedicalCardinal(null);
		}
		if (Common.isEmpty(social.getBirthStart())){
			social.setBirthHandle(null);
			social.setUnitBirthMoney(null);
			social.setUnitBirthPer(null);
			social.setUnitBirthCardinal(null);
		}
		if (Common.isEmpty(social.getUnemployStart())){
			social.setUnemployHandle(null);
			social.setUnitUnemploymentCardinal(null);
			social.setUnitUnemploymentPer(null);
			social.setUnitUnemploymentMoney(null);
			social.setPersonalUnemploymentPer(null);
			social.setPersonalUnemploymentCardinal(null);
			social.setPersonalUnemploymentMoney(null);
		}
		if (Common.isEmpty(social.getWorkInjuryStart())){
			social.setWorkInjuryHandle(null);
			social.setUnitInjuryMoney(null);
			social.setUnitWorkUnjuryPer(null);
			social.setUnitWorkInjuryCardinal(null);
		}
		if (Common.isEmpty(social.getBigailmentStart())
				|| (Common.isEmpty(social.getPensionStart())
				&& Common.isEmpty(social.getMedicalStart())
				&& Common.isEmpty(social.getBirthStart())
				&& Common.isEmpty(social.getUnemployStart())
				&& Common.isEmpty(social.getBigailmentStart())
				&& Common.isNotNull(social.getWorkInjuryStart())
				)){
			social.setBigailmentHandle(null);
			social.setPersonalBigailmentCardinal(null);
			social.setPersonalBigailmentPer(null);
			social.setPersonalBigailmentMoney(null);
			social.setUnitBigailmentMoney(null);
			social.setUnitBigailmentPer(null);
			social.setUnitBigailmentCardinal(null);
		}
	}

	private void initHandleStatus(TDispatchImportVo excel,
								  Map<String, TSocialFundInfo> socialFundMap,
								  TSocialInfo social,
								  boolean dispatchPart) {
		TSocialFundInfo socialFund;
		if (Common.isNotNull(socialFundMap)) {
			socialFund = socialFundMap.get(excel.getEmpIdcard());
			if (Common.isNotNull(socialFund)){
				if (CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())){
					social.setPensionHandle(null);
					social.setUnitPensionCardinal(null);
					social.setUnitPensionPer(null);
					social.setPersonalPensionCardinal(null);
					social.setPersonalPensionPer(null);
					social.setUnitPersionMoney(null);
					social.setPersonalPersionMoney(null);
					social.setPensionStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitPensionCardinal(social.getUnitPensionCardinal());
						socialFund.setUnitPensionPer(social.getUnitPensionPer());
						socialFund.setPersonalPensionCardinal(social.getPersonalPensionCardinal());
						socialFund.setPersonalPensionPer(social.getPersonalPensionPer());
					}
				}
				if (CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())){
					social.setMedicalHandle(null);
					social.setUnitMedicalCardinal(null);
					social.setUnitMedicalPer(null);
					social.setPersonalMedicalCardinal(null);
					social.setPersonalMedicalPer(null);
					social.setUnitMedicalMoney(null);
					social.setPersonalMedicalMoney(null);
					social.setMedicalStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitMedicalCardinal(social.getUnitMedicalCardinal());
						socialFund.setUnitMedicalPer(social.getUnitMedicalPer());
						socialFund.setPersonalMedicalCardinal(social.getPersonalMedicalCardinal());
						socialFund.setPersonalMedicalPer(social.getPersonalMedicalPer());
					}
				}
				if (CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())){
					social.setUnemployHandle(null);
					social.setUnitUnemploymentCardinal(null);
					social.setUnitUnemploymentPer(null);
					social.setPersonalUnemploymentCardinal(null);
					social.setPersonalUnemploymentPer(null);
					social.setUnitUnemploymentMoney(null);
					social.setPersonalUnemploymentMoney(null);
					social.setUnemployStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitUnemploymentCardinal(social.getUnitUnemploymentCardinal());
						socialFund.setUnitUnemploymentPer(social.getUnitUnemploymentPer());
						socialFund.setPersonalUnemploymentCardinal(social.getPersonalUnemploymentCardinal());
						socialFund.setPersonalUnemploymentPer(social.getPersonalUnemploymentPer());
					}
				}
				if (CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())){
					social.setWorkInjuryHandle(null);
					social.setUnitWorkInjuryCardinal(null);
					social.setUnitWorkUnjuryPer(null);
					social.setUnitInjuryMoney(null);
					social.setWorkInjuryStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitWorkInjuryCardinal(social.getUnitWorkInjuryCardinal());
					}
				}
				if (CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())){
					social.setBirthHandle(null);
					social.setUnitBirthCardinal(null);
					social.setUnitBirthPer(null);
					social.setUnitBirthMoney(null);
					social.setBirthStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitBirthCardinal(social.getUnitBirthCardinal());
						socialFund.setUnitBirthPer(social.getUnitBirthPer());
					}
				}
				if (CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())){
					social.setBigailmentHandle(null);
					social.setUnitBigailmentCardinal(null);
					social.setUnitBigailmentPer(null);
					social.setPersonalBigailmentCardinal(null);
					social.setPersonalBigailmentPer(null);
					social.setUnitBigailmentMoney(null);
					social.setPersonalBigailmentMoney(null);
					social.setBigailmentStart(null);
				}else {
					if (!dispatchPart){
						socialFund.setUnitBigailmentCardinal(social.getUnitBigailmentCardinal());
						socialFund.setUnitBigailmentPer(social.getUnitBigailmentPer());
						socialFund.setPersonalBigailmentCardinal(social.getPersonalBigailmentCardinal());
						socialFund.setPersonalBigailmentPer(social.getPersonalBigailmentPer());
					}
				}
				socialFundMap.put(excel.getEmpIdcard(),socialFund);
			}
		}
	}
	private void initHoldInfo(List<String> socialholds,
							  List<String> fundHolds,
							  Map<String, SysBaseSetInfo> socialHoldMap,
							  Map<String, SysBaseSetInfo> fundHoldMap) {
		Date now = DateUtil.getCurrentDateTime();
		if (Common.isNotNull(socialholds)) {
			List<SysBaseSetInfo> socialBases = baseSetMapper.selectList(Wrappers.<SysBaseSetInfo>query().lambda()
					.eq(SysBaseSetInfo::getBaseType, CommonConstants.ZERO_STRING)
					.le(SysBaseSetInfo::getApplyStartDate, now)
					.in(SysBaseSetInfo::getDepartName,socialholds)
					.eq(SysBaseSetInfo::getStatus,CommonConstants.ZERO_STRING)
					.eq(SysBaseSetInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
					.and(obj-> obj.isNull(SysBaseSetInfo::getApplyEndDate).or().ge(SysBaseSetInfo::getApplyEndDate,now))
					.groupBy(SysBaseSetInfo::getDepartName));
			if (Common.isNotNull(socialBases)) {
				for (SysBaseSetInfo set:socialBases){
					socialHoldMap.put(set.getDepartName(),set);
				}
			}
			socialBases.clear();
		}
		if (Common.isNotNull(fundHolds)) {
			List<SysBaseSetInfo> fundBases = baseSetMapper.getFundBaseSet(fundHolds);
			if (Common.isNotNull(fundBases)) {
				for (SysBaseSetInfo set:fundBases){
					fundHoldMap.put(set.getDepartName(),set);
				}
			}
			fundBases.clear();
		}
	}

	private void initContractInfo(Map<String, EmpContractDispatchVo> contracts,
								  TDispatchImportVo excel,
								  DispatchEmpVo empVo, ProjectSetInfoVo setInfoVo, YifuUser user) {
		// 合同开始时间和截止时间一致直接跳过
		if (Common.isNotNull(excel.getContractStart())
				&& Common.isNotNull(empVo)
				&& Common.isNotNull(excel.getContractEnd())
				&& excel.getContractStart().equals(empVo.getContractStart())
				&& excel.getContractEnd().equals(empVo.getContractEnd())){
			return;
		}
		EmpContractDispatchVo contract;
		contract = new EmpContractDispatchVo();
		contract.setContractEnd(excel.getContractEnd());
		contract.setContractName(excel.getContractName());
		contract.setContractSubName(excel.getContractSubName());
		contract.setContractType(excel.getContractType());
		contract.setContractStart(excel.getContractStart());
		contract.setContractSubName(excel.getContractSubName());
		contract.setDeptNo(excel.getSettleDomainCode());
		contract.setPost(excel.getPost());
		contract.setSituation("正常签订");
		contract.setEmpIdcard(excel.getEmpIdcard());
		contract.setEmpName(excel.getEmpName());
		contract.setWorkingHours(excel.getWorkingHours());
		contract.setContractTerm(excel.getContractTerm());
		if (Common.isNotNull(excel.getSocialHousehold())){
			contract.setContractParty(excel.getSocialHousehold());
		}
		if (Common.isEmpty(excel.getSocialHousehold()) && Common.isNotNull(excel.getProvidentHousehold())){
			contract.setContractParty(excel.getSocialHousehold());
		}
		if (Common.isNotNull(user)){
			contract.setCreateBy(user.getId());
			contract.setCreateName(user.getNickname());
		}
		contract.setSettleDomain(setInfoVo.getId());
		contract.setDeptNo(setInfoVo.getDepartNo());
		contract.setCustomerId(setInfoVo.getCustomerId());
		contract.setSubjectUnit(setInfoVo.getCustomerName());
		contract.setSubjectDepart(setInfoVo.getDepartName());
		if (Common.isNotNull(empVo)) {
			contract.setEmpId(empVo.getId());
			contract.setEmpNo(empVo.getEmpNo());
			if (Common.isNotNull(empVo.getEmpNatrue())){
				contract.setEmpType(empVo.getEmpNatrue());
			}
			contract.setFileProvince(empVo.getFileProvince());
			contract.setFileCity(empVo.getFileCity());
			contract.setFileTown(empVo.getFileTown());
		}
		if (Common.isEmpty(contract.getContractTerm()) && Common.isNotNull(contract.getContractStart()) && Common.isNotNull(contract.getContractEnd())){
			contract.setContractTerm(Integer.toString(Common.getYearOfTime(contract.getContractStart(), contract.getContractEnd())));
		}
		contracts.put(excel.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+excel.getSettleDomainCode(),contract);
	}

	private void initProjectInfo(Map<String, EmpProjectDispatchVo> projects,
								 TDispatchImportVo excel,
								 DispatchEmpVo empVo, YifuUser user, ProjectSetInfoVo setInfoVo, SysBaseSetInfo socialSet) {
		EmpProjectDispatchVo project;
		project = new EmpProjectDispatchVo();
		project.setCreateBy(user.getId());
		project.setCreateName(user.getNickname());
		project.setDeptNo(excel.getSettleDomainCode());
		project.setContractType(excel.getContractType());
		project.setEmpIdcard(excel.getEmpIdcard());
		project.setEmpName(excel.getEmpName());
		project.setEmpNatrue(excel.getEmpType());
		project.setPost(excel.getPost());
		project.setWorkingHours(excel.getWorkingHours());
		project.setTryPeriod(excel.getTryPeriod());
		if (Common.isNotNull(socialSet)){
			project.setSocialProvince(socialSet.getProvince());
			project.setSocialCity(socialSet.getCity());
			project.setSocialTown(socialSet.getTown());
		}
		if (Common.isNotNull(empVo)) {
			project.setEmpId(empVo.getId());
			project.setEmpCode(empVo.getEmpCode());
			project.setEmpNo(empVo.getEmpNo());
		}
		if (Common.isNotNull(setInfoVo)){
			project.setDeptName(setInfoVo.getDepartName());
			project.setBusinessPrimaryType(setInfoVo.getBusinessPrimaryType());
			project.setBusinessSecondType(setInfoVo.getBusinessSecondType());
			project.setBusinessThirdType(setInfoVo.getBusinessThirdType());
			project.setUnitId(setInfoVo.getCustomerId());
			project.setUnitName(setInfoVo.getCustomerName());
			project.setUnitNo(setInfoVo.getCustomerCode());
			project.setDeptId(setInfoVo.getId());
		}
		projects.put(excel.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+excel.getSettleDomainCode(),project);
	}

	private void initEmpAddInfo(Map<String, EmpAddDispatchVo> empAdds, TDispatchImportVo excel, YifuUser user) {
		EmpAddDispatchVo emp;
		emp = new EmpAddDispatchVo();
		emp.setCreateBy(user.getId());
		emp.setCreateName(user.getNickname());
		emp.setEmpIdcard(excel.getEmpIdcard());
		emp.setEmpName(excel.getEmpName());
		emp.setEmpNational(excel.getEmpNational());
		emp.setEmpNatrue(excel.getEmpType());
		emp.setEmpPhone(excel.getEmpMobile());
		emp.setEmpRegisType(excel.getEmpRegisType());
		emp.setContractStatus(CommonConstants.ZERO_INT);
		emp.setDeleteFlag(CommonConstants.ZERO_STRING);
		emp.setFileSource(CommonConstants.ONE_STRING);
		emp.setFileProvince(Common.isNotNullToInt(excel.getFileProvince()));
		emp.setFileCity(Common.isNotNullToInt(excel.getFileCity()));
		emp.setFileTown(Common.isNotNullToInt(excel.getFileTown()));
		emp.setFileStatus(CommonConstants.ZERO_INT);
		emp.setStatus(CommonConstants.ZERO_INT);
		emp.setIdProvince(Common.isNotNullToInt(excel.getIdCardProvince()));
		emp.setIdCity(Common.isNotNullToInt(excel.getIdCardCity()));
		emp.setIdTown(Common.isNotNullToInt(excel.getIdCardTown()));
		emp.setProjectNum(CommonConstants.ONE_INT);
		emp.setDeptNo(excel.getSettleDomainCode());
		emp.setPost(excel.getPost());
		emp.setDeptId(excel.getSettleDomainId());
		emp.setDeptNo(excel.getSettleDomainCode());
		emp.setDeptName(excel.getDepartName());
		emp.setUnitName(excel.getCustomerName());
		emp.setUnitNo(excel.getCustomerCode());
		empAdds.put(excel.getEmpIdcard(),emp);
	}

	private boolean validDdispatchStatus(List<ErrorMessage> errorMessageList, TSocialFundInfo sf,
										 TDispatchImportVo excel) {
		if (Common.isNotNull(sf) && Common.isNotNull(excel.getSocialHousehold())) {
			// 拒绝新增1：派单待审核、派单待办理、办理中、办理成功且未派减成功------ 先排除兼职工伤
			if (CommonConstants.ZERO_STRING.equals(sf.getSocialAddStatus())
					|| CommonConstants.ONE_STRING.equals(sf.getSocialAddStatus())
					|| CommonConstants.SIX_STRING.equals(sf.getSocialAddStatus())
					|| (CommonConstants.TWO_STRING.equals(sf.getSocialAddStatus())
					&& !CommonConstants.TWO_STRING.equals(sf.getSocialReduceStatus()))
			) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_EXISTING)));
				return true;
			}
			// 拒绝新增2：新增兼职工伤---全部办理失败或全部派减成功才可以派减兼职工伤
			boolean flag = Common.isEmpty(excel.getPensionStart())
					&& Common.isEmpty(excel.getMedicalStart())
					&& Common.isEmpty(excel.getBirthStart())
					&& Common.isEmpty(excel.getUnemployStart())
					&& Common.isEmpty(excel.getBigailmentStart())
					&& Common.isNotNull(excel.getWorkInjuryStart())
					&& (BigDecimal.ZERO.compareTo(excel.getWorkInjuryCardinal()) <= 0);
			if (flag) {
				// 有兼职工伤不可重复增 (未派减成功不可新增兼职工伤)
				if ((CommonConstants.ZERO_STRING.equals(sf.getWorkInjuryHandle())
						&& !CommonConstants.TEN_STRING.equals(sf.getSocialStatus()))
						|| CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_INJURY_EXISTING)));
					return true;
				}
				// 有五险未派减不给新增兼职工伤
				flag = CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
						|| CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
						|| CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
						|| CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
						|| (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
						&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness()));
				if (flag) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_NOT_REDUCE)));
					return true;
				}
			}else {
				// 五险派单 如果前面兼职工伤没派减 不可派增
				flag =  (BigDecimalUtils.safeAdd(sf.getUnitPersionMoney(),sf.getUnitBigailmentMoney(),
						sf.getUnitBirthMoney(),sf.getUnitMedicalMoney(),sf.getUnitUnemploymentMoney(),
						sf.getUnitInjuryMoney()).compareTo(BigDecimalUtils.isNullToZero(sf.getUnitInjuryMoney())) == 0
						&& BigDecimalUtils.isNullToZero(sf.getUnitInjuryMoney()).compareTo(BigDecimal.ZERO) != 0 )
						&& !(CommonConstants.TEN_STRING.equals(sf.getSocialStatus())
						||  CommonConstants.THREE_STRING.equals(sf.getWorkInjuryHandle())
						||  CommonConstants.TWO_STRING.equals(sf.getWorkInjuryHandle()));
				if (flag) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_INJURY_EXISTING_LIMIT)));
					return true;
				}
			}
		}
		return false;
	}

	private Map<String, TSocialFundInfo> getSocialFundMap(List<String> idcards) {
		List<TSocialFundInfo> list = socialFundMapper.selectList(Wrappers.<TSocialFundInfo>query().lambda()
				.in(TSocialFundInfo::getEmpIdcard, idcards)
				.groupBy(TSocialFundInfo::getEmpIdcard));
		if (Common.isNotNull(list)) {
			Map<String, TSocialFundInfo> map = new HashMap<>();
			for (TSocialFundInfo info:list){
				map.put(info.getEmpIdcard(),info);
			}
			return map;
		}
		return null;
	}

	private void initIdcardAndCode(List<TDispatchImportVo> excelVOList,
								   List<String> idcards, List<String> codes,
								   List<String> socialholds,
								   List<String> fundholds) {
		if (Common.isNotNull(excelVOList)) {
			for (TDispatchImportVo vo : excelVOList) {
				idcards.add(vo.getEmpIdcard());
				codes.add(vo.getSettleDomainCode());
				if (Common.isNotNull(vo.getSocialHousehold())) {
					socialholds.add(vo.getSocialHousehold());
				}
				if (Common.isNotNull(vo.getProvidentHousehold())) {
					fundholds.add(vo.getProvidentHousehold());
				}
			}
		}
	}

	private Map<String, DispatchEmpVo> getDispatchEmpVo(List<String> idcards, List<String> codes) {
		Map<String, DispatchEmpVo> empVoMap = null;
		if (Common.isNotNull(idcards) || Common.isNotNull(codes)) {
			DispatchCheckVo checkVo = new DispatchCheckVo();
			checkVo.setCodes(CollUtil.distinct(codes));
			checkVo.setIdCards(CollUtil.distinct(idcards));
			R<Map<String,DispatchEmpVo>> res = archivesDaprUtil.getDispatchEmpVo(checkVo);
			if (Common.isNotNull(res) && Common.isNotNull(res.getData())) {
				empVoMap = res.getData();
			}
		}
		return empVoMap;
	}

	private boolean validImport(List<ErrorMessage> errorMessageList,
								TDispatchImportVo excel,
								ProjectSetInfoVo setInfoVo,
								TSocialFundInfo socialFund,
								DispatchEmpVo empVo, SysBaseSetInfo socialSet, SysBaseSetInfo fundSet) {
		if (Common.isNotNull(excel.getSocialHousehold()) && Common.isEmpty(excel.getPaymentType())) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_NOT_EMPTY)));
			return true;
		}
		if (Common.isEmpty(setInfoVo)){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_PROJECT_NOT_FOUND)));
			return true;
		}
		if (CommonConstants.ONE_STRING.equals(setInfoVo.getStopFlag())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SETTLEDOMAIN_STOP)));
			return true;
		}
		if (Common.isEmpty(empVo)){
			if (Common.isEmpty(excel.getFileProvince())
					|| Common.isEmpty(excel.getFileCity())
					|| Common.isEmpty(excel.getIdCardProvince())
					|| Common.isEmpty(excel.getIdCardCity())
					|| Common.isEmpty(excel.getWorkingHours())
					|| Common.isEmpty(excel.getEmpNational())
					|| Common.isEmpty(excel.getEmpMobile())
					|| Common.isEmpty(excel.getEmpType())
					|| Common.isEmpty(excel.getPost())
					|| Common.isEmpty(excel.getEducationName())
					|| Common.isEmpty(excel.getContractName())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_NOT_EMPTY)));
				return true;
			}
			if (Common.isNotNull(excel.getContractName()) && validContractInfo(errorMessageList,excel)){
				return true;
			}
			// 如果没有人员档案和项目档案的时候校验身份证和手机号码
			R<Boolean> checkRes = checkDaprUtil.checkIdCardAndMobile(excel.getEmpName(),excel.getEmpIdcard(),excel.getEmpMobile());
			if (Common.isEmpty(checkRes) || checkRes.getCode() != CommonConstants.SUCCESS){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), checkRes.getMsg()));
				return true;
			}
			// 校验手机号码重复
			checkRes = archivesDaprUtil.checkMobile(excel.getEmpMobile());
			if (Common.isEmpty(checkRes) || checkRes.getCode() != CommonConstants.SUCCESS){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), checkRes.getMsg()));
				return true;
			}
			if (checkRes.getData().booleanValue()){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_MOBILE_REPEAT)));
				return true;
			}
		}
		Date contractDateTemp = excel.getContractStart();
		/*项目档案有可用状态的合同：
		不对合同做判断，取值：项目档案的合同；
		项目档案无可用状态的合同：
		合同类型必填、业务细分（合同类型为其他时必填）、签订期限必填
		签订期限：无固定期限    合同到期时间、合同期限非必填，合同开始时间必填；
		签订期限：固定期限、已完成一定工作任务为期限    合同期限非必填，合同开始时间、合同到期时间都必填*/
		if (Common.isNotNull(empVo)){
			if (Common.isNotNull(empVo.getProjectStatus()) && empVo.getProjectStatus().intValue() == CommonConstants.ONE_INT){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_PROJECT_NOT_USED)));
				return true;
			}
			if (Common.isNotNull(empVo.getFileStatus()) && empVo.getFileStatus().intValue() == CommonConstants.ONE_INT){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_NOT_USED)));
				return true;
			}
			// 档案无合同 合同起日期、合同类型必填
			if (Common.isEmpty(empVo.getContractName()) && validContractInfo(errorMessageList,excel)){
				return true;
			}
			if (Common.isNotNull(empVo.getEmpNatrue())){
				excel.setEmpType(empVo.getEmpNatrue());
			}
			if (Common.isNotNull(empVo.getEmpPhone())){
				excel.setEmpMobile(empVo.getEmpPhone());
			}
			excel.setFileProvince(Common.isNotNullToStr(empVo.getFileProvince()));
			excel.setFileCity(Common.isNotNullToStr(empVo.getFileCity()));
			excel.setFileTown(Common.isNotNullToStr(empVo.getFileTown()));
			excel.setIdCardProvince(Common.isNotNullToStr(empVo.getIdProvince()));
			excel.setIdCardCity(Common.isNotNullToStr(empVo.getIdCity()));
			excel.setIdCardTown(Common.isNotNullToStr(empVo.getIdCity()));
			excel.setEmpNational(empVo.getEmpNational());
			excel.setEmpRegisType(empVo.getEmpRegisType());
			excel.setPost(empVo.getPost());
			if (Common.isNotNull(empVo.getContractStart())){
				excel.setContractStart(empVo.getContractStart());
				excel.setContractEnd(empVo.getContractEnd());
				excel.setContractType(empVo.getContractType());
				excel.setContractSubName(empVo.getContractSubName());
				excel.setContractName(empVo.getContractName());
				excel.setContractTerm(empVo.getContractTerm());
			}
		}
		excel.setSettleDomainId(setInfoVo.getId());
		excel.setDepartName(setInfoVo.getDepartName());
		excel.setCustomerCode(setInfoVo.getCustomerCode());
		excel.setCustomerId(setInfoVo.getCustomerId());
		excel.setCustomerName(setInfoVo.getCustomerName());

		if (Common.isEmpty(excel.getSocialHousehold()) && Common.isEmpty(excel.getProvidentHousehold())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_AND_FUND_NOT_EMPTY)));
			return true;
		}
		if ((Common.isEmpty(empVo) || Common.isEmpty(empVo.getContractStart()))
				&& Common.isNotNull(excel.getContractName()) && (
						Common.isEmpty(excel.getContractType())
						|| Common.isEmpty(excel.getContractStart())
		)) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_CONTRACT_NOT_EMPTY)));
			return true;
		}
		// 非自定义的 基数 起缴日期不可空
		if (Common.isNotNull(excel.getSocialHousehold())){
			if (!CommonConstants.ONE_STRING.equals(excel.getPaymentType())
					&& (Common.isEmpty(excel.getRecordBase())
					|| Common.isEmpty(excel.getPensionStart()))
			) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_NOT_EMPTY)));
				return true;
			}
			if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())
			 && (Common.isNullOrZero(excel.getPensionCardinal()) || Common.isEmpty(excel.getPensionStart()))
					&& !(
					Common.isEmpty(excel.getPensionStart())
					&& Common.isNotNull(excel.getWorkInjuryStart())
					&& Common.isEmpty(excel.getMedicalStart())
					&& Common.isEmpty(excel.getBirthStart())
					&& Common.isEmpty(excel.getUnemployStart())
					&& Common.isEmpty(excel.getBigailmentStart())
					&& Common.isNullOrZero(excel.getPensionCardinal())
					&& Common.isNullOrZero(excel.getMedicalCardinal())
					&& Common.isNullOrZero(excel.getBirthCardinal())
					&& Common.isNullOrZero(excel.getUnemploymentCardinal())
					&& !Common.isNullOrZero(excel.getWorkInjuryCardinal())
					&& Common.isNullOrZero(excel.getBigailmentCardinal())
					)
			){
				//养老基数为空 兼职工伤除外
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DIY_MEDICAL_NOT_EMPTY)));
				return true;
			}
		}
		// 兼职工伤 的起缴日期不可为空
		if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())
				&& Common.isEmpty(excel.getPensionCardinal())
				&& Common.isEmpty(excel.getWorkInjuryCardinal())
		){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DIY_NOT_EMPTY)));
			return true;
		}
		// 兼职工伤 养老空 非工伤起缴日期不可有数据
		if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())
				&& Common.isEmpty(excel.getPensionStart())
				&& Common.isNotNull(excel.getWorkInjuryStart())
				&& (Common.isNotNull(excel.getMedicalStart())
				|| Common.isNotNull(excel.getBirthStart())
				|| Common.isNotNull(excel.getUnemployStart())
				|| Common.isNotNull(excel.getBigailmentStart()))
		){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DIY_INJURY_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getProvidentHousehold()) && (
				Common.isEmpty(excel.getProvidentCardinal())
						|| Common.isEmpty(excel.getProvidentStart())
						|| Common.isEmpty(excel.getProvidentPer())
		)) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_NOT_EMPTY)));
			return true;
		}

		if (Common.isNotNull(socialFund)){
			// 社保状态：派增（0待审核、1待办理、2办理中 3办理成功、4部分办理失败 5 办理失败）、派减（6待审核 7待办理 8办理成功 9 办理失败 10 审核不通过-增）
			if (Common.isNotNull(excel.getSocialHousehold())
					&& (CommonConstants.SIX_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.SEVEN_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.NINE_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.ZERO_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.ONE_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.THREE_STRING.equals(socialFund.getSocialStatus())
					|| CommonConstants.TWO_STRING.equals(socialFund.getSocialStatus()))
			){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_EXISTING)));
				return true;
			}
			// 公积金状态：派增（0待审核、1待办理、3办理成功、4办理失败）、派减（5待审核 6待办理 7 办理成功 8 办理失败 9 审核不通过-增）
			if (Common.isNotNull(excel.getProvidentHousehold())
					&& (CommonConstants.FIVE_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.SIX_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.EIGHT_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.ZERO_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.ONE_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.THREE_STRING.equals(socialFund.getFundStatus()))){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_EXISTING)));
				return true;
			}
		}
		if (Common.isNotNull(excel.getSocialHousehold())){
			// 各个社保基数和日期空 默认养老日期和基数
			initExcelBaseAndDate(excel);
			// 校验各项起缴日期 查看是否符合社保补缴政策
			if (validSocialStartDate(errorMessageList, excel, socialSet)){
				return true;
			}
			//校验各项基数
			if (validSocialBaseInfo(errorMessageList, excel, empVo, socialSet,contractDateTemp)){
				return true;
			}
		}
		// 校验公积金上下限和起缴日期
		if (Common.isNotNull(excel.getProvidentHousehold())){
			if(Common.isNotNull(fundSet)
					&& Common.isNotNull(excel.getProvidentCardinal())
					&& (excel.getProvidentCardinal().compareTo(fundSet.getUpperLimit()) > CommonConstants.ZERO_INT
					|| excel.getProvidentCardinal().compareTo(fundSet.getLowerLimit())< CommonConstants.ZERO_INT)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_LIMIT_ERROR)));
				return true;
			}
			if (ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getProvidentStart()),
					fundSet.getCanOverpay(),fundSet.getOverpayNumber(),fundSet.getHaveThisMonth())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_DATE_LIMIT_ERROR)));
				return true;
			}

		}
		return false;
	}
	private boolean validContractInfo(List<ErrorMessage> errorMessageList, TDispatchImportVo excel){
		// 合同起缴时间、合同类型、签订期限必填
		if ((Common.isEmpty(excel.getContractStart())
				|| Common.isEmpty(excel.getContractType())
				|| Common.isEmpty(excel.getContractName()))){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_CONTRACT_NOT_EMPTY)));
			return true;
		}
		// 业务细分（合同类型为其他时必填）
		if (excel.getContractName().equals("其他")
				&& Common.isEmpty(excel.getContractSubName())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_CONTRACT_SUB_NAME_NOT_EMPTY)));
			return true;
		}
		// 签订期限：固定期限、已完成一定工作任务为期限    合同期限非必填，合同开始时间、合同到期时间都必填
		if (excel.getContractType().equals(CommonConstants.ONE_STRING) && Common.isEmpty(excel.getContractEnd())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_CONTRACT_END_NOT_EMPTY)));
			return true;
		}
		return false;
	}

	private boolean validSocialBaseInfo(List<ErrorMessage> errorMessageList, TDispatchImportVo excel, DispatchEmpVo empVo, SysBaseSetInfo socialSet, Date contractDateTemp) {
		if (Common.isNotNull(socialSet) && CommonConstants.ONE_STRING.equals(excel.getPaymentType())
				&& ((Common.isNotNull(excel.getPensionCardinal())
				&& (excel.getPensionCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getPensionCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT))
				||(Common.isNotNull(excel.getMedicalCardinal())
				&& (excel.getMedicalCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getMedicalCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT))
				||(Common.isNotNull(excel.getUnemploymentCardinal())
				&& (excel.getUnemploymentCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getUnemploymentCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT))
				||(Common.isNotNull(excel.getWorkInjuryCardinal())
				&& (excel.getWorkInjuryCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getWorkInjuryCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT))
				||(Common.isNotNull(excel.getBirthCardinal())
				&& (excel.getBirthCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getBirthCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT))
				||(Common.isNotNull(excel.getBigailmentCardinal())
				&& (excel.getBigailmentCardinal().compareTo(socialSet.getUpperLimit()) > CommonConstants.ZERO_INT
				|| excel.getBigailmentCardinal().compareTo(socialSet.getLowerLimit())< CommonConstants.ZERO_INT)))
		){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_LIMIT_ERROR)));
			return true;
		}
		// 备案基数和养老基数 养老起缴日期 必填在前面已必填校验，这里不重复校验
		if (Common.isNotNull(excel.getRecordBase()) && Common.isNotNull(excel.getSocialHousehold())){
			// 自定义 只要有一个不相同的 日期或基数 就要提示
			if (CommonConstants.ONE_STRING.equals(excel.getPaymentType()) && Common.isEmpty(excel.getTrustRemark())){
				boolean flag = (Common.isNotNull(excel.getPensionCardinal())
						&& excel.getPensionCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)
						|| (Common.isNotNull(excel.getMedicalCardinal())
						&& excel.getMedicalCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)
						|| (Common.isNotNull(excel.getUnemploymentCardinal())
						&& excel.getUnemploymentCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)
						|| (Common.isNotNull(excel.getWorkInjuryCardinal())
						&& excel.getWorkInjuryCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)
						|| (Common.isNotNull(excel.getBirthCardinal())
						&& excel.getBirthCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)
						|| (Common.isNotNull(excel.getBigailmentCardinal())
						&& excel.getBigailmentCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT);
				if (flag){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_BASE_LIMIT_ERROR)));
					return true;
				}
				flag = (Common.isNotNull(contractDateTemp)
						&& ((!contractDateTemp.equals(excel.getPensionStart()) && Common.isNotNull(excel.getPensionStart()))
						|| (!contractDateTemp.equals(excel.getMedicalStart()) && Common.isNotNull(excel.getMedicalStart()))
						|| (!contractDateTemp.equals(excel.getUnemployStart()) && Common.isNotNull(excel.getUnemployStart()))
						|| (!contractDateTemp.equals(excel.getBirthStart()) && Common.isNotNull(excel.getBirthStart()))
						|| (!contractDateTemp.equals(excel.getWorkInjuryStart()) && Common.isNotNull(excel.getWorkInjuryStart()))
						|| (!contractDateTemp.equals(excel.getBigailmentStart()) && Common.isNotNull(excel.getBigailmentStart()))));
				if (flag){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR2)));
					return true;
				}
			}
			Date temp;
			if (Common.isEmpty(empVo)){
				temp = excel.getContractStart();
			}else if (Common.isNotNull(empVo) && Common.isNotNull(empVo.getContractStart())){
				temp = empVo.getContractStart();
			}else {
				temp = excel.getContractStart();
			}
			if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())
					&& Common.isEmpty(excel.getTrustRemark())
					&& Common.isEmpty(excel.getPensionStart())
					&& !temp.equals(excel.getWorkInjuryStart())
			){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR)));
				return true;
			}
			// 其他 只用判断对应养老基数和时间 与合同时间 即可
			if (!CommonConstants.ONE_STRING.equals(excel.getPaymentType())  && Common.isEmpty(excel.getTrustRemark())
					&& !temp.equals(excel.getPensionStart())
			){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR2)));
				return true;
			}

			if (!CommonConstants.ONE_STRING.equals(excel.getPaymentType())
					&& Common.isEmpty(excel.getTrustRemark())
					&& (Common.isEmpty(excel.getPensionCardinal())
					|| excel.getPensionCardinal().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_BASE_LIMIT_ERROR)));
				return true;
			}

		}
		return false;
	}

	private boolean validSocialStartDate(List<ErrorMessage> errorMessageList, TDispatchImportVo excel, SysBaseSetInfo socialSet) {
		if (Common.isNotNull(excel.getPensionStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getPensionStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getMedicalStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getMedicalStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getUnemployStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getUnemployStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getWorkInjuryStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getWorkInjuryStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getBirthStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getBirthStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		if (Common.isNotNull(excel.getBigailmentStart())
				&& ServiceUtil.checkDispatchDate(LocalDateTimeUtils.convertDateToLDT(excel.getBigailmentStart()),
				socialSet.getCanOverpay(), socialSet.getOverpayNumber(), socialSet.getHaveThisMonth())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_START_IS_ERROR)));
			return true;
		}
		return false;
	}

	private void initExcelBaseAndDate(TDispatchImportVo excel) {
		if (Common.isEmpty(excel.getMedicalCardinal())){
			excel.setMedicalCardinal(excel.getPensionCardinal());
		}
		if (Common.isEmpty(excel.getUnemploymentCardinal())){
			excel.setUnemploymentCardinal(excel.getPensionCardinal());
		}
		if (Common.isEmpty(excel.getWorkInjuryCardinal())){
			excel.setWorkInjuryCardinal(excel.getPensionCardinal());
		}
		if (Common.isEmpty(excel.getBirthCardinal())){
			excel.setBirthCardinal(excel.getPensionCardinal());
		}
		if (Common.isEmpty(excel.getBigailmentCardinal())){
			excel.setBigailmentCardinal(excel.getPensionCardinal());
		}
		if (Common.isEmpty(excel.getMedicalStart())){
			excel.setMedicalStart(excel.getPensionStart());
		}
		if (Common.isEmpty(excel.getUnemployStart())){
			excel.setUnemployStart(excel.getPensionStart());
		}
		if (Common.isEmpty(excel.getWorkInjuryStart())){
			excel.setWorkInjuryStart(excel.getPensionStart());
		}
		if (Common.isEmpty(excel.getBirthStart())){
			excel.setBirthStart(excel.getPensionStart());
		}
		if (Common.isEmpty(excel.getBigailmentStart())){
			excel.setBigailmentStart(excel.getPensionStart());
		}
	}


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

				@Override
				public void invoke(TDispatchReduceVo 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());
					batchReduceDispatch(cachedDataList, errorMessageList,user,orderId);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	@Override
	public void batchReduceDispatch(List<TDispatchReduceVo> excelVOList, List<ErrorMessage> errorMessageList, YifuUser user, String orderId) {
		if (!Common.isNotNull(excelVOList)){
			return;
		}
		Map<String,String> excelVOTemp = new HashMap<>();
		// 个性化校验逻辑
		List<String> idcards = new ArrayList<>();
		List<String> codes = new ArrayList<>();
		// 初始化参数
		initIdcard(excelVOList, idcards,codes);
		// 通过身份证和项目编码获取档案&项目档案&最新合同
		Map<String, DispatchEmpVo> empVoMap = getDispatchEmpVo(idcards, codes);
		// 通过身份证查询社保&公积金&社保公积金查询信息: 身份证维度唯一
		Map<String, TSocialFundInfo> socialFundMap = getSocialFundMap(idcards);
		// 获取项目编码数据 以供校验
		Map<String, ProjectSetInfoVo> projectVoMap = getProjectVoMap(codes);
		DispatchEmpVo empVo;
		TDispatchInfo dispatch;
		TDispatchReduceVo excel;
		TSocialFundInfo socialFund;
		ProjectSetInfoVo setInfoVo;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			socialFund = null;
			empVo= null;
			excel = excelVOList.get(i);
			setInfoVo = getSetInfoVo(projectVoMap,excel.getDepartNo());
			if (Common.isNotNull(socialFundMap)){
				socialFund = socialFundMap.get(excel.getEmpIdcard());
			}
			if (Common.isEmpty(setInfoVo)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_PROJECT_NOT_FOUND)));
				continue;
			}
			if (Common.isEmpty(socialFund)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_FUND_NOT_EMPTY)));
				continue;
			}
			// 自定义校验
			if (validReduce(errorMessageList,excelVOTemp, socialFundMap,socialFund, excel)){
				continue;
			}
			if (Common.isNotNull(empVoMap)) {
				empVo = empVoMap.get(excel.getEmpIdcard());
			}
			excelVOTemp.put(excel.getRowIndex().toString(),excel.getEmpIdcard());
			// 初始化派单 和 社保公积金查询信息
			dispatch = getDispatchInfo(empVo, excel, socialFund,setInfoVo,user);
			try {
				dispatch.setOrderId(orderId);
				dispatch.setApplyNo(getApplyCode());
				dispatch.setStatus(CommonConstants.ONE_STRING);
				baseMapper.insert(dispatch);
				socialFundMapper.updateById(socialFund);
			}catch (Exception e){
				log.error("批量派减异常：",e);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_FAILED));
			}
		}
	}

	private TDispatchInfo getDispatchInfo(DispatchEmpVo empVo,
										  TDispatchReduceVo excel,
										  TSocialFundInfo socialFund,
										  ProjectSetInfoVo setInfoVo,
										  YifuUser user) {
		TDispatchInfo dispatch;
		dispatch = new TDispatchInfo();
		if (Common.isNotNull(user)){
			dispatch.setCreateBy(user.getId());
			dispatch.setCreateName(user.getNickname());
			dispatch.setOrganName(user.getDeptName());
		}
		dispatch.setCreateTime(LocalDateTime.now());
		dispatch.setEmpId(socialFund.getEmpId());
		dispatch.setEmpName(socialFund.getEmpName());
		dispatch.setEmpNo(socialFund.getEmpNo());
		dispatch.setEmpType(socialFund.getEmpType());
		dispatch.setEmpIdcard(socialFund.getEmpIdcard());
		dispatch.setType(CommonConstants.ONE_STRING);
		dispatch.setLeaveDate(excel.getLeaveDate());
		dispatch.setDeleteFlag(CommonConstants.ZERO_STRING);
		dispatch.setReduceReason(excel.getReasonType());
		dispatch.setTrustRemark(excel.getTrustRemark());
		if (Common.isNotNull(setInfoVo)){
			dispatch.setSettleDomain(setInfoVo.getId());
			dispatch.setSettleDomainName(setInfoVo.getDepartName());
			dispatch.setSettleDomainCode(setInfoVo.getDepartNo());
			dispatch.setBelongUnit(setInfoVo.getCustomerId());
			dispatch.setBelongUnitName(setInfoVo.getCustomerName());
			TEmployeeProject temp = new TEmployeeProject();
			temp.setDeptId(dispatch.getSettleDomain());
			temp.setEmpId(dispatch.getEmpId());
			R<TEmployeeProject> res = archivesDaprUtil.getTEmployeeProjectById(temp);
			if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
				if (Common.isNotNull(res.getData().getWorkingHours())) {
					dispatch.setWorkingHours(res.getData().getWorkingHours());
				}
			}
		}
		StringBuffer temp = new StringBuffer();
		if (Common.isNotNull(excel.getSocialReduceDate())){
			dispatch.setSocialHandleStatus(CommonConstants.ZERO_STRING);
			dispatch.setSocialId(socialFund.getSocialId());
			dispatch.setSocialHouseholdName(socialFund.getSocialHouseholdName());
			dispatch.setSocialProvince(socialFund.getSocialProvince());
			dispatch.setSocialCity(socialFund.getSocialCity());
			dispatch.setSocialTown(socialFund.getSocialTown());
			dispatch.setSocialReduceDate(excel.getSocialReduceDate());
			socialFund.setSocialReduceStatus(CommonConstants.ZERO_STRING);
			socialFund.setSocialReduceStatus(CommonConstants.ZERO_STRING);
			socialFund.setSocialStatus(CommonConstants.SIX_STRING);
			// 养老办理状态：0待办理1办理成功2办理失败3已派减
			if (CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())){
				temp.append(DispatchConstants.DISPATCH_PENSION);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())){
				temp.append(DispatchConstants.DISPATCH_MEDICAL);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())){
				temp.append(DispatchConstants.DISPATCH_INJURY);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())){
				temp.append(DispatchConstants.DISPATCH_BIRTH);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())){
				temp.append(DispatchConstants.DISPATCH_UNEMP);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
					&& CommonConstants.ZERO_STRING.equals(socialFund.getIsIllness())
			){
				temp.append(DispatchConstants.DISPATCH_BIGMAILMENT);
			}
		}
		if (Common.isNotNull(excel.getFundReduceDate())){
			// 公积金状态：派增（0待审核、1待办理、3办理成功、4办理失败9 审核不通过）、派减（5待审核 6待办理 7 办理成功 8 办理失败 ）
			if (CommonConstants.THREE_STRING.equals(socialFund.getFundStatus())){
				temp.append(DispatchConstants.DISPATCH_FUND);
			}
			dispatch.setFundHandleStatus(CommonConstants.ZERO_STRING);
			dispatch.setFundId(socialFund.getFundId());
			dispatch.setProvidentHouseholdName(socialFund.getProvidentHouseholdName());
			dispatch.setFundProvince(socialFund.getFundProvince());
			dispatch.setFundCity(socialFund.getFundCity());
			dispatch.setFundTown(socialFund.getFundTown());
			dispatch.setFundReduceDate(excel.getFundReduceDate());
			socialFund.setFundStatus(CommonConstants.FIVE_STRING);
			socialFund.setFundReduceStatus(CommonConstants.ZERO_STRING);
		}
		if (Common.isNotNull(temp.toString())){
			temp.deleteCharAt(temp.length()-1);
		}
		dispatch.setDispatchItem(temp.toString());
		dispatch.setBelongUnitName(socialFund.getUnitName());
		dispatch.setBelongUnit(socialFund.getUnitId());
		if (Common.isNotNull(empVo)){
			dispatch.setEmpMobile(empVo.getEmpPhone());
			dispatch.setEmpNational(empVo.getEmpNational());
			dispatch.setEmpId(empVo.getId());
			dispatch.setEmpNo(empVo.getEmpNo());
			// 封装合同信息 如果有合同取值实际合同信息
			dispatch.setContractStart(empVo.getContractStart());
			dispatch.setContractEnd(empVo.getContractEnd());
			dispatch.setContractTerm(empVo.getContractTerm());
			dispatch.setContractType(empVo.getContractType());
			dispatch.setFileProvince(empVo.getFileProvince());
			dispatch.setFileCity(empVo.getFileCity());
			dispatch.setFileTown(empVo.getFileTown());
			dispatch.setContractName(empVo.getContractName());
			dispatch.setContractSubName(empVo.getContractSubName());
		}
		return dispatch;
	}

	private boolean validReduce(List<ErrorMessage> errorMessageList,
								Map<String, String> excelVOTemp,
								Map<String, TSocialFundInfo> socialFundMap,
								TSocialFundInfo socialFund,
								TDispatchReduceVo excel) {
		if (Common.isNotNull(excelVOTemp.get(excel.getEmpIdcard()))){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_EXISTS)));
			return true;
		}
		if (Common.isEmpty(excel.getFundReduceDate()) && Common.isEmpty(excel.getSocialReduceDate())){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_SOCIAL_FUND_NOT_EMPTY)));
			return true;
		}
		if (Common.isEmpty(socialFundMap)){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_FUND_NOT_EMPTY)));
			return true;
		}
		// 项目编码校验

		//社保状态：派增（0待审核、1待办理、2办理中 3办理成功、4部分办理失败 5 办理失败）、派减（6待审核 7待办理 8办理成功 9 办理失败）
		if (Common.isNotNull(excel.getSocialReduceDate())){
			if (Common.isEmpty(socialFund.getSocialStatus())
					|| !(socialFund.getSocialStatus().equals(CommonConstants.THREE_STRING)
					|| socialFund.getSocialStatus().equals(CommonConstants.FOUR_STRING)
					|| socialFund.getSocialStatus().equals(CommonConstants.NINE_STRING))){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_SOCIAL_STATUS_ERROR)));
				return true;
			}
			if (!excel.getDepartNo().equals(socialFund.getSettleDomainCode())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_SOCIAL_DEPARTNO_ERROR)));
				return true;
			}
		}
		//公积金状态：派增（0待审核、1待办理、3办理成功、4办理失败）、派减（5待审核 6待办理 7 办理成功 8 办理失败）
		if (Common.isNotNull(excel.getFundReduceDate())){
			if (Common.isEmpty(socialFund.getFundStatus())
					|| (!socialFund.getFundStatus().equals(CommonConstants.THREE_STRING)
					&& !socialFund.getFundStatus().equals(CommonConstants.EIGHT_STRING))){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_FUND_STATUS_ERROR)));
				return true;
			}
			if (!excel.getDepartNo().equals(socialFund.getSettleDomainCodeFund())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_FUND_DEPARTNO_ERROR)));
				return true;
			}
		}
		return false;
	}

	private void initIdcard(List<TDispatchReduceVo> excelVOList, List<String> idcards, List<String> codes) {
		if (Common.isNotNull(excelVOList)) {
			for (TDispatchReduceVo vo : excelVOList) {
				idcards.add(vo.getEmpIdcard());
				codes.add(vo.getDepartNo());
			}
		}
	}

	@Override
	public R<Boolean> removeByIdDiy(String id) {
		if (Common.isEmpty(id)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		TDispatchInfo dispatch  = baseMapper.selectById(id);
		if (Common.isEmpty(dispatch)){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		dispatch.setDeleteFlag(CommonConstants.ONE_STRING);
		if(baseMapper.updateById(dispatch)>0){
			return R.ok(true,CommonConstants.SAVE_SUCCESS);
		}else {
			return R.failed(false,CommonConstants.SAVE_FAILED);
		}
	}
	/**
	 * 通过id查询派单相关系信息
	 * @author fxj
	 * @param id id
	 * @return R
	 * @date 2022-07-25 10:19
	 */
	@Override
	public DispatchDetailVo getSocialAndFundInfoById(String id) {
		DispatchDetailVo detailVo = new DispatchDetailVo();
		TDispatchInfo dispatch = baseMapper.selectById(id);
		detailVo.setDispatch(dispatch);
		if (Common.isNotNull(dispatch)){
			if (Common.isNotNull(dispatch.getSocialId())){
				detailVo.setSocial(socialMapper.selectById(dispatch.getSocialId()));
			}
			if (Common.isNotNull(dispatch.getFundId())){
				detailVo.setFund(fundMapper.selectById(dispatch.getFundId()));
			}
			if (Common.isNotNull(dispatch.getContractId())){
				R<TEmployeeContractInfo> res = archivesDaprUtil.getContractById(dispatch.getContractId());
				if (Common.isNotNull(res)){
					detailVo.setContract(res.getData());
				}
			}
			if (Common.isNotNull(dispatch.getSettleDomain()) && Common.isNotNull(dispatch.getEmpId())){
				TEmployeeProject temp = new TEmployeeProject();
				temp.setDeptId(dispatch.getSettleDomain());
				temp.setEmpId(dispatch.getEmpId());
				R<TEmployeeProject> res = archivesDaprUtil.getTEmployeeProjectById(temp);
				if (Common.isNotNull(res)){
					detailVo.setProject(res.getData());
				}
			}
			if (Common.isNotNull(dispatch.getEmpId())){
				R<TEmployeeInfo> res = archivesDaprUtil.getTEmployeeInfoById(dispatch.getEmpId());
				if (Common.isNotNull(res)){
					detailVo.setEmployee(res.getData());
				}
			}
			detailVo.setAudits(auditInfoMapper.selectList(Wrappers.<TAuditInfo>query().lambda()
					.and(obj->obj.eq(TAuditInfo::getDispatchInfoId,dispatch.getId())
							.or().eq(TAuditInfo::getSocialId,dispatch.getId())
							.or().eq(TAuditInfo::getProvidentId,dispatch.getId()))));
		}
		return detailVo;
	}

	/**
	 * 初始化派单审核信息
	 * @Author fxj
	 * @date 2020-10-27
	 * @return
	 **/
	private void initAuditInfo(TAuditInfo auditInfo,
							   String remark,
							   String handleStatus,
							   YifuUser user,
							   String tile, String s){
		if (null == auditInfo){
			auditInfo = new TAuditInfo();
		}
		auditInfo.setId(null);
		auditInfo.setAuditStatus(handleStatus);
		auditInfo.setAuditRemark(Common.isNullToString(remark));
		auditInfo.setTitle(tile);
		auditInfo.setOrganName(user.getDeptName());
		auditInfo.setAuditUser(user.getNickname());
		auditInfo.setAuditTime(new Date());
		auditInfo.setRemark(s);
		auditInfo.setIsCommision(CommonConstants.ONE_STRING);
	}
	/**
	 * @Author fxj
	 * @Description 派单申请批量审核
	 * @Date 16:54 2022/7/25
	 * @Param
	 * @return
	 **/
	@Override
	public List<ErrorMessage> addBatchApplyAudit(List<String> idsList, YifuUser user, int flag, String auditStatus, String auditRemark, String remark) {
		List<ErrorMessage> errorList = new ArrayList<>();
		if (!Common.isNotNull(idsList)) {
			errorList.add(new ErrorMessage(-1, CommonConstants.PARAM_IS_NOT_ERROR));
			return errorList;
		}
		// 获取所有派单信息
		List<TDispatchInfo> dispatchs = baseMapper.selectList(Wrappers.<TDispatchInfo>query().lambda().in(TDispatchInfo::getId, idsList));
		if (Common.isNotNull(dispatchs)) {
			// 获取所有派单查询信息
			Map<String,TSocialFundInfo>  socialFundMap = initSocialFundMap(dispatchs);
			try {
				TSocialInfo socialInfo;
				TProvidentFund providentFund;
				String remarkTemp;
				TAuditInfo auditInfo;
				TSocialFundInfo sf = null;
				Date now = new Date();
				// 预估库同步社保还是公积金的标志，0：全部；1仅社保；2仅公积金
				int forecastFlag;
				for (TDispatchInfo dis : dispatchs) {
					forecastFlag = getForecastFlag(dis);
					auditInfo = new TAuditInfo();
					remarkTemp = "";
					if (Common.isNotNull(socialFundMap)){
						sf = socialFundMap.get(dis.getEmpIdcard());
					}
					if (Common.isEmpty(sf)){
						errorList.add(new ErrorMessage(-1, "找不到员工社保公积金查询数据：" + dis.getEmpName()));
						continue;
					}
					//社保状态处理
					if (Common.isNotNull(dis.getSocialId())) {
						remarkTemp = "社保";
						socialInfo = socialMapper.selectById(dis.getSocialId());
						if (null == socialInfo && Common.isNotNull(dis.getSocialId())) {
							errorList.add(new ErrorMessage(-1, "找不到员工社保派单数据：" + dis.getEmpName()));
							continue;
						}
						if (null != socialInfo) {
							// 派增审核
							if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())){
								//派增审核通过
								if (CommonConstants.ZERO_INT == flag) {
									socialInfo.setAuditStatus(CommonConstants.ONE_STRING);
									// 待办理
									sf.setSocialAddStatus(CommonConstants.ONE_STRING);
									sf.setSocialStatus(CommonConstants.ONE_STRING);
								//派增审核不通过  需要处理预估数据
								} else if (CommonConstants.ONE_INT == flag) {
									socialInfo.setDeleteFlag(CommonConstants.ONE_STRING);
									// 作废更新：社保状态、同步预估数据   审核不通过直接作废
									socialInfo.setAuditStatus(CommonConstants.TWO_STRING);
									socialInfo.setDeleteFlag(CommonConstants.ONE_STRING);
									sf.setSocialAddStatus(CommonConstants.FIVE_STRING);
									sf.setSocialStatus(CommonConstants.TEN_STRING);
								}
								socialInfo.setAuditTime(now);
								socialInfo.setAuditUser(user.getId());
							}
							// 派减审核
							if (CommonConstants.dingleDigitStrArray[1].equals(dis.getType())){
								//派增审核通过
								if (CommonConstants.ZERO_INT == flag) {
									socialInfo.setReduceCan(CommonConstants.ONE_STRING);
									// 待办理
									sf.setSocialReduceStatus(CommonConstants.ONE_STRING);
									sf.setSocialStatus(CommonConstants.SEVEN_STRING);
									//派增审核不通过  需要处理预估数据
								} else if (CommonConstants.ONE_INT == flag) {
									// 作废更新：社保状态、同步预估数据  8 审核不通过直接作废
									sf.setSocialReduceStatus(CommonConstants.ONE_STRING_NEGATE);
									sf.setSocialStatus(CommonConstants.THREE_STRING);
									sf.setSocialReduceDate(null);
								}
							}
							socialMapper.updateById(socialInfo);
						}
					}
					//公积金状态处理
					if (Common.isNotNull(dis.getFundId())) {
						if (Common.isEmpty(remarkTemp)) {
							remarkTemp += "、公积金";
						} else {
							remarkTemp += "公积金";
						}
						providentFund = fundMapper.selectById(dis.getFundId());
						if (Common.isEmpty(providentFund)) {
							errorList.add(new ErrorMessage(-1, "找不到员工公积金派单数据：" + dis.getEmpName()));
							continue;
						}
						if (Common.isNotNull(providentFund)) {
							//派增
							if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())){
								// 审核通过
								if (CommonConstants.ZERO_INT == flag) {
									providentFund.setAuditStatus(CommonConstants.ONE_STRING);
									sf.setFundAddStatus(CommonConstants.ONE_STRING);
									sf.setFundStatus(CommonConstants.ONE_STRING);
									// 审核不通过
								} else if (CommonConstants.ONE_INT == flag) {
									// 作废更新：公积金状态、同步档案的公积金状态、同步预估数据
									providentFund.setAuditStatus(CommonConstants.TWO_STRING);
									providentFund.setDeleteFlag(CommonConstants.ONE_STRING);
									sf.setFundAddStatus(CommonConstants.FOUR_STRING);
									sf.setFundStatus(CommonConstants.NINE_STRING);
								}
								providentFund.setAuditTime(now);
								providentFund.setAuditUser(user.getId());
							}
							//派减
							if (CommonConstants.dingleDigitStrArray[1].equals(dis.getType())){
								// 审核通过
								if (CommonConstants.ZERO_INT == flag) {
									providentFund.setReduceCan(CommonConstants.ONE_STRING);
									sf.setFundReduceStatus(CommonConstants.ONE_STRING);
									sf.setFundStatus(CommonConstants.SIX_STRING);
									// 审核不通过
								} else if (CommonConstants.ONE_INT == flag) {
									// 作废更新：公积金状态、同步档案的公积金状态
									sf.setFundReduceStatus(CommonConstants.ONE_STRING_NEGATE);
									sf.setFundStatus(CommonConstants.THREE_STRING);
									sf.setFundReduceDate(null);
								}
							}
							fundMapper.updateById(providentFund);

						}
					}
					// 审核不通过 直接作废   要考虑 部分派增的情况
					if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
						remarkTemp += DispatchConstants.DISPATCH_ADD;
					} else {
						remarkTemp += DispatchConstants.DISPATCH_REDUCE;
					}
					// 派单状态信息拼接
					if (CommonConstants.ZERO_INT == flag) {
						remarkTemp += "审核通过：" + Common.isNullToString(auditRemark);
						initAuditInfo(auditInfo, remarkTemp, CommonConstants.ONE_STRING, user,remarkTemp,remark);
					} else {
						remarkTemp += "审核不通过：" + Common.isNullToString(auditRemark);
						initAuditInfo(auditInfo, remarkTemp, CommonConstants.TWO_STRING, user,remarkTemp, remark);
					}
					//记录处理意见到派单  最新的意见会覆盖之前的，详情 到流程中查询
					dis.setHandleRemark(ServiceUtil.ifNullToEmpty(auditRemark));
					dis.setAuditRemark(ServiceUtil.ifNullToEmpty(auditRemark));
					auditInfo.setDispatchInfoId(dis.getId());
					//更新派单状态
					if (CommonConstants.ZERO_INT == flag) {
						//审核通过
						dis.setStatus(CommonConstants.TWO_STRING);
					} else if (CommonConstants.ONE_INT == flag) {
						//审核不通过
						dis.setStatus(CommonConstants.THREE_STRING);
					}

					boolean flagTemp = false;
					// 派增审核通过 要更新 人员档案 项目档案 合同的状态信息
					if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())){
						R<Boolean> res = null;
						if (CommonConstants.ZERO_INT == flag){
							res = archivesDaprUtil.updateEmpInfo(dis.getEmpIdcard(),dis.getSettleDomainCode(),dis.getContractId(),CommonConstants.ZERO_STRING);
						}
						if (CommonConstants.ONE_INT == flag){
							res = archivesDaprUtil.updateEmpInfo(dis.getEmpIdcard(),dis.getSettleDomainCode(),dis.getContractId(),CommonConstants.ONE_STRING);

							// 派增审核不通过 失败项重新派单审核不通过 恢复为部分办理失败
							flagTemp = Common.isNotNull(sf) && Common.isNotNull(dis.getSocialId())
									&& (CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
									|| CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
									|| CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
									|| CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
									|| CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
									|| (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
									&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness())))
									&& !(CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
									&& CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
									&& CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
									&& CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
									&& CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
									&& (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
									&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness())));
							if (flagTemp){
								sf.setSocialStatus(CommonConstants.FOUR_STRING);
								sf.setSocialAddStatus(CommonConstants.THREE_STRING);
							}
						}
						if (Common.isEmpty(res) || CommonConstants.SUCCESS != res.getCode()){
							ServiceUtil.runTimeExceptionDiy("更新人员档案、项目档案、合同状态异常：" + (Common.isNotNull(res)?res.getMsg():CommonConstants.EMPTY_STRING));
						}
					}
					//新增审核记录信息
					auditInfo.setEmpIdcard(dis.getEmpIdcard());
					auditInfo.setDispatchInfoId(dis.getId());
					auditInfoMapper.insert(auditInfo);
					dis.setAuditUser(user.getId());
					dis.setAuditUserName(user.getNickname());
					dis.setAuditTime(now);
					baseMapper.updateById(dis);


					socialFundMapper.updateById(sf);
					// 派增审核不通过
					if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())
							&& CommonConstants.ONE_INT == flag){
						// 更新预估数据 -- 失败项重新派单审核不通过不处理预估
						if (!flagTemp){
							forecastLibraryService.updateForecastLibaryByDispatchReduce(sf, forecastFlag);
						}
						// 更新人员档案和项目档案的社保公积金状态
						UpProjectSocialFundVo vo = new UpProjectSocialFundVo();
						if (Common.isNotNull(dis.getSocialId())){
							vo.setSocialStatus(CommonConstants.ZERO_STRING);
						}
						if (Common.isNotNull(dis.getFundId())){
							vo.setFundStatus(CommonConstants.ZERO_STRING);
						}
						vo.setEmpIdCard(dis.getEmpIdcard());
						vo.setDepartNo(dis.getSettleDomainCode());
						if (flagTemp){
							vo.setSocialStatus(CommonConstants.TWO_STRING);
						}
						R<Boolean> resUp = archivesDaprUtil.updateProjectSocialFund(vo);
						if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()){
							ServiceUtil.runTimeExceptionDiy(DispatchConstants.DISPATCH_SYN_DOC_EXE);
						}
					}
				}
			} catch (Exception e) {
				log.error(DispatchConstants.DISPATCH_AUDIT_ERROR , e);
				errorList.add(new ErrorMessage(-1, DispatchConstants.DISPATCH_AUDIT_ERROR + e.getMessage()));
				return errorList;
			}
		} else {
			errorList.add(new ErrorMessage(-1, DispatchConstants.NO_OPERATOR_DATA));
			return errorList;
		}
		return errorList;
	}
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> addApplyAudit(String ids, String auditStatus, String auditRemark, String remark) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		try {
			if (!Common.isNotNull(ids)) {
				return R.failed(DispatchConstants.DISPATCH_ID_NOT_EMPTY);
			}
			int flag;
			if (CommonConstants.ONE_STRING.equals(auditStatus)) {
				//审核通过
				flag = CommonConstants.ZERO_INT;
			} else if (CommonConstants.TWO_STRING.equals(auditStatus)) {
				//审核不通过
				flag = CommonConstants.ONE_INT;
			} else {
				return R.failed("派单审核状态参数异常：0待审核  1审核通过 2审核不通过");
			}
			List<ErrorMessage> errorInfo = addBatchApplyAudit(Common.initStrToList(ids, CommonConstants.COMMA_STRING), user,  flag, auditStatus, Common.isNullToString(auditRemark),remark);
			return R.ok(errorInfo,"派单审核结果：");
		} catch (Exception e) {
			log.error("派单审核异常：" + e.getMessage());
			return R.failed("数据异常，派单审核失败!");
		}
	}
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> addApplyHandle(String ids, String typeSub, String handleStatus, String handleRemark, String socialType, String remark) {
		try {
			YifuUser user = SecurityUtils.getUser();
			if (null == user) {
				return R.failed(CommonConstants.USER_FAIL);
			}
			if (!Common.isNotNull(ids)) {
				return R.failed(DispatchConstants.DISPATCH_ID_NOT_EMPTY);
			}
			int flag;
			if (CommonConstants.ONE_STRING.equals(handleStatus)) {
				//办理成功
				flag = CommonConstants.ZERO_INT;
			} else if (CommonConstants.TWO_STRING.equals(handleStatus)) {
				//办理失败
				flag = CommonConstants.ONE_INT;
			} else {
				return R.failed("派单办理状态参数异常：0待办理  1办理通过 2办理不通过");
			}
			List<ErrorMessage> errorInfo = addBatchApplyHandle(Common.initStrToList(ids, CommonConstants.COMMA_STRING)
					, typeSub, user,  flag, handleStatus, Common.isNullToString(handleRemark), socialType,remark);
			if (errorInfo == null || errorInfo.isEmpty()) {
				return R.ok(null,"办理成功！");
			} else {
				return R.ok(errorInfo,"派单办理结果：");
			}
		} catch (Exception e) {
			log.error(DispatchConstants.DISPATCH_EXCEPTION + e.getMessage());
			return R.failed("数据异常，办理失败!");
		}
	}

	private Map<String, TSocialFundInfo>  initSocialFundMap(List<TDispatchInfo> dispatchs) {
		List<String> idCards = dispatchs.stream().map(TDispatchInfo::getEmpIdcard).collect(Collectors.toList());
		if (Common.isNotNull(idCards)){
			List<TSocialFundInfo>  socialFunds = socialFundMapper.selectList(Wrappers.<TSocialFundInfo>query().lambda()
					.in(TSocialFundInfo::getEmpIdcard,idCards));
			if (Common.isNotNull(socialFunds)){
				return socialFunds.stream().collect(Collectors.toMap(k->k.getEmpIdcard(),k->k));
			}
		}
		return new HashMap<>();
	}

	/**
	 * 社保派单批量办理
	 * @param typeSub 0社保办理；1公积金办理
	 * @param idsList
	 * @param user
	 * @param flag 0审核通过； 1审核不通过
	 * @param handleStatus 1 办理成功 2 办理失败
	 * @param handleRemark
	 * @param socialType 社保拆分的每一项（1养老 2医疗 3失业 4工伤 5生育 6大病）
	 * @param remark
	 * @return
	 * @Author fxj
	 * @Date 2022-07-26
	 **/
	public List<ErrorMessage> addBatchApplyHandle(List<String> idsList, String typeSub, YifuUser user
			, int flag, String handleStatus, String handleRemark, String socialType, String remark) {
		List<ErrorMessage> errorList = new ArrayList<>();
		if (!Common.isNotNull(idsList)) {
			errorList.add(new ErrorMessage(-1, CommonConstants.PARAM_IS_NOT_ERROR));
			return errorList;
		}
		List<TDispatchInfo> disList = baseMapper.selectList(Wrappers.<TDispatchInfo>query().lambda().in(TDispatchInfo::getId, idsList));
		if (Common.isNotNull(disList)) {
			// 获取所有派单查询信息
			Map<String,TSocialFundInfo>  socialFundMap = initSocialFundMap(disList);
			try {
				TSocialInfo socialInfo = null;
				TProvidentFund providentFund = null;
				TAuditInfo auditInfo = null;
				StringBuilder socialTypeRemark = new StringBuilder();
				TSocialFundInfo  sf = null;
				Date now = new Date();
				StringBuilder temp = new StringBuilder();
				// 预估库同步社保还是公积金的标志，0：全部；1仅社保；2仅公积金
				int forecastFlag = CommonConstants.ZERO_INT;
				// auditFlag 表示社保办理无办理项是不保存
				boolean auditFlag = true;
				for (TDispatchInfo dis : disList) {
					auditFlag = true;
					if (CommonConstants.ZERO_STRING.equals(typeSub)) {
						forecastFlag = CommonConstants.ONE_INT;
					} else if (CommonConstants.ONE_STRING.equals(typeSub)) {
						forecastFlag = CommonConstants.TWO_INT;
					}
					auditInfo = new TAuditInfo();
					if (Common.isNotNull(socialFundMap)){
						sf = socialFundMap.get(dis.getEmpIdcard());
					}
					if (Common.isEmpty(sf)){
						errorList.add(new ErrorMessage(-1, "找不到员工社保公积金查询数据：" + dis.getEmpName()));
						continue;
					}
					if (!CommonConstants.TWO_STRING.equals(dis.getStatus())) {
						errorList.add(new ErrorMessage(-1, "派单审核通过后才可以办理：" + dis.getEmpName()));
						continue;
					}
					if (Common.isNotNull(dis.getSocialId())) {
						// 无更新直接跳过
						if (Common.isEmpty(socialTypeRemark)
								&& CommonConstants.ZERO_STRING.equals(typeSub)
								&& CommonConstants.ZERO_STRING.equals(dis.getType())
								&& Common.isEmpty(socialType)) {
							continue;
						}
						socialInfo = socialMapper.selectById(dis.getSocialId());
						socialTypeRemark = getHandleRemark(socialType, socialInfo);
					} else {
						socialInfo = null;
					}
					if (Common.isNotNull(dis.getFundId())) {
						providentFund = fundMapper.selectById(dis.getFundId());
					} else {
						providentFund = null;
					}
					//派增处理
					if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
						//社保派增办理
						if (CommonConstants.ZERO_STRING.equals(typeSub)) {
							if (Common.isNotNull(socialInfo) && Common.isNotNull(socialInfo.getId())) {
								socialInfo.setHandleStatus(handleStatus);
								socialInfo.setHandleTime(now);
								socialInfo.setHandleUser(user.getId());

								// 社保办理状态补充判断：
								this.setSocialHandleStatus(handleStatus, socialType, flag, socialInfo, dis,sf);

								socialMapper.updateById(socialInfo);
								dis.setSocialHandleRemark(ServiceUtil.ifNullToEmpty(handleRemark));
								auditFlag = Common.isNotNull(Common.isNullToString(socialTypeRemark));
								if (auditFlag){
									auditInfo.setType(CommonConstants.ONE_STRING);
									if (CommonConstants.ZERO_INT == flag) {
										temp.setLength(CommonConstants.ZERO_INT);
										temp.append(DispatchConstants.DISPATCH_SOCIAL_ADD);
										temp.append(Common.isNullToString(socialTypeRemark));
										temp.append(DispatchConstants.DISPATCH_HANDLE_SUCCESS);
										initAuditInfo(auditInfo, ( temp + ServiceUtil.ifNullToEmpty(handleRemark)), CommonConstants.THREE_STRING, user, temp.toString(), remark);
									} else {
										temp.setLength(CommonConstants.ZERO_INT);
										temp.append(DispatchConstants.DISPATCH_SOCIAL_ADD);
										temp.append(Common.isNullToString(socialTypeRemark));
										temp.append(DispatchConstants.DISPATCH_HANDLE_FAIL);
										initAuditInfo(auditInfo, ( temp + ServiceUtil.ifNullToEmpty(handleRemark)), CommonConstants.FOUR_STRING, user, temp.toString(), remark);
									}
									auditInfo.setSocialId(dis.getId());
								}
							} else {
								errorList.add(new ErrorMessage(-1, "找不到对应员工社保派增派单数据：" + dis.getEmpName()));
								continue;
							}
							//公积金办理
						} else if (CommonConstants.ONE_STRING.equals(typeSub)) {

							if (null != providentFund && Common.isNotNull(providentFund.getId())) {
								// 办理状态（0待办理/1已办理2办理失败3已派减）
								providentFund.setHandleStatus(handleStatus);
								providentFund.setHandleTime(now);
								providentFund.setHandleUser(user.getId());
								dis.setFundHandleStatus(handleStatus);
								if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType()) && CommonConstants.ZERO_INT == flag) {
									//派增办理通过 改成可派减状态
									providentFund.setReduceCan(CommonConstants.dingleDigitStrArray[0]);
									sf.setFundAddStatus(CommonConstants.TWO_STRING);
									sf.setFundStatus(CommonConstants.THREE_STRING);
								} else if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType()) && CommonConstants.ONE_INT == flag) {
									//派增办理不通过 改成不可派减状态
									providentFund.setReduceCan(CommonConstants.dingleDigitStrArray[1]);
									sf.setFundAddStatus(CommonConstants.THREE_STRING);
									sf.setFundStatus(CommonConstants.FOUR_STRING);
								}
								fundMapper.updateById(providentFund);
								//公积金办理成功增加收入
								if (Common.isNotNull(dis.getFundId()) &&
										CommonConstants.THREE_STRING.equals(sf.getFundStatus())){
									int monthDiff;
									// 获取最小的起缴月
									Date minStartDate = this.getMinDate(sf);
									// 再计算月份
									monthDiff = DateUtil.getMonthDiff(minStartDate, new Date()) + 2;
									List<TForecastLibrary> libraryFundInfoList;
									for (int i = 0; i < monthDiff; i++) {
										//获取所有的预估数据
										List<TForecastLibrary> libraryFundInfoList1 = new ArrayList<>();
										libraryFundInfoList = forecastLibraryService.list(Wrappers.<TForecastLibrary>query().lambda()
												.eq(TForecastLibrary::getEmpIdcard, sf.getEmpIdcard())
												.eq(TForecastLibrary::getDataType, CommonConstants.ONE_INT)
												.eq(TForecastLibrary::getSettleDomainId,sf.getSettleDomainFund())
												.eq(TForecastLibrary::getProvidentPayMonth, DateUtil.addMonth(1 - i)));
										if (Common.isNotNull(libraryFundInfoList)) {
											for (TForecastLibrary library :libraryFundInfoList) {
												//办理成功生成收入
												createIncomeInfo(library);
												if (CommonConstants.ZERO_INT == library.getDataPush()) {
													libraryFundInfoList1.add(library);
												}
											}
											if (Common.isNotNull(libraryFundInfoList1)) {
												forecastLibraryService.pushForecastFundInfo(libraryFundInfoList1);
											}
										}
									}

								}
								dis.setFundHandleRemark(ServiceUtil.ifNullToEmpty(handleRemark));
								if (CommonConstants.ZERO_INT == flag) {
									initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_ADD_SUCCESS + handleRemark), CommonConstants.THREE_STRING, user, DispatchConstants.DISPATCH_FUND_ADD_SUCCESS, remark);
								} else {
									initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_ADD_FAIL + handleRemark), CommonConstants.FOUR_STRING, user, DispatchConstants.DISPATCH_FUND_ADD_FAIL, remark);
								}
								auditInfo.setProvidentId(dis.getId());
							} else {
								errorList.add(new ErrorMessage(-1, "找不到对应员工公积金派增派单数据：" + dis.getEmpName()));
								continue;
							}
						}
						//派减处理
					} else if (CommonConstants.ONE_STRING.equals(dis.getType())) {
						//社保派减办理
						if (CommonConstants.ZERO_STRING.equals(typeSub)) {
							if (Common.isNotNull(socialInfo) && Common.isNotNull(socialInfo.getId())) {
								// 社保办理状态补充判断：
								this.setSocialHandleStatus(handleStatus, socialType, flag, socialInfo, dis,sf);
								//社保派减办理成功才变更社保的办理状态
								if (CommonConstants.ZERO_INT == flag) {
									socialInfo.setHandleStatus(CommonConstants.THREE_STRING);
									socialInfo.setReduceHandleUser(user.getId());
									socialInfo.setReduceHandleTime(now);
									if (Common.isNotNull(dis.getSocialReduceDate())) {
										socialInfo.setSocialReduceDate(dis.getSocialReduceDate());
										sf.setSocialReduceDate(dis.getSocialReduceDate());
									}
									sf.setSocialReduceStatus(CommonConstants.TWO_STRING);
									sf.setSocialStatus(CommonConstants.EIGHT_STRING);
								}
								if (CommonConstants.ONE_INT == flag) {
									//派减办理不通过
									socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[0]);//改成可派减状态
									sf.setSocialReduceStatus(CommonConstants.THREE_STRING);
									sf.setSocialStatus(CommonConstants.NINE_STRING);
									sf.setSocialReduceDate(null);
								}
								socialInfo.setHandleTime(now);
								socialInfo.setHandleUser(user.getId());
								socialMapper.updateById(socialInfo);
								dis.setSocialHandleRemark(ServiceUtil.ifNullToEmpty(handleRemark));
								auditInfo = new TAuditInfo();
								auditInfo.setType(CommonConstants.ONE_STRING);
								if (CommonConstants.ZERO_INT == flag) {
									temp.setLength(CommonConstants.ZERO_INT);
									temp.append(DispatchConstants.DISPATCH_SOCIAL_REDUCE);
									temp.append(Common.isNullToString(socialTypeRemark));
									temp.append(DispatchConstants.DISPATCH_HANDLE_SUCCESS);
									temp.append(ServiceUtil.ifNullToEmpty(handleRemark));
									initAuditInfo(auditInfo,temp.toString(), CommonConstants.THREE_STRING, user, temp.toString(), remark);
								} else {
									temp.setLength(CommonConstants.ZERO_INT);
									temp.append(DispatchConstants.DISPATCH_SOCIAL_REDUCE);
									temp.append(Common.isNullToString(socialTypeRemark));
									temp.append(DispatchConstants.DISPATCH_HANDLE_FAIL);
									temp.append(ServiceUtil.ifNullToEmpty(handleRemark));
									initAuditInfo(auditInfo,temp.toString(), CommonConstants.FOUR_STRING, user, temp.toString(), remark);
								}
								dis.setSocialHandleStatus(handleStatus);
								auditInfo.setSocialId(dis.getId());
							} else {
								errorList.add(new ErrorMessage(-1, "找不到对应员工社保数据：" + dis.getEmpName()));
								continue;
							}
							//公积金派减办理
						} else if (CommonConstants.ONE_STRING.equals(typeSub)) {
							if (Common.isNotNull(providentFund) && Common.isNotNull(providentFund.getId())) {
								//公积金派减办理成功才变更公积金的办理状态
								if (CommonConstants.ZERO_INT == flag) {
									providentFund.setHandleStatus(CommonConstants.THREE_STRING);
									providentFund.setReduceHandleTime(now);
									providentFund.setReduceHandleUser(user.getId());
									if (Common.isNotNull(dis.getFundReduceDate())) {
										providentFund.setFundReduceDate(dis.getFundReduceDate());
										sf.setFundReduceDate(dis.getFundReduceDate());
									}
									sf.setFundReduceStatus(CommonConstants.TWO_STRING);
									sf.setFundStatus(CommonConstants.SEVEN_STRING);
								}
								if (CommonConstants.ONE_INT == flag) {
									//派减办理不通过
									providentFund.setReduceCan(CommonConstants.dingleDigitStrArray[0]);//改成可派减状态
									sf.setFundReduceStatus(CommonConstants.THREE_STRING);
									sf.setFundStatus(CommonConstants.EIGHT_STRING);
									sf.setFundReduceDate(null);
								}
								providentFund.setHandleTime(now);
								providentFund.setHandleUser(user.getId());
								fundMapper.updateById(providentFund);
								dis.setFundHandleRemark(ServiceUtil.ifNullToEmpty(handleRemark));
								if (CommonConstants.ZERO_INT == flag) {
									initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_REDUCE_SUCCESS + handleRemark), CommonConstants.SIX_STRING, user, DispatchConstants.DISPATCH_FUND_REDUCE_SUCCESS, remark);
									dis.setFundHandleStatus(CommonConstants.ONE_STRING);
								} else {
									initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_REDUCE_FAIL + handleRemark), CommonConstants.FOUR_STRING, user, DispatchConstants.DISPATCH_FUND_REDUCE_FAIL, remark);
									dis.setFundHandleStatus(CommonConstants.TWO_STRING);
								}
								auditInfo.setProvidentId(dis.getId());
							} else {
								errorList.add(new ErrorMessage(-1, "找不到对应员工公积金数据：" + dis.getEmpName()));
								continue;
							}
						}

					}
					//更新派单状态
					if (Common.isNotNull(auditInfo)) {
						//派增判断
						if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
							if (Common.isNotNull(dis.getSocialHandleStatus())
									&& Common.isNotNull(dis.getFundHandleStatus())
									&& (CommonConstants.ONE_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.THREE_STRING.equals(dis.getSocialHandleStatus()))
									&& (CommonConstants.ONE_STRING.equals(dis.getFundHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getFundHandleStatus()))) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
							if (Common.isEmpty(dis.getSocialHandleStatus())
									&& (CommonConstants.ONE_STRING.equals(dis.getFundHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getFundHandleStatus()))) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
							if ((CommonConstants.ONE_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.THREE_STRING.equals(dis.getSocialHandleStatus()))
									&& Common.isEmpty(dis.getFundHandleStatus())) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
							//派减判断
						} else if (CommonConstants.ONE_STRING.equals(dis.getType())) {
							if (Common.isNotNull(dis.getSocialId())
									&& Common.isNotNull(dis.getFundId())
									&& (CommonConstants.ONE_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getSocialHandleStatus()))
									&& (CommonConstants.ONE_STRING.equals(dis.getFundHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getFundHandleStatus()))) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
							if (Common.isEmpty(dis.getSocialId()) &&  Common.isNotNull(dis.getFundId())
									&& (CommonConstants.ONE_STRING.equals(dis.getFundHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getFundHandleStatus()))) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
							if (Common.isEmpty(dis.getFundId()) && Common.isNotNull(dis.getSocialId())
									&&(CommonConstants.ONE_STRING.equals(dis.getSocialHandleStatus())
									|| CommonConstants.TWO_STRING.equals(dis.getSocialHandleStatus()))) {
								//办理成功
								dis.setStatus(CommonConstants.FOUR_STRING);
							}
						}
						dis.setHandleRemark(ServiceUtil.ifNullToEmpty(handleRemark));
						//新增办理记录信息
						auditInfo.setDispatchInfoId(dis.getId());
						auditInfo.setEmpIdcard(dis.getEmpIdcard());
						if (auditFlag){
							auditInfoMapper.insert(auditInfo);
						}
						baseMapper.updateById(dis);
						socialFundMapper.updateById(sf);
						//1.派增办理失败 刷新预估数据
						if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
							// 全部办理失败 社保和公积金派增办理失败 减少预估
							if (CommonConstants.ONE_INT == flag
									&& (CommonConstants.FIVE_STRING.equals(sf.getSocialStatus())
									|| CommonConstants.FOUR_STRING.equals(sf.getFundStatus()))){
								// 派增办理，全部失败 同步预估库数据
								forecastLibraryService.updateForecastLibaryByDispatchReduce(sf, forecastFlag);
							}
							// 社保办理只要办理成功就刷新预估数据  公积金办理不用处理
							if (Common.isNotNull(dis.getSocialId())
									&& CommonConstants.FOUR_STRING.equals(sf.getSocialStatus())
									|| CommonConstants.TWO_STRING.equals(sf.getSocialStatus())
									|| CommonConstants.THREE_STRING.equals(sf.getSocialStatus())){
								forecastLibraryService.updateForecastLibaryByDispatch(sf);
							}
						}
						//  2.派减办理成功  处理预估 (不管社保还是公积金办理失败)
						if (CommonConstants.ONE_STRING.equals(dis.getType())
								&& CommonConstants.ZERO_INT == flag){
							// 同步预估库数据
							forecastLibraryService.updateForecastLibaryByDispatchReduce(sf, forecastFlag);
						}
						// 派减办理失败不同步档案的相关字段信息
						if (!(CommonConstants.ONE_STRING.equals(dis.getType()) && CommonConstants.ONE_INT == flag)){
							UpProjectSocialFundVo vo = new UpProjectSocialFundVo();
							// 社保状态 社保状态（字典）: 0 无社保 1 处理中 2.部分购买 3.正常 4.已派减
							initSocialFundStatus(socialInfo, providentFund, vo,sf);
							vo.setEmpIdCard(dis.getEmpIdcard());
							vo.setDepartNo(dis.getSettleDomainCode());
							R<Boolean> resUp = archivesDaprUtil.updateProjectSocialFund(vo);
							if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()){
								ServiceUtil.runTimeExceptionDiy(DispatchConstants.DISPATCH_SYN_DOC_EXE);
							}
						}
					} else {
						errorList.add(new ErrorMessage(-1, "派单数据错误！"));
					}
				}
			} catch(Exception e){
				log.error(DispatchConstants.DISPATCH_EXCEPTION, e);
				errorList.add(new ErrorMessage(-1, DispatchConstants.DISPATCH_EXCEPTION + e.getMessage()));
				return errorList;
			}
		} else{
			errorList.add(new ErrorMessage(-1, DispatchConstants.NO_OPERATOR_DATA));
			return errorList;
		}
		return errorList;
	}

	/**
	 * @param dis
	 * @Description: 获取办理/审核时，要变更的预估库的种类
	 * @Author: hgw
	 * @Date: 2022/8/9 11:24
	 * @return: int
	 **/
	private int getForecastFlag(TDispatchInfo dis) {
		int forecastFlag;
		forecastFlag = CommonConstants.ZERO_INT;
		if (Common.isNotNull(dis.getSocialId())) {
			forecastFlag = CommonConstants.ONE_INT;
			if (Common.isNotNull(dis.getFundId())) {
				forecastFlag = CommonConstants.ZERO_INT;
			}
		} else if (Common.isNotNull(dis.getFundId())) {
			forecastFlag = CommonConstants.TWO_INT;
		}
		return forecastFlag;
	}
	/**
	 * @Author fxj
	 * @Description 派增：
	 * 	 * 1、派单处社保或公积金状态为待审核、待办理、办理中，项目档案处社保或公积金状态为处理中1；
	 * 	 * 2、派单处社保或公积金状态为审核不通过或办理失败，项目档案处社保状态为无社保，公积金状态为无公积金0；
	 * 	 * 3、派单处社保状态为部分办理失败，项目档案处社保状态为部分购买 2
	 * 	 * 4、派单处社保或公积金状态为办理成功，项目档案处社保或公积金状态为正常 3
	 * 	 * 派减：
	 * 	 * 1、派减状态为待审核、待办理、审核不通过、办理失败，项目档案处社保或公积金状态不变；
	 * 	 * 2、派减状态为办理成功，项目档案处社保或公积金状态变为已派减 4
	 * 	 * 人员档案处社保或公积金状态根据身份证+项目进行整合：
	 * 	 * 社保状态优先级：正常>部分购买>处理中>已派减>无社保
	 * 	 * 公积金状态优先级：正常>处理中>已派减>无公积金
	 * @Date 15:18 2022/8/9
	 * @Param
	 * @return
	**/
	private void initSocialFundStatus(TSocialInfo socialInfo, TProvidentFund providentFund, UpProjectSocialFundVo vo, TSocialFundInfo sf) {
		if (Common.isNotNull(socialInfo)){
			// 办理失败或审核不通过且无办理成功项
			if (CommonConstants.FIVE_STRING.equals(sf.getSocialStatus())
					|| (CommonConstants.TEN_STRING.equals(sf.getSocialStatus())
					&& !CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
					&& !CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
					&& !CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
					&& !CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
					&& !CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
					&& !(CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
					&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness())))
			){
				vo.setSocialStatus(CommonConstants.ZERO_STRING);
			}
			// 待办理或办理中或部分办理失败或审核不通过部分办理成功 处理中
			if (CommonConstants.ZERO_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.TWO_STRING.equals(sf.getSocialStatus())){
				vo.setSocialStatus(CommonConstants.ONE_STRING);
			}
			// 部分办理失败或审核不通过部分办理成功
			if (CommonConstants.FOUR_STRING.equals(sf.getSocialStatus())
					|| (CommonConstants.TEN_STRING.equals(sf.getSocialStatus())
					&& (CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
					|| (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
					&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness()))
			))){
				vo.setSocialStatus(CommonConstants.TWO_STRING);
			}
			if (CommonConstants.THREE_STRING.equals(sf.getSocialStatus())){
				vo.setSocialStatus(CommonConstants.THREE_STRING);
			}
			if (CommonConstants.EIGHT_STRING.equals(sf.getSocialStatus())){
				vo.setSocialStatus(CommonConstants.FOUR_STRING);
			}
		}
		// 公积金状态 社保状态（字典）: 0 无社保 1 处理中 2.正常 3.已派减
		if (Common.isNotNull(providentFund)){
			if (CommonConstants.TWO_STRING.equals(providentFund.getHandleStatus())
					|| CommonConstants.TWO_STRING.equals(providentFund.getAuditStatus())){
				vo.setFundStatus(CommonConstants.ZERO_STRING);
			}
			if (CommonConstants.ZERO_STRING.equals(providentFund.getHandleStatus())){
				vo.setFundStatus(CommonConstants.ONE_STRING);
			}
			if (CommonConstants.ONE_STRING.equals(providentFund.getHandleStatus())){
				vo.setFundStatus(CommonConstants.TWO_STRING);
			}
			if (CommonConstants.THREE_STRING.equals(providentFund.getHandleStatus())){
				vo.setFundStatus(CommonConstants.THREE_STRING);
			}
		}
	}

	private StringBuilder getHandleRemark(String socialType, TSocialInfo socialInfo) {
		StringBuilder socialTypeRemark;
		socialTypeRemark = new StringBuilder();
		if (Common.isNotNull(socialType)) {
			String[] stArr = socialType.split(",");
			for (String st : stArr) {
				// socialType （1养老 2医疗 3失业 4工伤 5生育 6大病）
				if (Integer.parseInt(st) == CommonConstants.ONE_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getPensionHandle())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
				if (Integer.parseInt(st) == CommonConstants.TWO_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getMedicalHandle())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
				if (Integer.parseInt(st) == CommonConstants.THREE_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getUnemployHandle())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
				if (Integer.parseInt(st) == CommonConstants.FOUR_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getWorkInjuryHandle())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
				if (Integer.parseInt(st) == CommonConstants.FIVE_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getBirthHandle())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
				if (Integer.parseInt(st) == CommonConstants.SIX_INT
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())){
					socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
				}
			}
			if (Common.isNotNull(socialTypeRemark.toString())){
				socialTypeRemark.deleteCharAt(socialTypeRemark.length()-1);
			}
		}
		return socialTypeRemark;
	}
	/**
	 * @param flag 0审核通过； 1审核不通过
	 * @param socialInfo
	 * @param dis
	 * @param socialType  社保拆分的每一项（1养老 2医疗 3失业 4工伤 5生育 6大病）
	 * @Description: 判断社保状态并塞值
	 * @Author: fxj
	 * @Date: 2022-07-26
	 * @return: void
	 **/
	private void setSocialHandleStatus(String handleStatus, String socialType, int flag, TSocialInfo socialInfo
			, TDispatchInfo dis, TSocialFundInfo  sf) {
		// 办理成功 处理社保相关数据 （直接排除五险）
		updateSocialByHandle(flag, socialInfo, dis, sf);
		// 批量办理，或者办理选择对应的类型，修改对应的办理状态
		this.setSocialSixStatus(handleStatus, socialType, socialInfo,sf);
		boolean handleing = CommonConstants.FOUR_STRING.equals(socialInfo.getHandleStatus());
		// HandleStatus办理状态 0 未办理 1 全部办理成功(原-已办理) 2 全部办理失败（原-办理失败） 3已派减 4办理中 5部分办理失败
		// 派减，审核不通过，社保状态不变更
		// 1.派减处理
		if (CommonConstants.ONE_STRING.equals(dis.getType())){
			//办理成功 (办理失败不做处理，预估在另外的地方处理)
			if (CommonConstants.ZERO_INT == flag){
				// 同步社保分项办理状态
				socialInfo.setPensionHandle(CommonConstants.THREE_STRING);
				socialInfo.setMedicalHandle(CommonConstants.THREE_STRING);
				socialInfo.setUnemployHandle(CommonConstants.THREE_STRING);
				socialInfo.setWorkInjuryHandle(CommonConstants.THREE_STRING);
				socialInfo.setBirthHandle(CommonConstants.THREE_STRING);
				socialInfo.setHandleStatus(CommonConstants.THREE_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[1]);//改成不可派减状态
				sf.setSocialReduceStatus(CommonConstants.TWO_STRING);
				sf.setSocialStatus(CommonConstants.EIGHT_STRING);
				sf.setPensionHandle(CommonConstants.THREE_STRING);
				sf.setMedicalHandle(CommonConstants.THREE_STRING);
				sf.setUnemployHandle(CommonConstants.THREE_STRING);
				sf.setWorkInjuryHandle(CommonConstants.THREE_STRING);
				sf.setBirthHandle(CommonConstants.THREE_STRING);
				sf.setHandleStatus(CommonConstants.THREE_STRING);
				if (CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())){
					sf.setBigailmentHandle(CommonConstants.THREE_STRING);
					socialInfo.setBigailmentHandle(CommonConstants.THREE_STRING);
				}
			}
			//办理失败不做处理,只更新社保公积金查询状态
			if (CommonConstants.ONE_INT == flag){
				sf.setSocialReduceStatus(CommonConstants.THREE_STRING);
				sf.setSocialStatus(CommonConstants.NINE_STRING);
			}
		}
		// 2.派增处理 socialType  社保拆分的每一项（1养老 2医疗 3失业 4工伤 5生育 6大病）
		if (CommonConstants.ZERO_STRING.equals(dis.getType()) && Common.isNotNull(dis.getSocialId())){
			//办理成功 flag=0 办理失败 flag=1
			// 派增：
			if ((Common.isEmpty(sf.getPensionHandle()) || CommonConstants.ONE_STRING.equals(sf.getPensionHandle()))
					&& (Common.isEmpty(sf.getMedicalHandle()) || CommonConstants.ONE_STRING.equals(sf.getMedicalHandle()))
					&& (Common.isEmpty(sf.getUnemployHandle()) || CommonConstants.ONE_STRING.equals(sf.getUnemployHandle()))
					&& (Common.isEmpty(sf.getWorkInjuryHandle()) || CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle()))
					&& (Common.isEmpty(sf.getBirthHandle()) || CommonConstants.ONE_STRING.equals(sf.getBirthHandle()))
					&& (Common.isEmpty(sf.getBigailmentHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
					|| CommonConstants.THREE_STRING.equals(sf.getBigailmentHandle()))) {
				// 全部成功（或者为空--兼容历史数据问题）：全部成功
				socialInfo.setHandleStatus(CommonConstants.ONE_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[0]);//改成可派减状态
				sf.setSocialStatus(CommonConstants.THREE_STRING);
				sf.setSocialAddStatus(CommonConstants.TWO_STRING);
				sf.setSocialReduceStatus(CommonConstants.ONE_STRING_NEGATE);
				sf.setSocialReduceDate(null);
				dis.setSocialHandleStatus(CommonConstants.ONE_STRING);
			} else if ((Common.isEmpty(sf.getPensionHandle()) || CommonConstants.TWO_STRING.equals(sf.getPensionHandle()))
					&& (Common.isEmpty(sf.getMedicalHandle()) || CommonConstants.TWO_STRING.equals(sf.getMedicalHandle()))
					&& (Common.isEmpty(sf.getUnemployHandle()) || CommonConstants.TWO_STRING.equals(sf.getUnemployHandle()))
					&& (Common.isEmpty(sf.getWorkInjuryHandle()) || CommonConstants.TWO_STRING.equals(sf.getWorkInjuryHandle()))
					&& (Common.isEmpty(sf.getBirthHandle()) || CommonConstants.TWO_STRING.equals(sf.getBirthHandle()))
					&& (Common.isEmpty(sf.getBigailmentHandle())
					|| CommonConstants.TWO_STRING.equals(sf.getBigailmentHandle())
					|| CommonConstants.THREE_STRING.equals(sf.getBigailmentHandle()))
					) {
				// 全部失败（或者为空）：全部失败
				socialInfo.setHandleStatus(CommonConstants.TWO_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[1]);//改成不可派减状态
				sf.setSocialStatus(CommonConstants.FIVE_STRING);
				sf.setSocialAddStatus(CommonConstants.FOUR_STRING);
				dis.setSocialHandleStatus(CommonConstants.TWO_STRING);
			} else if ((Common.isEmpty(sf.getPensionHandle()) || CommonConstants.ZERO_STRING.equals(sf.getPensionHandle()))
					|| (Common.isEmpty(sf.getMedicalHandle()) || CommonConstants.ZERO_STRING.equals(sf.getMedicalHandle()))
					|| (Common.isEmpty(sf.getUnemployHandle()) || CommonConstants.ZERO_STRING.equals(sf.getUnemployHandle()))
					|| (Common.isEmpty(sf.getWorkInjuryHandle()) || CommonConstants.ZERO_STRING.equals(sf.getWorkInjuryHandle()))
					|| (Common.isEmpty(sf.getBirthHandle()) || CommonConstants.ZERO_STRING.equals(sf.getBirthHandle()))
					|| (Common.isNotNull(sf.getBigailmentHandle()) && CommonConstants.ZERO_STRING.equals(sf.getBigailmentHandle())
					)) {
				// 含有办理中的：办理中
				socialInfo.setHandleStatus(CommonConstants.FOUR_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[1]);//改成不可派减状态
				sf.setSocialStatus(CommonConstants.TWO_STRING);
				sf.setSocialAddStatus(CommonConstants.SIX_STRING);
				dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
				dis.setStatus(CommonConstants.TWO_STRING);
				//排除兼职工伤的情况
			} else {
				// 其他：部分办理失败
				socialInfo.setHandleStatus(CommonConstants.FIVE_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[0]);//改成可派减状态
				sf.setSocialStatus(CommonConstants.FOUR_STRING);
				sf.setSocialAddStatus(CommonConstants.THREE_STRING);
				dis.setSocialHandleStatus(CommonConstants.THREE_STRING);
			}
			if (handleing){
				dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
				dis.setStatus(CommonConstants.TWO_STRING);
				socialInfo.setHandleStatus(CommonConstants.FOUR_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[1]);//改成不可派减状态
				sf.setSocialStatus(CommonConstants.TWO_STRING);
				sf.setSocialAddStatus(CommonConstants.SIX_STRING);
			}
		}
	}

	private void updateSocialByHandle(int flag, TSocialInfo socialInfo, TDispatchInfo dis, TSocialFundInfo sf) {
		if (CommonConstants.ZERO_INT== flag
				&& CommonConstants.ZERO_STRING.equals(dis.getType())
				&& Common.isNotNull(dis.getSocialId())){
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
					&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())){
				sf.setUnitBigailmentMoney(socialInfo.getUnitBigailmentMoney());
				sf.setPersonalBigailmentMoney(socialInfo.getPersonalBigailmentMoney());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getPensionHandle())){
				sf.setUnitPensionCardinal(socialInfo.getUnitPensionCardinal());
				sf.setPersonalPensionCardinal(socialInfo.getPersonalPensionCardinal());
				sf.setUnitPensionPer(socialInfo.getUnitPensionPer());
				sf.setPersonalPensionPer(socialInfo.getPersonalPensionPer());
				sf.setUnitPersionMoney(BigDecimalUtils.safeMultiply(socialInfo.getUnitPensionCardinal(), socialInfo.getUnitPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setPersonalPersionMoney(BigDecimalUtils.safeMultiply(socialInfo.getPersonalPensionCardinal(), socialInfo.getPersonalPensionPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setPensionHandle(socialInfo.getPensionHandle());
				sf.setPensionStart(socialInfo.getPensionStart());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getMedicalHandle())){
				sf.setUnitMedicalCardinal(socialInfo.getUnitMedicalCardinal());
				sf.setPersonalMedicalCardinal(socialInfo.getPersonalMedicalCardinal());
				sf.setUnitMedicalPer(socialInfo.getUnitMedicalPer());
				sf.setPersonalMedicalPer(socialInfo.getPersonalMedicalPer());
				sf.setUnitMedicalMoney(BigDecimalUtils.safeMultiply(socialInfo.getUnitMedicalCardinal(), socialInfo.getUnitMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setPersonalMedicalMoney(BigDecimalUtils.safeMultiply(socialInfo.getPersonalMedicalCardinal(), socialInfo.getPersonalMedicalPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setMedicalHandle(socialInfo.getMedicalHandle());
				sf.setMedicalStart(socialInfo.getMedicalStart());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getUnemployHandle())){
				sf.setUnitUnemploymentCardinal(socialInfo.getUnitUnemploymentCardinal());
				sf.setPersonalUnemploymentCardinal(socialInfo.getPersonalUnemploymentCardinal());
				sf.setPersonalUnemploymentPer(socialInfo.getPersonalUnemploymentPer());
				sf.setUnitUnemploymentPer(socialInfo.getUnitUnemploymentPer());
				sf.setUnitUnemploymentMoney(BigDecimalUtils.safeMultiply(socialInfo.getUnitUnemploymentCardinal(), socialInfo.getUnitUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setPersonalUnemploymentMoney(BigDecimalUtils.safeMultiply(socialInfo.getPersonalUnemploymentCardinal(), socialInfo.getPersonalUnemploymentPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setUnemployHandle(socialInfo.getUnemployHandle());
				sf.setUnemployStart(socialInfo.getUnemployStart());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
					&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())){
				sf.setUnitBigailmentCardinal(socialInfo.getUnitBigailmentCardinal());
				sf.setPersonalBigailmentCardinal(socialInfo.getPersonalBigailmentCardinal());
				sf.setUnitBigailmentPer(socialInfo.getUnitBigailmentPer());
				sf.setPersonalBigailmentPer(socialInfo.getPersonalBigailmentPer());
				sf.setUnitBigailmentMoney(socialInfo.getUnitBigailmentMoney());
				sf.setPersonalBigailmentMoney(socialInfo.getPersonalBigailmentMoney());
				sf.setBigailmentHandle(socialInfo.getBigailmentHandle());
				sf.setBigailmentStart(socialInfo.getBigailmentStart());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getWorkInjuryHandle())){
				sf.setUnitWorkInjuryCardinal(socialInfo.getUnitWorkInjuryCardinal());
				sf.setUnitWorkUnjuryPer(socialInfo.getUnitWorkUnjuryPer());
				sf.setUnitInjuryMoney(BigDecimalUtils.safeMultiply(socialInfo.getUnitWorkInjuryCardinal(), socialInfo.getUnitWorkUnjuryPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setWorkInjuryHandle(socialInfo.getWorkInjuryHandle());
				sf.setWorkInjuryStart(socialInfo.getWorkInjuryStart());
			}
			if (CommonConstants.ZERO_STRING.equals(socialInfo.getBirthHandle())){
				sf.setUnitBirthCardinal(socialInfo.getUnitBirthCardinal());
				sf.setUnitBirthPer(socialInfo.getUnitBirthPer());
				sf.setUnitBirthMoney(BigDecimalUtils.safeMultiply(socialInfo.getUnitBirthCardinal(), socialInfo.getUnitBirthPer(),BigDecimal.valueOf(CommonConstants.ONE_OF_PERCENT.doubleValue())));
				sf.setBirthHandle(socialInfo.getBirthHandle());
				sf.setBirthStart(socialInfo.getBirthStart());
			}

			sf.setUnitSocialSum(BigDecimalUtils.safeAdd(sf.getUnitPersionMoney()
					, sf.getUnitMedicalMoney(), sf.getUnitBirthMoney()
					, sf.getUnitInjuryMoney()
					, sf.getUnitUnemploymentMoney()
					, sf.getUnitBigailmentMoney()));
			sf.setPersonalSocialSum(BigDecimalUtils.safeAdd(sf.getPersonalBigailmentMoney()
					, sf.getPersonalPersionMoney()
					, sf.getPersonalMedicalMoney()
					, sf.getPersonalUnemploymentMoney()));
		}
	}

	/**
	 * @param handleStatus
	 * @param socialType
	 * @param socialInfo
	 * @param sf
	 * @Description: 填充社保的新的六个状态字段
	 * @Author: hgw
	 * @Date: 2021/6/9 17:12
	 * @return: void
	 **/
	private void setSocialSixStatus(String handleStatus, String socialType, TSocialInfo socialInfo, TSocialFundInfo sf) {
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.ONE_STRING))
				&& Common.isNotNull(socialInfo.getPensionHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getPensionHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getPensionHandle())) {
			socialInfo.setPensionHandle(handleStatus);
			sf.setPensionHandle(handleStatus);
		}
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.TWO_STRING))
				&& Common.isNotNull(socialInfo.getMedicalHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getMedicalHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())) {
			socialInfo.setMedicalHandle(handleStatus);
			sf.setMedicalHandle(handleStatus);
		}
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.THREE_STRING))
				&& Common.isNotNull(socialInfo.getUnemployHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getUnemployHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())) {
			socialInfo.setUnemployHandle(handleStatus);
			sf.setUnemployHandle(handleStatus);
		}
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.FOUR_STRING))
				&& Common.isNotNull(socialInfo.getWorkInjuryHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getWorkInjuryHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())) {
			socialInfo.setWorkInjuryHandle(handleStatus);
			sf.setWorkInjuryHandle(handleStatus);
		}
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.FIVE_STRING))
				&& Common.isNotNull(socialInfo.getBirthHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getBirthHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getBirthHandle())) {
			socialInfo.setBirthHandle(handleStatus);
			sf.setBirthHandle(handleStatus);
		}
		if ((Common.isEmpty(socialType) || socialType.contains(CommonConstants.SIX_STRING))
				&& Common.isNotNull(socialInfo.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
				&& !CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness())) {
			socialInfo.setBigailmentHandle(handleStatus);
			sf.setBigailmentHandle(handleStatus);
		}
		// 单个办理的时候处理派单和社保的办理状态  有办理成功也有办理失败的 为办理中
		if ((CommonConstants.ONE_STRING.equals(socialInfo.getPensionHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getPensionHandle())
				|| CommonConstants.ONE_STRING.equals(socialInfo.getMedicalHandle())
				|| CommonConstants.ONE_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| CommonConstants.ONE_STRING.equals(socialInfo.getBirthHandle())
				|| CommonConstants.ONE_STRING.equals(socialInfo.getUnemployHandle())
				|| (CommonConstants.ONE_STRING.equals(socialInfo.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness()))
				|| CommonConstants.TWO_STRING.equals(socialInfo.getMedicalHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getBirthHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getUnemployHandle())
				|| (CommonConstants.TWO_STRING.equals(socialInfo.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())))
				&& (CommonConstants.ZERO_STRING.equals(socialInfo.getPensionHandle())
				|| CommonConstants.ZERO_STRING.equals(socialInfo.getMedicalHandle())
				|| CommonConstants.ZERO_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| CommonConstants.ZERO_STRING.equals(socialInfo.getBirthHandle())
				|| CommonConstants.ZERO_STRING.equals(socialInfo.getUnemployHandle())
				|| (CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
				&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())))
		){
			socialInfo.setHandleStatus(CommonConstants.FOUR_STRING);
		}
	}
	/**
	 * @Author fxj
	 * @Description  导出 社保花名册
	 * @Date 17:40 2022/7/27
	 * @Param
	 * @return
	 **/
	@Override
	public void doexportSocialRecordRoster(HttpServletResponse response, SocialHandleSearchVo searchVo, String idStr, String[] exportFields) {
		String fileName = DispatchConstants.SOCIAL_RECORD_ROSTER_EXPORT + CommonConstants.XLSX;
		//获取要导出的列表
		List<SocialHandleExportVo> list = new ArrayList<>();
		long count = getRecordRosterCount(searchVo,idStr);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, SocialHandleExportVo.class).build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getRecordRosterList(searchVo,idStr);
					if (Common.isNotNull(list)){
						ExcelUtil<SocialHandleExportVo> util = new ExcelUtil<>(SocialHandleExportVo.class);
						for (SocialHandleExportVo vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						WriteSheet writeSheet = EasyExcel.writerSheet(DispatchConstants.SOCIAL_RECORD_ROSTER_EXPORT+index).build();
						excelWriter.write(list,writeSheet);
						index++;
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
				excelWriter.finish();
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet(DispatchConstants.SOCIAL_RECORD_ROSTER_EXPORT+index).build();
				excelWriter.write(list,writeSheet);
				excelWriter.finish();
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * @Author fxj
	 * @Description  社保花名册 count
	 * @Date 17:59 2022/7/27
	 * @Param
	 * @return
	**/
	private int getRecordRosterCount(SocialHandleSearchVo searchVo, String idStr) {
		List<String> ids = new ArrayList<>();
		if (Common.isNotNull(idStr)){
			ids = Common.initStrToList(idStr,CommonConstants.COMMA_STRING);
		}
		return baseMapper.getSocialRecordRosterListCount(searchVo,ids);
	}
	/**
	 * @Author fxj
	 * @Description  社保花名册 list
	 * @Date 17:59 2022/7/27
	 * @Param
	 * @return
	 **/
	private List<SocialHandleExportVo> getRecordRosterList(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.getSocialRecordRosterList(searchVo,Common.getList(idStr));
	}

	@Override
	public IPage<TDispatchInfo> getTDispatchSocialHandlePage(Page<TDispatchInfo> page, SocialHandleSearchVo tDispatchInfo) {
		return baseMapper.getTDispatchSocialHandlePage(page,tDispatchInfo,null);
	}

	@Override
	public IPage<TDispatchInfo> getTDispatchFundHandlePage(Page<TDispatchInfo> page, SocialHandleSearchVo tDispatchInfo) {
		return baseMapper.getTDispatchFundHandlePage(page,tDispatchInfo,null);
	}
	/**
	 * 导出公积金补缴清册
	 * @Author fxj
	 * @Date 2020-06-08
	 * @param idStr
	 * @param searchVo
	 * @return
	 **/
	@Override
	public R<List<FundSupplementaryExportVo>> getFundSupplementaryRecords(String idStr, SocialHandleSearchVo searchVo, List<String> settleDomains, String sql) {
		return R.ok(baseMapper.getFundSupplementaryRecords(searchVo,Common.getList(idStr),settleDomains,sql));
	}
	/**
	 * @Author fxj
	 * @Description 导出公积金补缴清册
	 * @Date 20:05 2022/7/27
	 * @Param
	 * @return
	 **/
	@Override
	public void doexportFundRecordChange(HttpServletResponse response,String idStr, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.SOCIAL_RECORD_EXPORT + LocalDateTime.now() + CommonConstants.XLSX;
		//获取要导出的列表
		List<FundHandleExportVo> list = new ArrayList<>();
		long count = getFundRecordCount(searchVo,idStr);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, FundHandleExportVo.class).build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getFundRecordList(searchVo,idStr);
					if (Common.isNotNull(list)){
						ExcelUtil<FundHandleExportVo> util = new ExcelUtil<>(FundHandleExportVo.class);
						for (FundHandleExportVo vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						WriteSheet writeSheet = EasyExcel.writerSheet("公积金变更清册"+index).build();
						excelWriter.write(list,writeSheet);
						index++;
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
				excelWriter.finish();
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("公积金变更清册"+index).build();
				excelWriter.write(list,writeSheet);
				excelWriter.finish();
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	private List<FundHandleExportVo> getFundRecordList(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.getFundRecordList(searchVo,Common.getList(idStr));
	}

	private long getFundRecordCount(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.getFundRecordCount(searchVo,Common.getList(idStr));
	}

	/**
	 * @param socialFundInfo
	 * @Description: 获取最小起缴日
	 * @Author: hgw
	 * @Date: 2022/7/29 11:06
	 * @return: java.util.Date
	 **/
	private Date getMinDate(TSocialFundInfo socialFundInfo) {
		Date minStartDate = null;
		if (socialFundInfo.getSocialStartDate() != null) {
			minStartDate = socialFundInfo.getSocialStartDate();
			if (socialFundInfo.getUnitPersionMoney() != null && socialFundInfo.getPensionStart() != null && socialFundInfo.getPensionStart().before(minStartDate)) {
				minStartDate = socialFundInfo.getPensionStart();
			}
			if (socialFundInfo.getUnitMedicalMoney() != null && socialFundInfo.getMedicalStart() != null && socialFundInfo.getMedicalStart().before(minStartDate)) {
				minStartDate = socialFundInfo.getMedicalStart();
			}
			if (socialFundInfo.getUnitUnemploymentMoney() != null && socialFundInfo.getUnemployStart() != null && socialFundInfo.getUnemployStart().before(minStartDate)) {
				minStartDate = socialFundInfo.getUnemployStart();
			}
			if (socialFundInfo.getUnitInjuryMoney() != null && socialFundInfo.getWorkInjuryStart() != null && socialFundInfo.getWorkInjuryStart().before(minStartDate)) {
				minStartDate = socialFundInfo.getWorkInjuryStart();
			}
			if (socialFundInfo.getUnitBirthMoney() != null && socialFundInfo.getBirthStart() != null && socialFundInfo.getBirthStart().before(minStartDate)) {
				minStartDate = socialFundInfo.getBirthStart();
			}
		}
		if (socialFundInfo.getProvidentStart() != null
				&& (null == minStartDate || socialFundInfo.getProvidentStart().before(minStartDate))) {
			minStartDate = socialFundInfo.getProvidentStart();
		}
		if (null == minStartDate) {
			minStartDate = new Date();
		}
		return minStartDate;
	}

	public void createIncomeInfo(TForecastLibrary library) {
		//获取项目信息
		TSettleDomain settleDomain = new TSettleDomain();
		List<TSettleDomainSelectVo> settleDomainR = null;
		R<TSettleDomainListVo> listVo = null;
		listVo = archivesDaprUtil.selectSettleDomainSelectVoById(library.getSettleDomainId());
		if (Common.isNotNull(listVo)) {
			TSettleDomainListVo tSettleDomainListVo = listVo.getData();
			if (Common.isNotNull(tSettleDomainListVo) && Common.isNotEmpty(tSettleDomainListVo.getListSelectVO())) {
				settleDomainR = tSettleDomainListVo.getListSelectVO();
				for (TSettleDomainSelectVo vo :settleDomainR) {
					BeanUtils.copyProperties(vo,settleDomain);
				}
			}
		}

		//判断是否存在当月的公积金收入数据
		Boolean isExist = false;
		TIncomeDetail incomeDetail = new TIncomeDetail();
		incomeDetail.setEmpIdcard(library.getEmpIdcard());
		incomeDetail.setPayMonth(library.getProvidentPayMonth());
		incomeDetail.setDeptNo(library.getDeptNo());
		incomeDetail.setSourceType(CommonConstants.TWO_STRING);
		List<TIncomeDetail> detailList = detailService.getTIncomeDetailList(incomeDetail);
		if (Common.isNotNull(detailList)) {
			BigDecimal sumMoney = BigDecimal.ZERO;
			for (TIncomeDetail income : detailList) {
				sumMoney = BigDecimalUtils.safeAdd(income.getMoney(),sumMoney);
			}
			if (sumMoney.compareTo(BigDecimal.ZERO) == CommonConstants.ONE_INT) {
				isExist = true;
			}
		}

		int isSum = 0;
		if (Common.isNotNull(settleDomain)) {
			// 含有社保，则计算收入
			if (Common.isNotNull(settleDomain.getManageServerItem()) && settleDomain.getManageServerItem()
					.contains(CommonConstants.TWO_STRING)) {
				//预估模式
				if (CommonConstants.ZERO_STRING.equals(settleDomain.getManagementTag())) {
					if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
						//预估模式只有按人次和人数收费
						if (!isExist) {
							createIncomeInsurance(library, settleDomain, CommonConstants.ONE_STRING,
									settleDomain.getManagementFee().toString(), settleDomain.getManagementType(),
									settleDomain.getManagementFee());
						}
					}
				}
			}
			if (Common.isNotNull(settleDomain.getRiskServerItem()) && settleDomain.getRiskServerItem()
					.contains(CommonConstants.TWO_STRING)) {
				if (CommonConstants.ZERO_STRING.equals(settleDomain.getRiskFundTag())) {
					//预估模式
					if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
						if (!isExist) {
							createIncomeInsurance(library, settleDomain, CommonConstants.TWO_STRING,
									settleDomain.getRiskFundFee().toString(), settleDomain.getRiskFundType(),
									settleDomain.getRiskFundFee());
						}
					}
				}
			}
		}
	}

	public void createIncomeInsurance(TForecastLibrary library, TSettleDomain settleDomain, String feeType,
									  String charges, String feeMode, BigDecimal money) {
		//生成收入数据
		TIncomeDetail detail = new TIncomeDetail();
		detail.setCreateTime(DateUtil.getCurrentDateTime());
		detail.setDeptName(settleDomain.getDepartName());
		detail.setDeptNo(settleDomain.getDepartNo());
		detail.setDeptId(settleDomain.getId());
		detail.setEmpIdcard(library.getEmpIdcard());
		detail.setEmpName(library.getEmpName());
		detail.setUnitNo(settleDomain.getCustomerNo());
		detail.setUnitId(settleDomain.getCustomerId());
		detail.setUnitName(settleDomain.getCustomerName());
		detail.setDataCreateMonth(DateUtil.addMonth(0));
		detail.setSourceId(library.getId());
		detail.setSourceType(CommonConstants.TWO_STRING);
		detail.setCreateMonth(library.getProvidentCreateMonth());
		detail.setPayMonth(library.getProvidentPayMonth());
		detail.setMoney(money);
		detail.setFeeType(feeType);
		detail.setFeeMode(feeMode);
		detail.setCharges(charges);
		detail.setMrSettleType(settleDomain.getMrSettleType());
		detail.setRedData(CommonConstants.ZERO_STRING);
		detail.setId(CommonConstants.NULL);
		incomeService.saveDetail(detail);
	}
}
