/*
 *    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.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
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.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysArea;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AllUserNaVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AreaVo;
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.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.*;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.redis.RedisDistributedLock;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchListVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseServiceParamListVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.*;
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.config.*;
import com.yifu.cloud.plus.v1.yifu.social.constants.DispatchConstants;
import com.yifu.cloud.plus.v1.yifu.social.constants.PreDispatchConstants;
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.*;
import com.yifu.cloud.plus.v1.yifu.social.util.DoSocialTask;
import com.yifu.cloud.plus.v1.yifu.social.util.ExcelMergeImage;
import com.yifu.cloud.plus.v1.yifu.social.util.ExcelToImage;
import com.yifu.cloud.plus.v1.yifu.social.util.ServiceUtil;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang.ArrayUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
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.http.HttpHeaders;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
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 CspDaprUtils cspDaprUtil;

	private final TSocialFundInfoMapper socialFundMapper;

	private final SysBaseSetInfoMapper baseSetMapper;

	private final TSocialInfoMapper socialMapper;

	private final TProvidentFundMapper fundMapper;

	private final TAuditInfoMapper auditInfoMapper;

	private final TDispatchInfoPreMapper dispatchInfoPreMapper;

	private final TSocialAutoLogService socialAutoLogService;

	@Autowired
	private CacheManager cacheManager;

	@Autowired
	private final CheckDaprUtil checkDaprUtil;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	private final TForecastLibraryService forecastLibraryService;

	ExcelUtil<Object> excelUtil = new ExcelUtil<>(Object.class);

	private final MenuUtil menuUtil;

	@Autowired
	private DoSocialTask socialTask;

	private final TDispatchSocialFundInfoService infoService;
	private final TSocialFreindSetService tSocialFreindSetService;
	@Autowired
	private ExcelMergeImage excelMergeImage;
	@Autowired
	private ExcelToImage excelToImage;
	@Autowired
	private OSSUtil ossUtil;

	@Autowired
	private SysHouseHoldInfoMapper houseHoldInfoMapper;

	@Autowired
	private TAttaInfoMapper attaInfoMapper;

	private final TSocialfundHouseResService tSocialfundHouseResService;
	private final TDispatchExportLogService tDispatchExportLogService;

	private final RestTemplate restTemplate;
	private final SocialFriendConfig socialFriendConfig;

	@Autowired
	private TSocialFriendBackLogService socialFriendBackLogService;

	@Autowired
	private WxConfig wxConfig;

	/**
	 * 派单信息记录表简单分页查询
	 *
	 * @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 = exportDispatchCount(searchVo);
		HashMap<String, String> userMap = new HashMap<>();
		try {
			// 获取用户信息
			R<AllUserNaVo> userListR = upmsDaprUtils.getAllUserName();
			if (Common.isNotNull(userListR)) {
				AllUserNaVo userList = userListR.getData();
				if (null != userList && !userList.getUserNames().isEmpty()) {
					userMap = userList.getUserNames();
				}
			}
			// 设置响应头
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
			// 初始化Excel工具
			ExcelUtil<TDispatchInfoExportVo> util = new ExcelUtil<>(TDispatchInfoExportVo.class);
			Map<String, String> nameAndDicTypeMap = util.getConverterDicType();
			Map<String, String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			if (redisLabelMap != null) {
				redisLabelMap.putAll(userMap);
			}
			//  获取输出流
			OutputStream out = null;
			ExcelWriter excelWriter = null;
			try {
				out = response.getOutputStream();
				excelWriter = EasyExcel.write(out, TDispatchInfoExportVo.class)
						.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
						.includeColumnFieldNames(searchVo.getExportFields())
						.build();

				int index = 0;
				if (count > CommonConstants.ZERO_INT) {
					WriteSheet writeSheet;
					for (int i = 0; i <= count; ) {
						searchVo.setLimitStart(i);
						searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
						list = exportDispatch(searchVo);
						if (Common.isNotNull(list)) {
							writeSheet = EasyExcel.writerSheet("派单" + index).build();
							excelWriter.write(list, writeSheet);
							index++;
						}
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
						if (Common.isNotNull(list)) {
							list.clear();
						}
					}
				} else {
					WriteSheet writeSheet = EasyExcel.writerSheet("派单" + index).build();
					excelWriter.write(list, writeSheet);
				}

			} catch (IOException e) {
				log.error("导出文件时发生IO异常", e);
				throw new RuntimeException("导出文件失败", e); // 可以根据需要转换为业务异常
			} finally {
				if (excelWriter != null) {
					try {
						excelWriter.finish();
					} catch (Exception e) {
						log.error("关闭ExcelWriter时发生异常", e);
					}
				}
			}
		}catch (Exception e) {
			log.error("执行导出时发生未知异常", e);
			throw new RuntimeException("导出过程中发生错误", e);
		} finally {
			// 清理列表数据
			if (Common.isNotNull(list)) {
				list.clear();
			}
		}
	}

	@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) {
				WriteSheet writeSheet;
				ExcelUtil<TDispatchAuditExportVo> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = exportAuditDispatch(searchVo);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(TDispatchAuditExportVo.class);
						for (TDispatchAuditExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcel.writerSheet("派单审核" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("派单审核" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	@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);
	}

	// 派单查询的导出list
	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);
	}

	// 派单查询的导出count
	private long exportDispatchCount(TDispatchInfoSearchVo searchVo) {
		if (Common.isNotNull(searchVo.getIds())) {
			List<String> idList = Common.getList(searchVo.getIds());
			searchVo.setIdList(idList);
		}
		return baseMapper.exportDispatchCount(searchVo);
	}

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

	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.like(TDispatchInfo::getCreateName, entity.getCreateName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())) {
			wrapper.eq(TDispatchInfo::getEmpIdcard, entity.getEmpIdcard());
		}
		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);
		Map<String, String> idCardMap = new HashMap<>();
		// 匿名内部类 不用额外写一个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, idCardMap,null);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		} finally {
			Common.clear(idCardMap);
		}
		return this.judgeAllMessage(errorMessageList);
	}

	@Override
	public void importTDispatchInfo(List<TDispatchImportVo> excelVOList,
									List<ErrorMessage> errorMessageList,
									YifuUser user, String orderId,
									Map<String, String> idCardMap,String autoFlag) {
		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, EmpProjectDispatchVo> projectsUpdateMap = 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 = null;
		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);
			if (idCardMap.get(excel.getEmpIdcard()) != null) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "身份证【" + excel.getEmpIdcard() + "】与第" + idCardMap.get(excel.getEmpIdcard()) + "行重复，未导入"));
				excelVOTemp.put(excel.getRowIndex().toString(), excel.getEmpIdcard());
				idCardMap.put(excel.getEmpIdcard(), idCardMap.get(excel.getEmpIdcard()) + "、" + excel.getRowIndex());
				continue;
			} else {
				idCardMap.put(excel.getEmpIdcard(), String.valueOf(excel.getRowIndex()));
			}
			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())
					|| CommonConstants.TWELVE_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;
				}
			} else {
				if (Common.isNotNull(excel.getRecordBase()) || Common.isNotNull(excel.getPensionStart()) ||
						Common.isNotNull(excel.getMedicalStart()) || Common.isNotNull(excel.getBirthStart()) ||
						Common.isNotNull(excel.getBigailmentStart()) || Common.isNotNull(excel.getUnemployStart()) ||
						Common.isNotNull(excel.getWorkInjuryStart()) || Common.isNotNull(excel.getPaymentType()) ||
						Common.isNotNull(excel.getPensionCardinal()) || Common.isNotNull(excel.getBirthCardinal()) ||
						Common.isNotNull(excel.getBigailmentCardinal()) || Common.isNotNull(excel.getMedicalCardinal())
						|| Common.isNotNull(excel.getUnemploymentCardinal()) || Common.isNotNull(excel.getWorkInjuryCardinal())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_HOLD_IS_EMPTY)));
					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;
				}
			} else {
				if (Common.isNotNull(excel.getProvidentStart()) || Common.isNotNull(excel.getProvidentCardinal()) ||
						Common.isNotNull(excel.getProvidentPer())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.FUND_HOLD_IS_EMPTY)));
					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,autoFlag)) {
				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, projectsUpdateMap);
			// 新增社保
			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);
			if (initDispatchAddInfo(user, dispatchMap, empVo, socialSet, fundSet, excel, socialFund, injury)) {
				excelVOTemp.put(excel.getRowIndex().toString(), excel.getEmpIdcard());
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_ITEM_EMPTY_EXISTS)));
				continue;
			}
			if (Common.isNotNull(dispatchMap.get(excel.getEmpIdcard())) && "公积金".equals(dispatchMap.get(excel.getEmpIdcard()).getDispatchItem())) {
				socialsMap.remove(excel.getEmpIdcard());
				excel.setSocialHousehold(null);
			}
			// 变更社保公积金查询
			initSocialFundAddInfo(socialFundAddMap, empVo, socialSet, fundSet, setInfoVo, socialFund, excel);
		}
		addVo.setEmpAddsMap(empAddsMap);
		addVo.setContractsMap(contractsMap);
		addVo.setProjectsMap(projectsMap);
		addVo.setProjectsUpdateMap(projectsUpdateMap);
		R<EmpDispatchAddVo> res = archivesDaprUtil.addDispatchInfo(addVo);
		// 开始插入各种数据了
		insertAllInfo(excelVOList, errorMessageList, empVoMap, 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,
							   Map<String, DispatchEmpVo> empVoMap,
							   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();
		}
		TAuditInfo auditInfo = null;
		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());
							dispatch.setFirstBuyMonthSocial(getFirstBuyMonthSocial(social));
						}
						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());
						}

						insertDispatch(emp, dispatch);
						// 新增派单申请提交记录
						auditInfo = new TAuditInfo();
						addAuditInfo(dispatch, auditInfo);
					}
				}
				//  插入或更新社保公积金查询信息  大病在封装社保的时候已经算了 大病技术和金额了
				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,dispatch);
				}
				// 生成预付数据
				if (Common.isNotNull(socialFund) && Common.isNotNull(socialFund.getId())) {
					forecastLibraryService.updateForecastLibaryByDispatch(null, null, socialFund);
				}
				// 同步更新人员档案和项目档案的社保公积金状态 学历信息

				updateDocSocialFund(social, fund, socialFund, empVoMap, excel);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN));
			} 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 addAuditInfo(TDispatchInfo dispatch, TAuditInfo auditInfo) {
		auditInfo.setEmpIdcard(dispatch.getEmpIdcard());
		auditInfo.setSocialId(dispatch.getSocialId());
		auditInfo.setProvidentId(dispatch.getFundId());
		auditInfo.setAuditStatus(CommonConstants.ZERO_STRING);
		auditInfo.setDispatchInfoId(dispatch.getId());
		auditInfo.setAuditRemark("派单申请提交");
		auditInfo.setTitle("派单申请");
		auditInfo.setOrganName(null != dispatch.getPreId() ? "" : dispatch.getOrganName());
		auditInfo.setAuditUser(dispatch.getCreateName());
		auditInfo.setAuditTime(new Date());
		auditInfo.setIsCommision(CommonConstants.ONE_STRING);
		auditInfoMapper.insert(auditInfo);
	}

	private void updateDocSocialFund(TSocialInfo social, TProvidentFund fund, TSocialFundInfo socialFund, Map<String, DispatchEmpVo> empVoMap, TDispatchImportVo excel) {
		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.setFileProvince(excel.getFileProvince());
		vo.setFileCity(excel.getFileCity());
		vo.setFileTown(excel.getFileTown());
		vo.setMobile(excel.getEmpMobile());
		vo.setEmpIdCard(socialFund.getEmpIdcard());
		DispatchEmpVo emp = null;
		if (Common.isNotNull(empVoMap)) {
			emp = empVoMap.get(excel.getEmpIdcard());
		}
		if (Common.isNotNull(emp) && Common.isEmpty(emp.getEmpRegisType()) && Common.isNotNull(excel.getEmpRegisType())) {
			vo.setEmpRegisType(excel.getEmpRegisType());
		}
		if (Common.isNotNull(excel.getEducationName())) {
			if (Common.isNotNull(emp)) {
				if (Common.isEmpty(emp.getHignEducation())) {
					vo.setHighEducation("");
					if (excel.getEducationName().equals("文盲")) {
						vo.setHighEducation("1");
					}
					if (excel.getEducationName().equals("小学")) {
						vo.setHighEducation("2");
					}
					if (excel.getEducationName().equals("初中")) {
						vo.setHighEducation("3");
					}
					if (excel.getEducationName().equals("高中")) {
						vo.setHighEducation("4");
					}
					if (excel.getEducationName().equals("大专")) {
						vo.setHighEducation("5");
					}
					if (excel.getEducationName().equals("本科")) {
						vo.setHighEducation("6");
					}
					if (excel.getEducationName().equals("硕士")) {
						vo.setHighEducation("7");
					}
					if (excel.getEducationName().equals("博士")) {
						vo.setHighEducation("8");
					}
					if (excel.getEducationName().equals("技工")) {
						vo.setHighEducation("9");
					}
					if (excel.getEducationName().equals("职高")) {
						vo.setHighEducation("10");
					}
					if (excel.getEducationName().equals("中专")) {
						vo.setHighEducation("11");
					}
					if (Common.isNotNull(excel.getSchoolName())) {
						vo.setSchoolName(excel.getSchoolName());
					}
					if (Common.isNotNull(excel.getMajor())) {
						vo.setMajor(excel.getMajor());
					}
					if (Common.isNotNull(excel.getGraduationTime())) {
						vo.setGradutionDate(excel.getGraduationTime());
					}
				}
			}
		}
		R<Boolean> resUp = archivesDaprUtil.updateProjectSocialFund(vo);
		if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()) {
			ServiceUtil.runTimeExceptionDiy(vo.getEmpIdCard() + 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);
			if (Common.isNotNull(dispatch.getPid())) {
				TDispatchInfo old = new TDispatchInfo();
				old.setId(dispatch.getPid());
				old.setAgainDispatchCode(dispatch.getApplyNo());
				baseMapper.updateById(old);
			}
		}
	}

	private void initSocialFundAndInsert(EmpAddDispatchVo emp,
										 TSocialInfo social,
										 TProvidentFund fund,
										 TSocialFundInfo socialFund,
										 EmpProjectDispatchVo project,
										 boolean dispatchPart, boolean injury,TDispatchInfo dispatch) {
		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);
			}
			//派单完成更新社保待购买表的状态
			if (Common.isNotNull(dispatch.getPreId())) {
				TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectById(dispatch.getPreId());
				if (Common.isNotNull(dispatchInfoPre)) {
					dispatchInfoPre.setProcessStatus(CommonConstants.THREE_STRING);
					dispatchInfoPre.setDispatcherId(socialFund.getDispatchId());
					dispatchInfoPre.setSocialFundId(socialFund.getId());
					dispatchInfoPre.setErrorInfo(null);
					dispatchInfoPre.setErrorTime(null);
					dispatchInfoPreMapper.updateById(dispatchInfoPre);
				}
			}
		}
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 获取首次购买月份
	 * @Date 14:12 2022/8/17
	 * @Param
	 **/
	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.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 (CommonConstants.ONE_STRING.equals(socialSet.getIsIllness())
							&& Common.isNotNull(socialFund.getBigailmentHandle())) {
						socialFund.setBigailmentHandle(null);
						socialFund.setBigailmentStart(null);
						socialFund.setUnitBigailmentCardinal(null);
						socialFund.setUnitBigailmentPer(null);
						socialFund.setPersonalBigailmentCardinal(null);
						socialFund.setPersonalBigailmentPer(null);
						socialFund.setPersonalBigailmentMoney(null);
						socialFund.setUnitBigailmentMoney(null);
					}
				}
			}
			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
	 **/
	@Lock4j(keys = "getDispatchApplyCode", expire = 60000, acquireTimeout = 1000)
	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 boolean initDispatchAddInfo(YifuUser user,
										Map<String, TDispatchInfo> dispatchMap,
										DispatchEmpVo empVo,
										SysBaseSetInfo socialSet,
										SysBaseSetInfo fundSet,
										TDispatchImportVo excel,
										TSocialFundInfo socialFund,
										boolean injury) {
		// 是否SSC：SSC派单组-1659015946137583618L  SSC审核组-1659016108176130049L
		long roleId = 1659015946137583618L;
		boolean isSsc = false;
		if (null != user) {
			isSsc = haveRole(user, roleId);
		}
		TDispatchInfo dispatch = new TDispatchInfo();
		// 初始化派单项
		dispatch.setOrderId(excel.getOrderId());
		initAddHandleItem(excel, socialFund, dispatch, socialSet, injury);
		if (Common.isEmpty(dispatch.getDispatchItem())) {
			return true;
		}
		if (Common.isNotNull(empVo) && Common.isNotNull(empVo.getContactAddress())) {
			dispatch.setContactAddress(empVo.getContactAddress());
		} else {
			dispatch.setContactAddress(excel.getContactAddress());
		}
		String deptName = null;
		if (Common.isNotNull(excel.getPreLoginName())) {
			R<SysUser> res = upmsDaprUtils.getSimpleUserByLoginName(excel.getPreLoginName());
			if (Common.isNotNull(res) && Common.isNotNull(res.getData())) {
				SysUser loginUser = res.getData();
				deptName = loginUser.getDeptName();
			}
		}
		dispatch.setOrganName(null == deptName ? user.getDeptName() : deptName);
		if (Common.isNotNull(excel.getPreId())) {
			dispatch.setPreId(excel.getPreId());
		}
		dispatch.setCreateBy(null == user ? "1" : user.getId());
		//如果登录名不为空查询登录人所属部门
		dispatch.setCreateName(Common.isNotNull(excel.getPreName()) ? excel.getPreName() : user.getNickname());
		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(Common.isNotNull(excel.getPreName()) ? excel.getPreName() : 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()) && !"公积金".equals(dispatch.getDispatchItem())) {
			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);
		if (isSsc) {
			dispatch.setStatus(CommonConstants.FIVE_STRING);
		}
		dispatch.setDeleteFlag(CommonConstants.ZERO_STRING);
		// 封装项目客户信息
		dispatch.setBelongUnit(excel.getCustomerId());
		dispatch.setBelongUnitName(excel.getCustomerName());
		dispatch.setEducationName(excel.getEducationName());
		dispatch.setSchoolName(excel.getSchoolName());
		dispatch.setMajor(excel.getMajor());
		dispatch.setGraduationTime(excel.getGraduationTime());
		dispatch.setFirstPayTime(excel.getFirstPayTime());
		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()));
			}
			if (Common.isEmpty(dispatch.getSchoolName())) {
				dispatch.setSchoolName(empVo.getSchool());
			}

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

	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());
			fund.setSettleDomainCode(excel.getSettleDomainCode());
			if (Common.isNotNull(empVo)) {
				fund.setEmpId(empVo.getId());
				fund.setEmpNo(empVo.getEmpNo());
				fund.setEmpIdcard(empVo.getEmpIdcard());
				fund.setEmpName(empVo.getEmpName());
			} else {
				fund.setEmpIdcard(excel.getEmpIdcard());
				fund.setEmpName(excel.getEmpName());
			}
			fund.setTrustRemark(excel.getTrustRemark());
			fund.setUnitProvidengCardinal(excel.getProvidentCardinal());
			fund.setPersonalProvidentCardinal(excel.getProvidentCardinal());
			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;
				}
				// 校验公积金比例后会同步excel的个人公积金比例，顺序不要调整了
				fund.setPersonalProvidentPer(excel.getPersonalProvidentPer());
				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) {
		//单位个人公积金是否一致：perFlag 0是 1 否 2024-12-05 v1.7.3
		if (CommonConstants.ZERO_STRING.equals(excel.getPerFlag())) {
			excel.setPersonalProvidentPer(excel.getProvidentPer());
		}
		if (Common.isNotNull(excel.getProvidentPer())
				&& Common.isNotNull(excel.getPersonalProvidentPer())
				&& Common.isNotNull(pays)) {
			for (SysPayProportion per : pays) {
				if (per.getCompanyPro().doubleValue() == excel.getProvidentPer().doubleValue()
						&& per.getPersonalPro().doubleValue() == excel.getPersonalProvidentPer().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,
							 Map<String, EmpProjectDispatchVo> projectsUpdateMap) {
		// 无档案无项目档案无合同无学历
		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())) {


			// 初始化项目档案
			Map<String, String> map = new HashMap<String, String>();
			map.put(empVo.getEmpIdcard(), empVo.getContactAddress());

			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);
		}
		// 有项目档案但岗位信息为空 && fxj 20241124 1.7.2  有项目档案 试用期为空
		if (Common.isNotNull(empVo)
				&& Common.isNotNull(empVo.getDeptNo())) {
			EmpProjectDispatchVo project = new EmpProjectDispatchVo();
			project.setDeptNo(empVo.getDeptNo());
			if (Common.isEmpty(empVo.getPost()) && Common.isNotNull(excel.getPost())) {
				project.setPost(excel.getPost());
				project.setNeedUpdate(true);
			}
			if (Common.isEmpty(empVo.getTryPeriod()) && Common.isNotNull(excel.getTryPeriod())) {
				project.setTryPeriod(excel.getTryPeriod());
				project.setNeedUpdate(true);
			}
			project.setEmpIdcard(empVo.getEmpIdcard());
			projectsUpdateMap.put(excel.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + excel.getSettleDomainCode(), project);
		}
	}

	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.setFirstPayTime(excel.getFirstPayTime());
			List<Date> lstDate = new ArrayList<>();
			if (Common.isNotNull(excel.getPensionStart())) {
				lstDate.add(excel.getPensionStart());
			}
			if (Common.isNotNull(excel.getUnemployStart())) {
				lstDate.add(excel.getUnemployStart());
			}
			if (Common.isNotNull(excel.getBigailmentStart())) {
				lstDate.add(excel.getBigailmentStart());
			}
			if (Common.isNotNull(excel.getWorkInjuryStart())) {
				lstDate.add(excel.getWorkInjuryStart());
			}
			if (Common.isNotNull(excel.getMedicalStart())) {
				lstDate.add(excel.getMedicalStart());
			}
			if (Common.isNotNull(excel.getBirthStart())) {
				lstDate.add(excel.getBirthStart());
			}
			social.setSocialStartDate(Collections.min(lstDate));
			//  封装单位信息 结算信息
			social.setBelongUnit(excel.getCustomerId());
			social.setSettleDomain(excel.getSettleDomainId());
			social.setSettleDomainCode(excel.getSettleDomainCode());
			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.getLowerPersion());
					social.setPersonalMedicalCardinal(socialSet.getLowerMedical());
					social.setPersonalUnemploymentCardinal(socialSet.getLowerUnemployment());

					social.setUnitPensionCardinal(socialSet.getLowerPersion());
					social.setUnitMedicalCardinal(socialSet.getLowerMedical());
					social.setUnitUnemploymentCardinal(socialSet.getLowerUnemployment());
					social.setUnitWorkInjuryCardinal(socialSet.getLowerInjury());
					social.setUnitBirthCardinal(socialSet.getLowerBirth());
					if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())) {
						social.setUnitBigailmentCardinal(socialSet.getLowerBig());
						social.setPersonalBigailmentCardinal(socialSet.getLowerBig());
					}
				}
				//按最高
				if (CommonConstants.TWO_STRING.equals(excel.getPaymentType())) {
					social.setPersonalPensionCardinal(socialSet.getUpPersion());
					social.setPersonalMedicalCardinal(socialSet.getUpMedical());
					social.setPersonalUnemploymentCardinal(socialSet.getUpUnemployment());

					social.setUnitPensionCardinal(socialSet.getUpPersion());
					social.setUnitMedicalCardinal(socialSet.getUpMedical());
					social.setUnitUnemploymentCardinal(socialSet.getUpUnemployment());
					social.setUnitWorkInjuryCardinal(socialSet.getUpInjury());
					social.setUnitBirthCardinal(socialSet.getUpBirth());
					if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())) {
						social.setPersonalBigailmentCardinal(socialSet.getUpBig());
						social.setUnitBigailmentCardinal(socialSet.getUpBig());
					}
				}
				if (CommonConstants.ZERO_STRING.equals(social.getIsIllness())) {
					social.setInsuranceBigailment(socialSet.getInsuranceBigailment());
					social.setPersonalBigailmentCardinal(ServiceUtil.ifNull(social.getPersonalBigailmentCardinal(), excel.getBigailmentCardinal()));
					social.setUnitBigailmentCardinal(ServiceUtil.ifNull(social.getUnitBigailmentCardinal(), excel.getBigailmentCardinal()));
					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);
		}
		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()));
	}

	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())
						|| CommonConstants.FOUR_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())
						|| CommonConstants.FOUR_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())
						|| CommonConstants.FOUR_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())
						|| CommonConstants.FOUR_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())
						|| CommonConstants.FOUR_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())
						|| CommonConstants.FOUR_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());
		contract.setTryPeriod(excel.getTryPeriod());
		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.setUnitNo(setInfoVo.getCustomerCode());
		contract.setSubjectUnit(setInfoVo.getCustomerName());
		contract.setSubjectDepart(setInfoVo.getDepartName());
		contract.setEmpNatrue(excel.getEmpType());
		if (Common.isNotNull(empVo)) {
			contract.setEmpId(empVo.getId());
			contract.setEmpNo(empVo.getEmpNo());
			if (Common.isNotNull(empVo.getEmpNatrue())) {
				contract.setEmpNatrue(empVo.getEmpNatrue());
			}
			if (Common.isNotNull(excel.getFileProvince())) {
				contract.setFileProvince(Integer.parseInt(excel.getFileProvince()));
				contract.setFileCity(null == excel.getFileCity() ? null : Integer.parseInt(excel.getFileCity()));
				contract.setFileTown(null == excel.getFileTown() ? null : Integer.parseInt(excel.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(excelUtil.getDicValueByDataType(excel.getContractName(), ExcelAttributeConstants.PERSONNEL_TYPE));
		project.setEmpIdcard(excel.getEmpIdcard());
		project.setEmpName(excel.getEmpName());
		project.setEmpNatrue(excel.getEmpType());
		project.setPost(excel.getPost());
		project.setWorkingHours(excel.getWorkingHours());
		project.setTryPeriod(excel.getTryPeriod());
		project.setEnjoinDate(null != excel.getContractStart() ? excel.getContractStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : null);
		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.setContactAddress(excel.getContactAddress());
		emp.setEmpName(excel.getEmpName());
		emp.setEmpNational(excel.getEmpNational());
		emp.setEmpNatrue(excel.getEmpType());
		emp.setEmpPhone(excel.getEmpMobile());
		emp.setEmpRegisType(excel.getEmpRegisType());
		emp.setHignEducation(excel.getEducationName());
		emp.setMajor(excel.getMajor());
		emp.setGradutionDate(excel.getGraduationTime());
		emp.setSchool(excel.getSchoolName());
		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.ELEVEN_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.SIX_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.SEVEN_STRING.equals(sf.getSocialStatus())
			) {
				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;
	}

	//autoFalg  "0"  为自动化
	private boolean validImport(List<ErrorMessage> errorMessageList,
								TDispatchImportVo excel,
								ProjectSetInfoVo setInfoVo,
								TSocialFundInfo socialFund,
								DispatchEmpVo empVo, SysBaseSetInfo socialSet, SysBaseSetInfo fundSet,String autoFlag) {
		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;
		}

		// MVP1.7.11：校验户是否在服务项里
		// 获取项目的服务项
		if (Common.isEmpty(setInfoVo.getServerItem())) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "项目未维护服务项目，请联系管理员"));
			return true;
		}
		String[] serverItemArr = setInfoVo.getServerItem().split("、");
		// 服务项校验
		if (Common.isNotNull(excel.getSocialHousehold()) && Common.isNotNull(excel.getProvidentHousehold())) {
			if (!ArrayUtils.contains(serverItemArr, "社保") && !ArrayUtils.contains(serverItemArr, "公积金")) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该项目未勾选 社保和公积金 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试"));
				return true;
			}
			if (!ArrayUtils.contains(serverItemArr, "社保")) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该项目未勾选 社保 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试"));
				return true;
			}
			if (!ArrayUtils.contains(serverItemArr, "公积金")) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该项目未勾选 公积金 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试"));
				return true;
			}
		} else if (Common.isNotNull(excel.getSocialHousehold())) {
			if (!ArrayUtils.contains(serverItemArr, "社保")) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该项目未勾选 社保 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试"));
				return true;
			}
		} else {
			if (!ArrayUtils.contains(serverItemArr, "公积金")) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "该项目未勾选 公积金 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试"));
				return true;
			}
		}

		//对应的项目编码已停止合作
		if (CommonConstants.ONE_STRING.equals(setInfoVo.getStopFlag()) || CommonConstants.TWO_STRING.equals(setInfoVo.getStopFlag())) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SETTLEDOMAIN_STOP)));
			return true;
		}
		String educationName;
		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.getContractName())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_NOT_EMPTY)));
				return true;
			}
			//无档案必填2024-08-21 fxj
			if (Common.isEmpty(excel.getEmpRegisType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_REGISTYPE_NOT_EMPTY)));
				return true;
			}
			if (Common.isEmpty(excel.getEducationName())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_EDUCATION_NOT_EMPTY)));
				return true;
			} else if (Common.isEmpty(excel.getSchoolName())) {
				educationName = excel.getEducationName();
				if ((educationName.contains("大专")
						|| educationName.contains("本科")
						|| educationName.contains("硕士")
						|| educationName.contains("博士"))) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_SCHOOL_NOT_EMPTY)));
					return true;
				}
			}

			if (Common.isNotNull(excel.getContractName()) && validContractInfo(errorMessageList, excel)) {
				return true;
			}
			//无档案试用期必填 20241128 fxj 1.7.2
			if (Common.isEmpty(excel.getTryPeriod())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_TRYPERIOD_NOT_EMPTY)));
				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.getEmpNatrue()) && Common.isNotNull(excel.getEmpType()) && !empVo.getEmpNatrue().equals(excel.getEmpType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_TYPE_ERROR)));
				return true;
			}
			//档案试用期必填 20241128 fxj 1.7.2
			if (Common.isEmpty(empVo.getTryPeriod())
					&& Common.isEmpty(excel.getTryPeriod())
					&& CommonConstants.ZERO_STRING.equals(empVo.getTryPeriod()) && !CommonConstants.ZERO_STRING.equals(autoFlag)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_TRYPERIOD_NOT_EMPTY)));
				return true;
			}
			if (CommonConstants.ZERO_STRING.equals(autoFlag) && Common.isEmpty(excel.getTryPeriod())){
				excel.setTryPeriod(empVo.getTryPeriod());
			}
			// fxj 2024-08-30 有档案 学历或户口性质为空 派单必填 学历或客户性质
			if (Common.isEmpty(empVo.getHignEducation()) && Common.isEmpty(excel.getEducationName())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_EDUCATION_NOT_EMPTY)));
				return true;
			} else if (Common.isEmpty(excel.getSchoolName()) && Common.isEmpty(empVo.getSchool())) {
				educationName = excel.getEducationName();
				if (Common.isEmpty(educationName)) {
					educationName = empVo.getHignEducation();
					// 这里不判断null，因为上面判断过了empVo与excel的学历不都为空
					if ((educationName.equals("5")
							|| educationName.equals("6")
							|| educationName.equals("7")
							|| educationName.equals("8"))) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_SCHOOL_NOT_EMPTY)));
						return true;
					}
				} else {
					if ((educationName.contains("大专")
							|| educationName.contains("本科")
							|| educationName.contains("硕士")
							|| educationName.contains("博士"))) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_SCHOOL_NOT_EMPTY)));
						return true;
					}
				}
			}
			if (Common.isEmpty(empVo.getEmpRegisType()) && Common.isEmpty(excel.getEmpRegisType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_EMP_REGISTYPE_NOT_EMPTY)));
				return true;
			}
			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.getContractStart())) {
				// 系统已存在的合同起缴日期
				if (Common.isNotNull(excel.getContractStart())) {
					String conYearMonthDay = DateUtil.formatDatePatten(empVo.getContractStart(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
					String excelConYearMonthDay = DateUtil.formatDatePatten(excel.getContractStart(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
					if (!conYearMonthDay.equals(excelConYearMonthDay)) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "系统内[合同]起缴日期年月日【"
								+ conYearMonthDay + "】与派单[合同]日期的年月日【" + excelConYearMonthDay + "】不一致！禁止派单！"));
						return true;
					}
				}
				String conYearMonth = DateUtil.formatDatePatten(empVo.getContractStart(), DateUtil.DATETIME_YYYYMM);
				if (Common.isEmpty(excel.getTrustRemark())) {
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getPensionStart(), "养老")) {
						return true;
					}
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getMedicalStart(), "医疗")) {
						return true;
					}
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getUnemployStart(), "失业")) {
						return true;
					}
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getWorkInjuryStart(), "工伤")) {
						return true;
					}
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getBirthStart(), "生育")) {
						return true;
					}
					if (judgeConStartAndSocialFund(errorMessageList, excel, conYearMonth, excel.getBigailmentStart(), "大病")) {
						return true;
					}
				}
			}
			if (Common.isNotNull(empVo.getEmpNatrue())) {
				excel.setEmpType(empVo.getEmpNatrue());
			}
			if (Common.isNotNull(empVo.getEmpPhone()) && Common.isEmpty(excel.getEmpMobile())) {
				excel.setEmpMobile(empVo.getEmpPhone());
			}
			// 如果存在档案但是手机号码不为空校验号码
			if (Common.isNotNull(excel.getEmpMobile())
					&& !excel.getEmpMobile().equals(empVo.getEmpPhone())
					&& checkMobileAndIdcard(errorMessageList, excel)) {
				return true;
			}
			// 档案地  手机号码， 派单有数据 更新档案，派单没有 有档案取值档案数据
			if (Common.isEmpty(excel.getFileProvince())) {
				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());
			if (Common.isNotNull(empVo.getEmpRegisType())) {
				//如果档案有值直接取值档案 2024-08-21 fxj
				excel.setEmpRegisType(empVo.getEmpRegisType());
			}
			//派单学历无值时，如果档案有值直接取值档案 2024-08-21 fxj
			initEducation(excel, null, empVo);
			if (Common.isEmpty(excel.getPost())) {
				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.getPerFlag())
						|| Common.isEmpty(excel.getProvidentPer())
						|| (Common.isEmpty(excel.getPersonalProvidentPer()) && CommonConstants.ONE_STRING.equals(excel.getPerFlag()))
		)) {
			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 审核不通过-增 11.派减办理中 12.派减部分办理失败）
			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())
					|| CommonConstants.ELEVEN_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 void initEducation(TDispatchImportVo excel, TDispatchReduceVo excelReduce, DispatchEmpVo empVo) {
		if (Common.isNotNull(empVo.getHignEducation())) {
			String educationName = null;
			if (empVo.getHignEducation().equals("1")) {
				educationName= "文盲";
			}
			if (empVo.getHignEducation().equals("2")) {
				educationName= "小学";
			}
			if (empVo.getHignEducation().equals("3")) {
				educationName= "初中";
			}
			if (empVo.getHignEducation().equals("4")) {
				educationName= "高中";
			}
			if (empVo.getHignEducation().equals("5")) {
				educationName= "大专";
			}
			if (empVo.getHignEducation().equals("6")) {
				educationName= "本科";
			}
			if (empVo.getHignEducation().equals("7")) {
				educationName= "硕士";
			}
			if (empVo.getHignEducation().equals("8")) {
				educationName= "博士";
			}
			if (empVo.getHignEducation().equals("9")) {
				educationName= "技工";
			}
			if (empVo.getHignEducation().equals("10")) {
				educationName= "职高";
			}
			if (empVo.getHignEducation().equals("11")) {
				educationName= "中专";
			}
			if (excel != null) {
				excel.setEducationName(educationName);
			} else if (excelReduce != null) {
				excelReduce.setEducationName(educationName);
			}
		}
	}

	/**
	 * @param errorMessageList
	 * @param excel
	 * @param conYearMonth
	 * @param startDate
	 * @Description: 判断合同日期与社保公积金日期是否一致
	 * @Author: hgw
	 * @Date: 2023/5/22 17:06
	 * @return: boolean
	 **/
	private boolean judgeConStartAndSocialFund(List<ErrorMessage> errorMessageList, TDispatchImportVo excel
			, String conYearMonth, Date startDate, String message) {
		if (Common.isNotNull(startDate)) {
			String startD = DateUtil.formatDatePatten(startDate, DateUtil.DATETIME_YYYYMM);
			if (!conYearMonth.equals(startD)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "系统内[合同]起缴日期年月【"
						+ conYearMonth + "】与派单[" + message + "]日期的年月【" + startD + "】不一致！委托备注必填！"));
				return true;
			}
		}
		return false;
	}

	private boolean checkMobileAndIdcard(List<ErrorMessage> errorMessageList, TDispatchImportVo excel) {
		// 如果没有人员档案和项目档案的时候校验身份证和手机号码
		R<Boolean> checkRes = checkDaprUtil.checkIdCardAndMobile(null, null, 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 (Common.isNotNull(checkRes.getData()) && checkRes.getData().booleanValue()) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "手机号码已被其他身份证使用！"));
			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())) {
			if (Common.isNotNull(excel.getPensionCardinal())
					&& (excel.getPensionCardinal().compareTo(socialSet.getUpPersion()) > CommonConstants.ZERO_INT
					|| excel.getPensionCardinal().compareTo(socialSet.getLowerPersion()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.YL_DISPATCH_SOCIAL_LIMIT_ERROR)));
				return true;
			}
			if (Common.isNotNull(excel.getMedicalCardinal())
					&& (excel.getMedicalCardinal().compareTo(socialSet.getUpMedical()) > CommonConstants.ZERO_INT
					|| excel.getMedicalCardinal().compareTo(socialSet.getLowerMedical()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.YB_DISPATCH_SOCIAL_LIMIT_ERROR)));
				return true;
			}
			if (Common.isNotNull(excel.getUnemploymentCardinal())
					&& (excel.getUnemploymentCardinal().compareTo(socialSet.getUpUnemployment()) > CommonConstants.ZERO_INT
					|| excel.getUnemploymentCardinal().compareTo(socialSet.getLowerUnemployment()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SY_DISPATCH_SOCIAL_LIMIT_ERROR)));
				return true;
			}
			if (Common.isNotNull(excel.getWorkInjuryCardinal())
					&& (excel.getWorkInjuryCardinal().compareTo(socialSet.getUpInjury()) > CommonConstants.ZERO_INT
					|| excel.getWorkInjuryCardinal().compareTo(socialSet.getLowerInjury()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.GS_DISPATCH_SOCIAL_LIMIT_ERROR)));
				return true;
			}
			if (Common.isNotNull(excel.getBirthCardinal())
					&& (excel.getBirthCardinal().compareTo(socialSet.getUpBirth()) > CommonConstants.ZERO_INT
					|| excel.getBirthCardinal().compareTo(socialSet.getLowerBirth()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.BIR_DISPATCH_SOCIAL_LIMIT_ERROR)));
				return true;
			}
			if (Common.isNotNull(excel.getBigailmentCardinal()) && CommonConstants.ONE_STRING.equals(socialSet.getCollectType())
					&& CommonConstants.ONE_STRING.equals(socialSet.getValueType())
					&& (excel.getBigailmentCardinal().compareTo(socialSet.getUpBig()) > CommonConstants.ZERO_INT
					|| excel.getBigailmentCardinal().compareTo(socialSet.getLowerBig()) < CommonConstants.ZERO_INT)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.DB_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())
						&& CommonConstants.ONE_STRING.equals(socialSet.getCollectType())
						&& CommonConstants.ONE_STRING.equals(socialSet.getValueType())
						&& 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;
				}
			}
			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())
					&& !DateUtil.formatDatePatten(temp, DateUtil.DATETIME_YYYYMM).equals(DateUtil.formatDatePatten(excel.getPensionStart(), DateUtil.DATETIME_YYYYMM))
			) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR2)));
				return true;
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getPaymentType())) {
				excel.setPensionCardinal(socialSet.getLowerPersion());
			}
			if (CommonConstants.TWO_STRING.equals(excel.getPaymentType())) {
				excel.setPensionCardinal(socialSet.getUpPersion());
			}
			//最低最高时候去校验时候去校验
			if (Common.isEmpty(excel.getTrustRemark()) && ((CommonConstants.ZERO_STRING.equals(excel.getPaymentType())
					&& (socialSet.getLowerPersion().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
					socialSet.getLowerMedical().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
					socialSet.getLowerUnemployment().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
					socialSet.getLowerInjury().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
					socialSet.getLowerBirth().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT || (
					CommonConstants.ONE_STRING.equals(socialSet.getCollectType())
							&& CommonConstants.ONE_STRING.equals(socialSet.getValueType()) &&
							socialSet.getLowerBig().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT))) ||
					(CommonConstants.TWO_STRING.equals(excel.getPaymentType())
							&& (socialSet.getUpPersion().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
							socialSet.getUpMedical().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
							socialSet.getUpUnemployment().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
							socialSet.getUpInjury().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
							socialSet.getUpBirth().compareTo(excel.getRecordBase()) != CommonConstants.ZERO_INT ||
							(CommonConstants.ONE_STRING.equals(socialSet.getCollectType())
									&& CommonConstants.ONE_STRING.equals(socialSet.getValueType()) &&
									socialSet.getUpBig().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, String flag) {
		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, flag);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return this.judgeAllMessage(errorMessageList);
	}

	private YifuUser getNewYifuUser(String userId, String userName) {
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new YifuUser(userId, 1L, "", userName,
				userName, "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null, null);
	}

	// 离职待办调用的批量派减社保、公积金
	@Override
	public BaseSearchListVO leaveToReduceSocialAndFund(TDispatchReduceListVo paramVo) {
		List<TDispatchReduceVo> excelVOList = paramVo.getListParam();
		BaseSearchListVO returnVo = new BaseSearchListVO();
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		int batchCount = CommonConstants.BATCH_COUNT;
		List<TDispatchReduceVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
		Map<Integer, String> rowLeaveMap = new HashMap<>();
		if (excelVOList != null && !excelVOList.isEmpty()) {
			int i=0;
			String leaveId;
			for (TDispatchReduceVo vo : excelVOList) {
				i++;
				leaveId = vo.getLeaveId();
				vo.setRowIndex(i);
				if (Common.isNotNull(leaveId)) {
					rowLeaveMap.put(i, leaveId);
				}
				cachedDataList.add(vo);
				if (cachedDataList.size() >= batchCount || i==excelVOList.size()) {
					batchReduceDispatch(cachedDataList, errorMessageList, getNewYifuUser(paramVo.getUserId(), paramVo.getUserName()), null, null);
					// 存储完成清理 list
					cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
				}
			}
		}
		if (!errorMessageList.isEmpty()) {
			for (ErrorMessage message : errorMessageList) {
				if (Common.isNotNull(message.getLineNum())) {
					message.setKey(rowLeaveMap.get(message.getLineNum()));
				}
			}
		}
		returnVo.setErrorMessageList(errorMessageList);
		return returnVo;
	}

	@Override
	public void batchReduceDispatch(List<TDispatchReduceVo> excelVOList, List<ErrorMessage> errorMessageList,
									YifuUser user, String orderId, String flag) {
		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, TSocialFundInfo> socialFundMap = getSocialFundMap(idcards);

		TSocialFundInfo socialFund;
		TDispatchReduceVo excel;
		//批量派减：校验待派减人员五险一金缴纳情况，若有公积金未派减，则会显示社保已派减，公积金未派减，并弹窗提示有派减失败数据，可同步导出派减数据表单
		//flag为1时 单独派减社保时校验公积金是否可用
		if (Common.isNotNull(flag) && CommonConstants.ONE_STRING.equals(flag)) {
			List<ErrorMessage> errorMessageList1 = new ArrayList<>();
			for (int i = 0; i < excelVOList.size(); i++) {
				socialFund = null;
				excel = excelVOList.get(i);
				if (Common.isNotNull(socialFundMap)) {
					socialFund = socialFundMap.get(excel.getEmpIdcard());
				}
				//单减社保，判断是否有正常的公积金
				if (Common.isNotNull(excel.getSocialReduceDate()) && Common.isEmpty(excel.getFundReduceDate())
						&& Common.isNotNull(socialFund)
						&& (CommonConstants.THREE_STRING.equals(socialFund.getFundStatus())
						|| CommonConstants.EIGHT_STRING.equals(socialFund.getFundStatus())
						|| CommonConstants.ZERO_STRING.equals(socialFund.getFundStatus())
						|| CommonConstants.ONE_STRING.equals(socialFund.getFundStatus()))) {
					errorMessageList1.add(new ErrorMessage(excel.getRowIndex(), excel.getEmpIdcard() + "-" + excel.getEmpName(), CommonConstants.RED, CommonConstants.ONE_STRING));
				}
			}
			if (!errorMessageList1.isEmpty() && errorMessageList1.stream().anyMatch(e -> CommonConstants.ONE_STRING.equals(e.getName()))) {
				errorMessageList.clear();
				errorMessageList.addAll(errorMessageList1);
				return;
			}
		}

		// 通过身份证和项目编码获取档案&项目档案&最新合同
		Map<String, DispatchEmpVo> empVoMap = getDispatchEmpVo(idcards, codes);
		// 获取项目编码数据 以供校验
		Map<String, ProjectSetInfoVo> projectVoMap = getProjectVoMap(codes);
		DispatchEmpVo empVo;
		TDispatchInfo dispatch;

		ProjectSetInfoVo setInfoVo;
		// 是否SSC：SSC派单组-1659015946137583618L  SSC审核组-1659016108176130049L
		long roleId = 1659015946137583618L;
		boolean isSsc = haveRole(user, roleId);
		StringBuilder remarkTemp;
		TAuditInfo auditInfo;
		// 执行数据插入操作 组装
		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(excel.getReasonType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "减少原因不能为空"));
				continue;
			}
			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 (Common.isNotNull(excel.getSocialReduceDate()) && Common.isEmpty(excel.getFundReduceDate())
					&& (CommonConstants.THREE_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.EIGHT_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.ZERO_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.ONE_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.FIVE_STRING.equals(socialFund.getFundStatus())
					|| CommonConstants.SIX_STRING.equals(socialFund.getFundStatus()))
					&& CommonConstants.ZERO_STRING.equals(excel.getChangeContractAndEmployee())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_NOT_EMPTY_CHANGE)));
				continue;
			}
			//单减公积金
			if (Common.isNotNull(excel.getFundReduceDate()) && Common.isEmpty(excel.getSocialReduceDate())
					&& CommonConstants.ZERO_STRING.equals(excel.getChangeContractAndEmployee())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_NOT_EMPTY_SIGNLE)));
				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());
			// 初始化派单 和 社保公积金查询信息
			initEducation(null, excel, empVo);
			dispatch = getDispatchInfo(empVo, excel, socialFund, setInfoVo, user);

			if (Common.isEmpty(dispatch.getDispatchItem())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_ITEM_EMPTY_EXISTS)));
				continue;
			}
			try {
				dispatch.setOrderId(orderId);
				dispatch.setApplyNo(getApplyCode());
				if (CommonConstants.ZERO_STRING.equals(excel.getIsAgainFlag())) {
					TDispatchInfo dispatchInfo = baseMapper.selectById(excel.getIsAgainId());
					dispatchInfo.setAgainDispatchCode(dispatch.getApplyNo());
					baseMapper.updateById(dispatchInfo);
				}
				dispatch.setStatus(CommonConstants.ONE_STRING);
				if (isSsc) {
					dispatch.setStatus(CommonConstants.FIVE_STRING);
				}
				auditInfo = new TAuditInfo();
				remarkTemp = new StringBuilder(CommonConstants.EMPTY_STRING);
				if (Common.isNotNull(dispatch.getSocialId())){
					remarkTemp.append("社保");
				}
				if (Common.isNotNull(dispatch.getFundId())){
					if (remarkTemp.length() > 0) {
						remarkTemp.append( "、公积金");
					} else {
						remarkTemp.append("公积金");
					}
				}
				remarkTemp.append("派减申请：");
				initAuditInfo(auditInfo, remarkTemp.toString(), CommonConstants.ZERO_STRING, user, remarkTemp.toString(), null);
				baseMapper.insert(dispatch);
				auditInfo.setEmpIdcard(dispatch.getEmpIdcard());
				auditInfo.setDispatchInfoId(dispatch.getId());
				auditInfo.setDispatchInfoId(dispatch.getId());
				auditInfoMapper.insert(auditInfo);
				//是否同步减档减项减合同未是时新增任务处理表
				if (Common.isNotNull(dispatch.getChangeContractAndEmployee())
						&& CommonConstants.ZERO_STRING.equals(dispatch.getChangeContractAndEmployee())) {
					InsertWorkHandlerVo insertVo = new InsertWorkHandlerVo();
					insertVo.setDepartName(dispatch.getSettleDomainName());
					insertVo.setEmpIdcard(dispatch.getEmpIdcard());
					insertVo.setEmpName(dispatch.getEmpName());
					insertVo.setDepartNo(dispatch.getSettleDomainCode());
					insertVo.setDetailId(dispatch.getId());
					insertVo.setOperUser(user.getNickname());
					R<Boolean> resUp = archivesDaprUtil.insertWorkHandler(insertVo);
					if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()) {
						ServiceUtil.runTimeExceptionDiy(insertVo.getEmpIdcard() + DispatchConstants.DISPATCH_SYN_DOC_EXE);
					}
				}
				socialFundMapper.updateById(socialFund);
				//派减时生成社保公积金查询快照
				TDispatchSocialFundInfo infoEntity = new TDispatchSocialFundInfo();
				BeanUtils.copyProperties(socialFund, infoEntity);
				infoEntity.setReduceSocialFundId(dispatch.getId());
				infoEntity.setId(String.valueOf(UUID.randomUUID()).replaceAll("-", ""));
				infoService.save(infoEntity);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN, dispatch.getId(), excel.getLeaveId()));
			} 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.setEducationName(excel.getEducationName());
		dispatch.setChangeContractAndEmployee(excel.getChangeContractAndEmployee());
		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(DateUtil.stringToDate(excel.getSocialReduceDate(), DateUtil.ISO_DATE_FORMAT));
			socialFund.setSocialReduceStatus(CommonConstants.ZERO_STRING);
			socialFund.setSocialReduceStatus(CommonConstants.ZERO_STRING);
			socialFund.setSocialStatus(CommonConstants.SIX_STRING);
			// 养老办理状态：0待办理1办理成功2办理失败3已派减 4 派减失败
			if (CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())
					|| CommonConstants.FOUR_STRING.equals(socialFund.getPensionHandle())) {
				temp.append(DispatchConstants.DISPATCH_PENSION);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())
					|| CommonConstants.FOUR_STRING.equals(socialFund.getMedicalHandle())) {
				temp.append(DispatchConstants.DISPATCH_MEDICAL);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())
					|| CommonConstants.FOUR_STRING.equals(socialFund.getWorkInjuryHandle())) {
				temp.append(DispatchConstants.DISPATCH_INJURY);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())
					|| CommonConstants.FOUR_STRING.equals(socialFund.getBirthHandle())) {
				temp.append(DispatchConstants.DISPATCH_BIRTH);
			}
			if (CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())
					|| CommonConstants.FOUR_STRING.equals(socialFund.getUnemployHandle())) {
				temp.append(DispatchConstants.DISPATCH_UNEMP);
			}
			if ((CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
					|| CommonConstants.FOUR_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())
					|| CommonConstants.EIGHT_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(DateUtil.stringToDate(excel.getFundReduceDate(), DateUtil.ISO_DATE_FORMAT));
			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(setInfoVo.getCustomerName());
		dispatch.setBelongUnit(setInfoVo.getCustomerId());
		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());
		}
		// 社保公积金派减派单兼容 划转逻辑
		if (Common.isNotNull(dispatch.getSocialId())) {
			dispatch.setSettleDomain(socialFund.getSettleDomain());
			dispatch.setSettleDomainCode(socialFund.getSettleDomainCode());
			dispatch.setSettleDomainName(socialFund.getSettleDomainName());
		} else if (Common.isNotNull(dispatch.getFundId()) && Common.isEmpty(dispatch.getSocialId())) {
			dispatch.setSettleDomain(socialFund.getSettleDomainFund());
			dispatch.setSettleDomainCode(socialFund.getSettleDomainCodeFund());
			dispatch.setSettleDomainName(socialFund.getSettleDomainNameFund());
		}
		return dispatch;
	}

	private boolean validReduce(List<ErrorMessage> errorMessageList,
								Map<String, String> excelVOTemp,
								Map<String, TSocialFundInfo> socialFundMap,
								TSocialFundInfo socialFund,
								TDispatchReduceVo excel) {
		// MVPV1.7.14 ,批量派减日志调整为年月格式
		if (Common.isNotNull(excel.getSocialReduceDate())){
			if (excel.getSocialReduceDate().length() != 6){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), DispatchConstants.EMPLOYEE + excel.getEmpName() + "社保停缴日期格式错误（例：202508）"));
				return true;
			}
			if (excel.getSocialReduceDate().length() == 6){
				excel.setSocialReduceDate(excel.getSocialReduceDate()+"01");
			}
			if (!Common.isValidDateAsso(excel.getSocialReduceDate())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), DispatchConstants.EMPLOYEE + excel.getEmpName() + "社保停缴日期格式错误（例：202508）"));
				return true;
			}
		}
		if (Common.isNotNull(excel.getFundReduceDate())){
			if (excel.getFundReduceDate().length() != 6){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), DispatchConstants.EMPLOYEE + excel.getEmpName() + "公积金停缴日期格式错误（例：202508）"));
				return true;
			}
			if (excel.getFundReduceDate().length() == 6){
				excel.setFundReduceDate(excel.getFundReduceDate()+"01");
			}
			if (!Common.isValidDateAsso(excel.getFundReduceDate())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), DispatchConstants.EMPLOYEE + excel.getEmpName() + "公积金停缴日期格式错误（例：202508）"));
				return true;
			}
		}

		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 办理失败12 派减部分办理失败）
		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)
					|| socialFund.getSocialStatus().equals(CommonConstants.TWELVE_STRING))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_REDUCE_SOCIAL_STATUS_ERROR)));
				return true;
			}
			//派减部分办理失败需要额外判断是否有办理成功的项可供派减;明细项办理状态：0待办理1办理成功2办理失败3已派减4派减失败5派减待办理
			if (!CommonConstants.ONE_STRING.equals(socialFund.getPensionHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getPensionHandle())
					&& !CommonConstants.ONE_STRING.equals(socialFund.getMedicalHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getMedicalHandle())
					&& !CommonConstants.ONE_STRING.equals(socialFund.getWorkInjuryHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getWorkInjuryHandle())
					&& !CommonConstants.ONE_STRING.equals(socialFund.getBirthHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getBirthHandle())
					&& !CommonConstants.ONE_STRING.equals(socialFund.getBigailmentHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getBigailmentHandle())
					&& !CommonConstants.ONE_STRING.equals(socialFund.getUnemployHandle())
					&& !CommonConstants.FOUR_STRING.equals(socialFund.getUnemployHandle())) {
				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查询派单相关系信息
	 *
	 * @param id id
	 * @return R
	 * @author fxj
	 * @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)) {
			TDispatchSocialFundInfo info = infoService.getOne(Wrappers.<TDispatchSocialFundInfo>query().lambda()
					.eq(TDispatchSocialFundInfo::getReduceSocialFundId, id)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(info) && CommonConstants.ONE_STRING.equals(dispatch.getType())) {
				detailVo.setDispatchSocial(info);
			}
			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;
	}

	/**
	 * 初始化派单审核信息
	 *
	 * @return
	 * @Author fxj
	 * @date 2020-10-27
	 **/
	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);
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 派单申请批量审核
	 * @Date 16:54 2022/7/25
	 * @Param isSingleAudit 1：单个审核接口并且户类型为单个，即时推送税友
	 **/
	@Override
	public List<ErrorMessage> addBatchApplyAudit(List<String> idsList, YifuUser user, int flag, String auditStatus
			, String auditRemark, String remark, String isSingleAudit,List<String> friendIdList,List<String> soldierIdList) {
		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));
		// 获取所有派单对应的户的自动化配置信息
		Map<String, AutoFlagVo> autoFlagMap = this.getAutoFlagMap(idsList);

		Map<String, String> autoDocMap = new HashMap<>();
		autoDocMap = getAutoDocFlagMap(idsList, autoDocMap);
		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;
				// 是否SSC，true是
				boolean isSSC;
				String autoFlagYgs;
				String autoFlagYsd;
				TDispatchSocialFundInfo socialFundInfo;
				// 是否自动化办理，true：推送到社保士兵
				boolean isAuto;
				AutoFlagVo autoFlagVo;
				// 同步更新档案等信息
				UpdateEmpVo updateEmpVo;
				for (TDispatchInfo dis : dispatchs) {
					autoFlagVo = autoFlagMap.get(dis.getId());
					if (autoFlagVo == null) {
						autoFlagVo = new AutoFlagVo();
					}
					autoFlagYgs = autoFlagVo.getAutoFlagYgs();
					autoFlagYsd = autoFlagVo.getAutoFlagYsd();
					if (Common.isEmpty(autoFlagYgs)) {
						autoFlagYgs = "1";
					}
					if (Common.isEmpty(autoFlagYsd)) {
						autoFlagYsd = "1";
					}
					isSSC = CommonConstants.FIVE_STRING.equals(dis.getStatus());
					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 (!CommonConstants.ONE_STRING.equals(dis.getStatus()) && !isSSC) {
							errorList.add(new ErrorMessage(-1, "派单非待审核状态，禁止操作：" + dis.getEmpName()));
							continue;
						}
						// 批量审核+审核为自动化+户配置为单个推送
						// 2025-9-11 16:41:08 1.7.15版本，批量审核允许通过类型为单个的
						/*if (!CommonConstants.ONE_STRING.equals(isSingleAudit)
								&& singleFlagMap.get(dis.getId()) != null
								&& CommonConstants.THREE_STRING.equals(auditStatus)
								&& null != socialInfo) {
							// 自动忽略这种社保，要单个审核并选择上传附件才行
							errorList.add(new ErrorMessage(-1, "户配置为单个推送，已跳过此条，请单个审核：" + dis.getEmpName()));
							continue;
						}*/
						if (null != socialInfo) {
							//派单审核通过更新社保待购买表的状态
							TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
									.eq(TDispatchInfoPre::getSocialFundId, sf.getId())
									.eq(TDispatchInfoPre::getTypeSub, CommonConstants.ZERO_STRING)
									.eq(TDispatchInfoPre::getProcessStatus, CommonConstants.THREE_STRING)
									.last(CommonConstants.LAST_ONE_SQL));
							// 派增审核
							if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())) {
								//派增审核通过
								if (CommonConstants.ZERO_INT == flag) {
									if (!isSSC) {
										socialInfo.setAuditStatus(CommonConstants.ONE_STRING);
										// 待办理
										sf.setSocialAddStatus(CommonConstants.ONE_STRING);
										sf.setSocialStatus(CommonConstants.ONE_STRING);
									}
									//审核通过更新状态
									if (Common.isNotNull(dispatchInfoPre)) {
										dispatchInfoPre.setProcessStatus(CommonConstants.FIVE_STRING);
										dispatchInfoPre.setErrorBackInfo(null);
										dispatchInfoPreMapper.updateById(dispatchInfoPre);
									}
									//派增审核不通过  需要处理预估数据
								} 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);
									//如果是部分办理失败的恢复最新的socialId ,避免后面派减取值问题
									if (null != sf.getSocialIdSuccess()){
										sf.setSocialId(sf.getSocialIdSuccess());
									}
								}
								socialInfo.setAuditTime(now);
								socialInfo.setAuditUser(user.getId());
								socialInfo.setAuditUserName(user.getNickname());
							}
							// 派减审核
							if (CommonConstants.dingleDigitStrArray[1].equals(dis.getType())) {
								//派减审核通过
								if (CommonConstants.ZERO_INT == flag) {
									if (!isSSC) {
										socialInfo.setReduceCan(CommonConstants.ONE_STRING);
										// 待办理
										sf.setSocialReduceStatus(CommonConstants.ONE_STRING);
										sf.setSocialStatus(CommonConstants.SEVEN_STRING);
										// 各个明细项的可派减项为待办理
										initReduceStatus(sf, socialInfo);
									}
									// 派减审核或办理，更新离职待办
									this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.FIVE_STRING, CommonConstants.ONE_STRING, auditRemark, user);

									//派减审核不通过  需要处理预估数据
								} else if (CommonConstants.ONE_INT == flag) {
									// 作废更新：社保状态、同步预估数据  8 审核不通过直接作废
									sf.setSocialReduceStatus(CommonConstants.ONE_STRING_NEGATE);
									if (CommonConstants.TWO_STRING.equals(sf.getPensionHandle())
											|| CommonConstants.TWO_STRING.equals(sf.getMedicalHandle())
											|| CommonConstants.TWO_STRING.equals(sf.getWorkInjuryHandle())
											|| CommonConstants.TWO_STRING.equals(sf.getBirthHandle())
											|| CommonConstants.TWO_STRING.equals(sf.getUnemployHandle())
											|| CommonConstants.TWO_STRING.equals(sf.getBigailmentHandle())
									) {
										sf.setSocialStatus(CommonConstants.FOUR_STRING);
									} else {
										sf.setSocialStatus(CommonConstants.THREE_STRING);
									}
									sf.setSocialReduceDate(null);

									// 派减审核或办理，更新离职待办
									this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.TEN_STRING, CommonConstants.ZERO_STRING, auditRemark, user);
								}
							}
							//自动化处理，如果未配置还是人工处理
							if (CommonConstants.THREE_STRING.equals(auditStatus)) {
								// 初始化之前，保留原状态给 自动化办理查询使用 hgw 2025-4-27 17:37:09
								socialInfo.setAddYgsHandleStatus(socialInfo.getYgsHandleStatus());
								socialInfo.setAddYsdHandleStatus(socialInfo.getYsdHandleStatus());
								socialInfo.setAddYgsRequestId(socialInfo.getYgsRequestId());
								socialInfo.setAddYsdRequestId(socialInfo.getYsdRequestId());
								socialInfo.setAddYgsRemark(socialInfo.getYgsRemark());
								socialInfo.setAddYsdRemark(socialInfo.getYsdRemark());

								if ((CommonConstants.ZERO_STRING.equals(socialInfo.getPensionHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getPensionHandle())
										|| CommonConstants.ZERO_STRING.equals(socialInfo.getWorkInjuryHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getWorkInjuryHandle())
										|| CommonConstants.ZERO_STRING.equals(socialInfo.getUnemployHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getUnemployHandle()))
										&& CommonConstants.ZERO_STRING.equals(autoFlagYgs)) {
									socialInfo.setYgsHandleStatus(CommonConstants.ONE_STRING);
								} else {
									socialInfo.setYgsHandleStatus(CommonConstants.ZERO_STRING);
								}
								if ((CommonConstants.ZERO_STRING.equals(socialInfo.getMedicalHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getMedicalHandle())
										|| CommonConstants.ZERO_STRING.equals(socialInfo.getBirthHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getBirthHandle())
										|| CommonConstants.ZERO_STRING.equals(socialInfo.getBigailmentHandle())
										|| CommonConstants.FIVE_STRING.equals(socialInfo.getBigailmentHandle()))
										&& CommonConstants.ZERO_STRING.equals(autoFlagYsd)) {
									socialInfo.setYsdHandleStatus(CommonConstants.ONE_STRING);
								} else {
									socialInfo.setYsdHandleStatus(CommonConstants.ZERO_STRING);
								}
								socialInfo.setYgsAddId(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYgsRequestId(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYgsRemarkOld(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYgsRemark(CommonConstants.CENTER_SPLIT_LINE_STRING);

								socialInfo.setYsdAddId(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYsdRequestId(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYsdRemarkOld(CommonConstants.CENTER_SPLIT_LINE_STRING);
								socialInfo.setYsdRemark(CommonConstants.CENTER_SPLIT_LINE_STRING);
							}
							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)) {
							//派单审核通过更新社保待购买表的状态
							TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
									.eq(TDispatchInfoPre::getSocialFundId, sf.getId())
									.eq(TDispatchInfoPre::getTypeSub, CommonConstants.ONE_STRING)
									.eq(TDispatchInfoPre::getProcessStatus, CommonConstants.THREE_STRING)
									.last(CommonConstants.LAST_ONE_SQL));
							//派增
							if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())) {
								// 审核通过
								if (CommonConstants.ZERO_INT == flag) {
									if (!isSSC) {
										providentFund.setAuditStatus(CommonConstants.ONE_STRING);
										sf.setFundAddStatus(CommonConstants.ONE_STRING);
										sf.setFundStatus(CommonConstants.ONE_STRING);
									}
									//审核通过更新状态
									if (Common.isNotNull(dispatchInfoPre)) {
										dispatchInfoPre.setProcessStatus(CommonConstants.FIVE_STRING);
										dispatchInfoPre.setErrorBackInfo(null);
										dispatchInfoPreMapper.updateById(dispatchInfoPre);
									}

									// 审核不通过
								} 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);
									//审核不通过更新状态
									if (Common.isNotNull(dispatchInfoPre)) {
										dispatchInfoPre.setProcessStatus(CommonConstants.FOUR_STRING);
										dispatchInfoPre.setErrorBackInfo(auditRemark);
										dispatchInfoPreMapper.updateById(dispatchInfoPre);

										TSocialAutoLog socialAutoLog = new TSocialAutoLog();
										socialAutoLog.setSocialId(UUID.randomUUID().toString());
										socialAutoLog.setEmpName(dispatchInfoPre.getEmpName());
										socialAutoLog.setEmpIdcard(dispatchInfoPre.getEmpIdcard());
										socialAutoLog.setErrorInfo(auditRemark);
										socialAutoLog.setPhone(dispatchInfoPre.getPhone());
										socialAutoLogService.save(socialAutoLog);

										sendDisFalureMessageToWx(dispatchInfoPre,socialAutoLog.getId());
									}

								}
								providentFund.setAuditTime(now);
								providentFund.setAuditUser(user.getId());
								providentFund.setAuditUserName(user.getNickname());
							}
							//派减
							if (CommonConstants.dingleDigitStrArray[1].equals(dis.getType())) {
								// 审核通过
								if (CommonConstants.ZERO_INT == flag) {
									if (!isSSC) {
										providentFund.setReduceCan(CommonConstants.ONE_STRING);
										sf.setFundReduceStatus(CommonConstants.ONE_STRING);
										sf.setFundStatus(CommonConstants.SIX_STRING);
									}
									// 派减审核或办理，更新离职待办
									this.sendLeave(dis.getId(), CommonConstants.TWO_STRING, CommonConstants.FIVE_STRING, CommonConstants.ONE_STRING, auditRemark, user);
									// 审核不通过
								} else if (CommonConstants.ONE_INT == flag) {
									// 作废更新：公积金状态、同步档案的公积金状态
									sf.setFundReduceStatus(CommonConstants.ONE_STRING_NEGATE);
									sf.setFundStatus(CommonConstants.THREE_STRING);
									sf.setFundReduceDate(null);
									// 派减审核或办理，更新离职待办
									this.sendLeave(dis.getId(), CommonConstants.TWO_STRING, CommonConstants.TEN_STRING, CommonConstants.ZERO_STRING, auditRemark, user);
								}
							}
							fundMapper.updateByIdOfAudit(providentFund);

						}
					}
					// 审核不通过 直接作废   要考虑 部分派增的情况
					if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
						remarkTemp += DispatchConstants.DISPATCH_ADD;
					} else {
						remarkTemp += DispatchConstants.DISPATCH_REDUCE;
					}
					if (isSSC) {
						remarkTemp += "SSC";
					}
					// 派单状态信息拼接
					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) {
						//审核通过
						if (!isSSC) {
							dis.setStatus(CommonConstants.TWO_STRING);
						} else {
							dis.setStatus(CommonConstants.ONE_STRING);
						}
					} else if (CommonConstants.ONE_INT == flag) {
						//审核不通过
						dis.setStatus(CommonConstants.THREE_STRING);
					}

					boolean flagTemp = false;
					// 派增审核不通过 失败项重新派单审核不通过 或 派减审核不通过 恢复为部分办理失败
					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.FOUR_STRING.equals(sf.getPensionHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
							|| ((CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle()))
							&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness()))
					))
							&& !(
							(CommonConstants.ONE_STRING.equals(sf.getPensionHandle()) || CommonConstants.FOUR_STRING.equals(sf.getPensionHandle()))
									&& (CommonConstants.ONE_STRING.equals(sf.getMedicalHandle()) || CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle()))
									&& (CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle()) || CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle()))
									&& (CommonConstants.ONE_STRING.equals(sf.getBirthHandle()) || CommonConstants.FOUR_STRING.equals(sf.getBirthHandle()))
									&& (CommonConstants.ONE_STRING.equals(sf.getUnemployHandle()) || CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle()))
									&& ((CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle()) || CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle()))
									&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness())));
					// 派增审核通过 要更新 人员档案 项目档案 合同的状态信息
					if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())) {
						R<Boolean> res = null;
						updateEmpVo = new UpdateEmpVo();
						updateEmpVo.setEmpIdCard(dis.getEmpIdcard());
						updateEmpVo.setProjectNo(dis.getSettleDomainCode());
						updateEmpVo.setContractId(dis.getContractId());
						updateEmpVo.setRemarkTemp(remarkTemp);
						updateEmpVo.setCreateBy(user.getId());
						updateEmpVo.setCreateName(user.getNickname());
						if (CommonConstants.ZERO_INT == flag && !isSSC) {

							// 审核通过同步到档案
							updateEmpVo.setIsCollege(getIsCollege(dis.getEducationName()));
							updateEmpVo.setHignEducation(getHignEducationValue(dis.getEducationName()));
							updateEmpVo.setSchool(dis.getSchoolName());
							updateEmpVo.setMajor(dis.getMajor());
							updateEmpVo.setGradutionDate(dis.getGraduationTime());


							updateEmpVo.setContactAddress(dis.getContactAddress());
							updateEmpVo.setType(CommonConstants.ZERO_STRING);
							res = archivesDaprUtil.updateEmpInfo(updateEmpVo);
						}
						if (CommonConstants.ONE_INT == flag) {
							updateEmpVo.setType(CommonConstants.ONE_STRING);
							res = archivesDaprUtil.updateEmpInfo(updateEmpVo);
						}
						if ((Common.isEmpty(res) || CommonConstants.SUCCESS != res.getCode()) && !isSSC) {
							ServiceUtil.runTimeExceptionDiy("更新人员档案、项目档案、合同状态异常：" + (Common.isNotNull(res) ? res.getMsg() : CommonConstants.EMPTY_STRING));
						}
					}
					// 非（批量审核+审核为自动化+户配置为单个推送），才可以改社保
					if (CommonConstants.ONE_INT == flag && flagTemp) {
						if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())) {
							sf.setSocialStatus(CommonConstants.FOUR_STRING);
							sf.setSocialAddStatus(CommonConstants.THREE_STRING);
						} else if (CommonConstants.dingleDigitStrArray[1].equals(dis.getType())
								&& (CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())
								|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
								|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
								|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
								|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())
								|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle()))) {
							sf.setSocialStatus(CommonConstants.TWELVE_STRING);
							sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
						}
					}
					//派增审核不通过更新派单信息
					if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())
							&& CommonConstants.ONE_INT == flag
							&& Common.isNotNull(dis.getSocialId())) {
						//派单审核通过更新社保待购买表的状态
						TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
								.eq(TDispatchInfoPre::getSocialFundId, sf.getId())
								.eq(TDispatchInfoPre::getTypeSub, CommonConstants.ZERO_STRING)
								.eq(TDispatchInfoPre::getProcessStatus, CommonConstants.THREE_STRING)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Common.isNotNull(dispatchInfoPre)) {
							if (sf.getSocialStatus().equals(CommonConstants.FOUR_STRING)) {
								dispatchInfoPre.setProcessStatus(CommonConstants.NINE_STRING);
							} else {
								dispatchInfoPre.setProcessStatus(CommonConstants.FOUR_STRING);
							}
							dispatchInfoPre.setErrorBackInfo(auditRemark);
							dispatchInfoPreMapper.updateById(dispatchInfoPre);

							TSocialAutoLog socialAutoLog = new TSocialAutoLog();
							socialAutoLog.setSocialId(UUID.randomUUID().toString());
							socialAutoLog.setEmpName(dispatchInfoPre.getEmpName());
							socialAutoLog.setEmpIdcard(dispatchInfoPre.getEmpIdcard());
							socialAutoLog.setErrorInfo(auditRemark);
							socialAutoLog.setPhone(dispatchInfoPre.getPhone());
							socialAutoLogService.save(socialAutoLog);
							sendDisFalureMessageToWx(dispatchInfoPre, socialAutoLog.getId());
						}
					}
					//新增审核记录信息
					auditInfo.setEmpIdcard(dis.getEmpIdcard());
					auditInfo.setDispatchInfoId(dis.getId());
					auditInfoMapper.insert(auditInfo);
					dis.setAuditUser(user.getId());
					dis.setAuditUserName(user.getNickname());
					dis.setAuditTime(now);
					//人工处理
					if (CommonConstants.ONE_STRING.equals(auditStatus)) {
						dis.setAutoFlag(CommonConstants.ONE_STRING);
						dis.setAutoFlagYsd(CommonConstants.ONE_STRING);
					}
					// 初始化为非自动办理
					isAuto = false;
					//自动化处理，如果未配置还是人工处理
					if (CommonConstants.THREE_STRING.equals(auditStatus)) {
						// 自动化处理
						if (CommonConstants.ZERO_STRING.equals(autoFlagYgs)) {
							dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
							dis.setAutoFlag(CommonConstants.ZERO_STRING);
							isAuto = true;
						} else {
							dis.setAutoFlag(CommonConstants.ONE_STRING);
						}
						if (CommonConstants.ZERO_STRING.equals(autoFlagYsd)) {
							dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
							dis.setAutoFlagYsd(CommonConstants.ZERO_STRING);
							isAuto = true;
						} else {
							dis.setAutoFlagYsd(CommonConstants.ONE_STRING);
						}
					}

					if (Common.isNotNull(autoFlagVo.getIsSingleYgs())) {
						dis.setIsSingle(autoFlagVo.getIsSingleYgs());
					}
					if (Common.isNotNull(autoFlagVo.getIsSingleYsd())) {
						dis.setIsSingleYsd(autoFlagVo.getIsSingleYsd());
					}
					if (Common.isNotNull(autoFlagVo.getRosterAutoFlagYgs())) {
						dis.setRosterAutoFlagYgs(autoFlagVo.getRosterAutoFlagYgs());
					}
					if (Common.isNotNull(autoFlagVo.getRosterAutoFlagYsd())) {
						dis.setRosterAutoFlagYsd(autoFlagVo.getRosterAutoFlagYsd());
					}
					if (Common.isNotNull(autoFlagVo.getDataFlagYgs())) {
						dis.setDataFlagYgs(autoFlagVo.getDataFlagYgs());
					}
					if (Common.isNotNull(autoFlagVo.getDataFlagYsd())) {
						dis.setDataFlagYsd(autoFlagVo.getDataFlagYsd());
					}

					dis.setIsAutoLeaveDoc(autoDocMap.get(dis.getId()));
					baseMapper.updateById(dis);
					socialFundMapper.updateById(sf);
					// 非（批量审核+审核为自动化+户配置为单个推送），才可以改社保
					if (isAuto) {
						TSocialFreindSet set = tSocialFreindSetService.getById("1");
						// 是否推送税友，默认不是，推送到士兵
						boolean isFriend = false;
						// 当前默认 安徽省 才可以税友推送办理
						String provinceId = "12";
						if (Common.isNotNull(dis.getSocialProvince()) && provinceId.equals(dis.getSocialProvince())
								&& set != null && Common.isNotNull(set.getType()) && set.getType() == 1) {
							isFriend = true;
							// 单个与批量审核，都推送，但是会过滤户里配置单个的
							friendIdList.add(dis.getId());
						} else {
							soldierIdList.add(dis.getId());
						}
					}

					//派减的申请审核完更新社保公积金查询快照表
					if (CommonConstants.ONE_STRING.equals(dis.getType())) {
						socialFundInfo = infoService.getOne(Wrappers.<TDispatchSocialFundInfo>query().lambda()
								.eq(TDispatchSocialFundInfo::getReduceSocialFundId, dis.getId())
								.last(CommonConstants.LAST_ONE_SQL));
						if (Common.isNotNull(socialFundInfo)) {
							socialFundInfo.setSocialStatus(sf.getSocialStatus());
							socialFundInfo.setSocialReduceStatus(sf.getSocialReduceStatus());
							socialFundInfo.setSocialReduceDate(sf.getSocialReduceDate());
							socialFundInfo.setSocialAddStatus(sf.getSocialAddStatus());
							socialFundInfo.setPensionHandle(sf.getPensionHandle());
							socialFundInfo.setMedicalHandle(sf.getMedicalHandle());
							socialFundInfo.setWorkInjuryHandle(sf.getWorkInjuryHandle());
							socialFundInfo.setUnemployHandle(sf.getUnemployHandle());
							socialFundInfo.setBirthHandle(sf.getBirthHandle());
							socialFundInfo.setBigailmentHandle(sf.getBigailmentHandle());
							infoService.updateById(socialFundInfo);
						}
					}

					// 派增审核不通过
					if (CommonConstants.dingleDigitStrArray[0].equals(dis.getType())
							&& CommonConstants.ONE_INT == flag) {
						// 更新预估数据 -- 失败项重新派单审核不通过不处理预估
						if (!flagTemp) {
							socialTask.asynchronousDisPatchHandle(null, null, sf, forecastFlag, null, null, CommonConstants.ZERO_INT);
						}
						// 更新人员档案和项目档案的社保公积金状态
						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.setFlag(CommonConstants.ONE_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(vo.getEmpIdCard() + 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;
	}

	private String getHignEducationValue(String educationName) {
		String educationNameValue;
		if (educationName.equals("文盲")) {
			educationNameValue = "1";
		}else if (educationName.equals("小学")) {
			educationNameValue = "2";
		}else if (educationName.equals("初中")) {
			educationNameValue = "3";
		}else if (educationName.equals("高中")) {
			educationNameValue = "4";
		}else if (educationName.equals("大专")) {
			educationNameValue = "5";
		}else if (educationName.equals("本科")) {
			educationNameValue = "6";
		}else if (educationName.equals("硕士")) {
			educationNameValue = "7";
		}else if (educationName.equals("博士")) {
			educationNameValue = "8";
		}else if (educationName.equals("技工")) {
			educationNameValue = "9";
		}else if (educationName.equals("职高")) {
			educationNameValue = "10";
		}else if (educationName.equals("中专")) {
			educationNameValue = "11";
		}else {
			educationNameValue = null;
		}
		return educationNameValue;
	}

	// 获取是否大专及以上
	private Integer getIsCollege(String educationName) {
		Integer isCollegeValue = CommonConstants.ZERO_INT;
		if (educationName.equals("大专") || educationName.equals("本科") || educationName.equals("硕士") || educationName.equals("博士")) {
			isCollegeValue = CommonConstants.ONE_INT;
		}
		return isCollegeValue;
	}

	// type 1社保，2医保
	private Map<String, AutoFlagVo> getAutoFlagMap(List<String> idsList) {
		Map<String, AutoFlagVo> autoFlagMap = new HashMap<>();
		List<AutoFlagVo> autoFlagList = baseMapper.getAutoFlag(idsList);
		if (Common.isNotNull(autoFlagList)) {
			for (AutoFlagVo flagVo : autoFlagList) {
				autoFlagMap.put(flagVo.getDispatchId(), flagVo);
			}
		}
		return autoFlagMap;
	}


	// 返回需要自动生成离职证明的map
	private Map<String, String> getAutoDocFlagMap(List<String> idsList, Map<String, String> autoDocMap) {
		List<String> singleFlagList = baseMapper.getAutoDocFlagMap(idsList);
		autoDocMap = getHuMap(autoDocMap, singleFlagList);
		return autoDocMap;
	}

	// 根据list返回map
	private Map<String, String> getHuMap(Map<String, String> singleFlagMap, List<String> singleFlagList) {
		if (Common.isNotNull(singleFlagList)) {
			if (Common.isNotNull(singleFlagMap)) {
				singleFlagMap = new HashMap<>();
			}
			for (String dispatchId : singleFlagList) {
				singleFlagMap.put(dispatchId, CommonConstants.ONE_STRING);
			}
		}
		return singleFlagMap;
	}

	private void initReduceStatus(TSocialFundInfo sf, TSocialInfo socialInfo) {
		// 各个明细项的可派减项为待办理
		if (CommonConstants.ONE_STRING.equals(sf.getPensionHandle()) || CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())) {
			sf.setPensionHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(sf.getMedicalHandle()) || CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())) {
			sf.setMedicalHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle()) || CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())) {
			sf.setWorkInjuryHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(sf.getUnemployHandle()) || CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())) {
			sf.setUnemployHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(sf.getBirthHandle()) || CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())) {
			sf.setBirthHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle()) || CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())) {
			sf.setBigailmentHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getPensionHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getPensionHandle())) {
			socialInfo.setPensionHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getMedicalHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getMedicalHandle())) {
			socialInfo.setMedicalHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getWorkInjuryHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getWorkInjuryHandle())) {
			socialInfo.setWorkInjuryHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getUnemployHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getUnemployHandle())) {
			socialInfo.setUnemployHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getBirthHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getBirthHandle())) {
			socialInfo.setBirthHandle(CommonConstants.FIVE_STRING);
		}
		if (CommonConstants.ONE_STRING.equals(socialInfo.getBigailmentHandle()) || CommonConstants.FOUR_STRING.equals(socialInfo.getBigailmentHandle())) {
			socialInfo.setBigailmentHandle(CommonConstants.FIVE_STRING);
		}
	}

	// String isSingleAudit 1：单个审核接口并且户类型为单个，即时推送税友
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> addApplyAudit(List<String> ids, String auditStatus, String auditRemark, String remark
			, String isSingleAudit,List<String> friendIdList,List<String> soldierIdList) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		try {
			if (Common.isEmpty(ids)) {
				return R.failed(DispatchConstants.DISPATCH_ID_NOT_EMPTY);
			}
			int flag;
			if (CommonConstants.ONE_STRING.equals(auditStatus) || CommonConstants.THREE_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(ids, user, flag, auditStatus
					, Common.isNullToString(auditRemark), remark, isSingleAudit,friendIdList,soldierIdList);
			return R.ok(errorInfo, "派单审核结果：");
		} catch (Exception e) {
			log.error("派单审核异常：" + e.getMessage());
			return R.failed("数据异常，派单审核失败!");
		}
	}

	// isAutoFlag:是否社保士兵的自动办理，true :是
	//@Transactional(rollbackFor = Exception.class)  在具体for循环中添加过事务注解，这个地方不需要事务注解
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> addApplyHandle(List<String> ids, String typeSub, String handleStatus
			, String handleRemark, String socialType, String remark, YifuUser userAuto, boolean isAutoHandle) {
		YifuUser user = SecurityUtils.getUser();
		if (userAuto != null) {
			user = userAuto;
		}
		if (null == user) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		if (Common.isEmpty(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办理不通过");
		}
		String key = CacheConstants.PAYMENT_DISPATCH_BATCH_IMPORT + CommonConstants.DOWN_LINE_STRING + user.getId();
		// 获取redis分布式事务锁
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key, "10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA + CommonConstants.DOWN_LINE_STRING + e.getMessage());
		}
		if (Common.isNotNull(requestId)) {
			try {
				List<ErrorMessage> errorInfo = addBatchApplyHandle(null, null, ids, typeSub, user, flag, handleStatus,
						Common.isNullToString(handleRemark), socialType, remark, isAutoHandle);
				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("数据异常，办理失败!");
			} finally {
				//主动释放锁
				RedisDistributedLock.unlock(key, requestId);
			}
		} else {
			return R.failed(ResultConstants.NO_GETLOCK_DATA);
		}
	}

	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
	 **/
	//@Transactional(rollbackFor = Exception.class)
	public List<ErrorMessage> addBatchApplyHandle(ConcurrentHashMap<String, String> socialMap, ConcurrentHashMap<String, String> fundMap,
												  List<String> idsList, String typeSub, YifuUser user
			, int flag, String handleStatus, String handleRemark, String socialType, String remark, boolean isAutoHandle) {
		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 {

				for (TDispatchInfo dis : disList) {
					if (extracted(socialMap, fundMap, typeSub, user, flag, handleStatus, handleRemark, socialType, remark, isAutoHandle, errorList, socialFundMap, dis))
						continue;
				}
			} 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;
	}

	//代码优化-解决死锁问题：fxj 2024-12-18 事务控制集中到每次循环，而不是所有for循环    TODO参数过多需要二次优化
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean extracted(ConcurrentHashMap<String, String> socialMap, ConcurrentHashMap<String, String> fundMap, String typeSub, YifuUser user, int flag, String handleStatus, String handleRemark, String socialType, String remark, boolean isAutoHandle, List<ErrorMessage> errorList, Map<String, TSocialFundInfo> socialFundMap, TDispatchInfo dis) {
		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;
		boolean partSuccess = false;
		TDispatchSocialFundInfo socialFundInfo;
		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()));
			return true;
		}
		partSuccess = 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.FOUR_STRING.equals(sf.getPensionHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
				|| ((CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle()))
				&& CommonConstants.ZERO_STRING.equals(sf.getIsIllness()))
		))
				&& !((CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getPensionHandle()))
				&& (CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle()))
				&& (CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle()))
				&& (CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle()))
				&& (CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle()))
				&& (CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
				|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())
				|| Common.isEmpty(sf.getBigailmentHandle()))
		);
		if (!CommonConstants.TWO_STRING.equals(dis.getStatus())) {
			errorList.add(new ErrorMessage(-1, "已办理完结，请勿重复操作：" + dis.getEmpName()));
			return true;
		}
		if (Common.isNotNull(dis.getSocialId())) {
			// 无更新直接跳过
			if (Common.isEmpty(socialTypeRemark)
					&& CommonConstants.ZERO_STRING.equals(typeSub)
					&& Common.isEmpty(socialType)) {
				return true;
			}
			socialInfo = socialMapper.selectById(dis.getSocialId());
			socialTypeRemark = getHandleRemark(socialType, socialInfo, dis.getType(), sf);
			// 无更新直接跳过
			if (Common.isEmpty(socialTypeRemark.toString()) && CommonConstants.ZERO_STRING.equals(typeSub)) {
				return true;
			}
		} 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());
					socialInfo.setHandleUserName(user.getNickname());
					//如果派单有办理成功项 就把最新的办理成功的社保明细ID存储到社保公积金查询中 20250820 修复部分办理成功后派减的问题
					if (CommonConstants.ONE_STRING.equals(handleStatus)){
						sf.setSocialIdSuccess(socialInfo.getId());
					}
					// 社保办理状态补充判断：
					this.setSocialHandleStatus(handleStatus, socialType, flag, socialInfo, dis, sf, isAutoHandle);

					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().concat(ServiceUtil.ifNullToEmpty(handleRemark)), 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().concat(ServiceUtil.ifNullToEmpty(handleRemark)), remark);
						}
						auditInfo.setSocialId(dis.getId());
					}
					//针对社保自动化过来的数据，办理更新待购买数据状态
					TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
							.eq(TDispatchInfoPre::getSocialFundId, sf.getId())
							.eq(TDispatchInfoPre::getTypeSub,CommonConstants.ZERO_STRING)
							.in(TDispatchInfoPre::getProcessStatus, Arrays.asList("5","6","9"))
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(dispatchInfoPre)) {
						//此处状态可能会更新为 办理成功 办理中 部分办理失败和办理失败
						if (sf.getSocialStatus().equals(CommonConstants.TWO_STRING)) {
							dispatchInfoPre.setProcessStatus(CommonConstants.SIX_STRING);
							dispatchInfoPre.setErrorBackInfo(null);
						}

						if (sf.getSocialStatus().equals(CommonConstants.FOUR_STRING)) {
							dispatchInfoPre.setProcessStatus(CommonConstants.NINE_STRING);
							dispatchInfoPre.setErrorBackInfo(handleRemark);
							StringBuffer errorTemp = new StringBuffer();
							//针对部分办理失败更新社保待购买的派单项
							if (CommonConstants.TWO_STRING.equals(sf.getPensionHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_PENSION);
							}
							if (CommonConstants.TWO_STRING.equals(sf.getMedicalHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_MEDICAL);
							}
							if (CommonConstants.TWO_STRING.equals(sf.getBirthHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_BIRTH);
							}
							if (CommonConstants.TWO_STRING.equals(sf.getWorkInjuryHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_INJURY);
							}
							if (CommonConstants.TWO_STRING.equals(sf.getUnemployHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_UNEMP);
							}
							if (CommonConstants.TWO_STRING.equals(sf.getBigailmentHandle())) {
								errorTemp.append(DispatchConstants.DISPATCH_BIGMAILMENT);
							}
							if (Common.isNotNull(errorTemp.toString())) {
								dispatchInfoPre.setDispatchItem(errorTemp.deleteCharAt(errorTemp.length() - 1).toString());
							}
							TSocialAutoLog socialAutoLog = new TSocialAutoLog();
							socialAutoLog.setSocialId(UUID.randomUUID().toString());
							socialAutoLog.setEmpName(dispatchInfoPre.getEmpName());
							socialAutoLog.setEmpIdcard(dispatchInfoPre.getEmpIdcard());
							socialAutoLog.setErrorInfo(handleRemark);
							socialAutoLog.setPhone(dispatchInfoPre.getPhone());
							socialAutoLogService.save(socialAutoLog);
							sendDisFalureMessageToWx(dispatchInfoPre,socialAutoLog.getId());
						}
						if (sf.getSocialStatus().equals(CommonConstants.FIVE_STRING)) {
							dispatchInfoPre.setProcessStatus(CommonConstants.EIGHT_STRING);
							dispatchInfoPre.setErrorBackInfo(handleRemark);

							TSocialAutoLog socialAutoLog = new TSocialAutoLog();
							socialAutoLog.setSocialId(UUID.randomUUID().toString());
							socialAutoLog.setEmpName(dispatchInfoPre.getEmpName());
							socialAutoLog.setEmpIdcard(dispatchInfoPre.getEmpIdcard());
							socialAutoLog.setErrorInfo(handleRemark);
							socialAutoLog.setPhone(dispatchInfoPre.getPhone());
							socialAutoLogService.save(socialAutoLog);
							sendDisFalureMessageToWx(dispatchInfoPre,socialAutoLog.getId());
						}
						if (sf.getSocialStatus().equals(CommonConstants.THREE_STRING)) {
							dispatchInfoPre.setErrorBackInfo(null);
							dispatchInfoPre.setProcessStatus(CommonConstants.SEVEN_STRING);
						}
						dispatchInfoPreMapper.updateById(dispatchInfoPre);
					}
				} else {
					errorList.add(new ErrorMessage(-1, "找不到对应员工社保派增派单数据：" + dis.getEmpName()));
					return true;
				}
				//公积金办理
			} 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());
					providentFund.setHandleUserName(user.getNickname());
					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) {
									//办理成功生成收入
									if (Common.isNotNull(library.getDataPush())) {
										socialTask.asynchronousDisPatchHandleForDispatch(library, CommonConstants.ZERO_INT == library.getDataPush().intValue());
									}
								}
							}
						}

					}
					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 + handleRemark), remark);
					} else {
						initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_ADD_FAIL + handleRemark), CommonConstants.FOUR_STRING, user, (DispatchConstants.DISPATCH_FUND_ADD_FAIL + handleRemark), remark);
					}
					auditInfo.setProvidentId(dis.getId());
					//针对社保自动化过来的数据，办理更新待购买数据状态
					TDispatchInfoPre dispatchInfoPre = dispatchInfoPreMapper.selectOne(Wrappers.<TDispatchInfoPre>query().lambda()
							.eq(TDispatchInfoPre::getSocialFundId, sf.getId())
							.eq(TDispatchInfoPre::getTypeSub,CommonConstants.ONE_STRING)
							.in(TDispatchInfoPre::getProcessStatus, Arrays.asList("5","6","9"))
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(dispatchInfoPre)) {
						if (sf.getFundStatus().equals(CommonConstants.FOUR_STRING)) {
							dispatchInfoPre.setProcessStatus(CommonConstants.EIGHT_STRING);
							dispatchInfoPre.setErrorBackInfo(handleRemark);

							TSocialAutoLog socialAutoLog = new TSocialAutoLog();
							socialAutoLog.setSocialId(UUID.randomUUID().toString());
							socialAutoLog.setEmpName(dispatchInfoPre.getEmpName());
							socialAutoLog.setEmpIdcard(dispatchInfoPre.getEmpIdcard());
							socialAutoLog.setErrorInfo(handleRemark);
							socialAutoLog.setPhone(dispatchInfoPre.getPhone());
							socialAutoLogService.save(socialAutoLog);
							sendDisFalureMessageToWx(dispatchInfoPre,socialAutoLog.getId());
						}
						if (sf.getFundStatus().equals(CommonConstants.THREE_STRING)) {
							dispatchInfoPre.setErrorBackInfo(null);
							dispatchInfoPre.setProcessStatus(CommonConstants.SEVEN_STRING);
						}
						dispatchInfoPreMapper.updateById(dispatchInfoPre);
					}
				} else {
					errorList.add(new ErrorMessage(-1, "找不到对应员工公积金派增派单数据：" + dis.getEmpName()));
					return true;
				}
			}
			//派减处理
		} 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, isAutoHandle);

					socialInfo.setReduceHandleUser(user.getId());
					socialInfo.setReduceHandleTime(now);
					//社保派减办理成功才变更社保的办理状态
					socialInfo.setHandleTime(now);
					socialInfo.setHandleUser(user.getId());
					socialInfo.setHandleUserName(user.getNickname());
					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);
					}
					auditInfo.setSocialId(dis.getId());

					// 派减审核或办理，更新离职待办
					if (Common.isNotNull(socialInfo.getHandleStatus())) {
						if (CommonConstants.SEVEN_STRING.equals(socialInfo.getHandleStatus())) {
							// 部分失败是0
							this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.SIX_STRING, CommonConstants.ZERO_STRING, handleRemark, user);
						} else if (CommonConstants.SIX_STRING.equals(socialInfo.getHandleStatus())) {
							// 派减办理中 - 后续改造这里和离职待办的导出（2026-02-03改造）
							this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.SEVEN_STRING, CommonConstants.ZERO_STRING, handleRemark, user);
						} else if (CommonConstants.THREE_STRING.equals(socialInfo.getHandleStatus())) {
							// 部分失败是0
							this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, handleRemark, user);
						} else if (CommonConstants.ONE_STRING.equals(socialInfo.getHandleStatus())) {
							// 部分失败是0
							this.sendLeave(dis.getId(), CommonConstants.ONE_STRING, CommonConstants.NINE_STRING, CommonConstants.ZERO_STRING, handleRemark, user);
						}
					}

				} else {
					errorList.add(new ErrorMessage(-1, "找不到对应员工社保数据：" + dis.getEmpName()));
					return true;
				}
				//公积金派减办理
			} 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.setReduceHandleUser(user.getId());
					providentFund.setReduceHandleTime(now);
					providentFund.setHandleTime(now);
					providentFund.setHandleUser(user.getId());
					providentFund.setHandleUserName(user.getNickname());
					fundMapper.updateFundInfoById(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 + handleRemark), remark);
						dis.setFundHandleStatus(CommonConstants.ONE_STRING);

						// 派减审核或办理，更新离职待办
						this.sendLeave(dis.getId(), CommonConstants.TWO_STRING, CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, handleRemark, user);
					} else {
						initAuditInfo(auditInfo, (DispatchConstants.DISPATCH_FUND_REDUCE_FAIL + handleRemark), CommonConstants.FOUR_STRING, user, (DispatchConstants.DISPATCH_FUND_REDUCE_SUCCESS + handleRemark), remark);
						dis.setFundHandleStatus(CommonConstants.TWO_STRING);

						this.sendLeave(dis.getId(), CommonConstants.TWO_STRING, CommonConstants.NINE_STRING, CommonConstants.ZERO_STRING, handleRemark, user);
					}
					auditInfo.setProvidentId(dis.getId());
				} else {
					errorList.add(new ErrorMessage(-1, "找不到对应员工公积金数据：" + dis.getEmpName()));
					return true;
				}
			}

		}
		//更新派单状态
		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.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.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())
						|| CommonConstants.THREE_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);
			//v1.8.9更新社保公积金缴纳地和户数据

			socialFundMapper.updateById(sf);
			//派减的申请审核完更新社保公积金查询快照表
			if (CommonConstants.ONE_STRING.equals(dis.getType())) {
				socialFundInfo = infoService.getOne(Wrappers.<TDispatchSocialFundInfo>query().lambda()
						.eq(TDispatchSocialFundInfo::getReduceSocialFundId, dis.getId())
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(socialFundInfo)) {
					String reduceSocialFundId = socialFundInfo.getReduceSocialFundId();
					String id = socialFundInfo.getId();
					BeanUtils.copyProperties(sf, socialFundInfo);
					socialFundInfo.setId(id);
					socialFundInfo.setReduceSocialFundId(reduceSocialFundId);
					infoService.updateById(socialFundInfo);
				}
			}

			//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()))) {
					// 派增办理，全部失败 同步预估库数据
					socialTask.asynchronousDisPatchHandle(socialMap, fundMap, sf, forecastFlag, null, null, CommonConstants.ZERO_INT);
				}
				// 社保办理只要办理成功就刷新预估数据  公积金办理不用处理（前面公积金办理成功的时候处理过了）
				if (CommonConstants.ZERO_STRING.equals(typeSub)
						&& (Common.isNotNull(dis.getSocialId())
						&& CommonConstants.FOUR_STRING.equals(sf.getSocialStatus())
						|| CommonConstants.THREE_STRING.equals(sf.getSocialStatus()))) {
					if (partSuccess) {
						forecastLibraryService.updateForecastLibaryByDispatch(socialMap, fundMap, sf);
					} else {
						socialTask.asynchronousDisPatchHandle(socialMap, fundMap, sf, 0, null, null, CommonConstants.ONE_INT);
					}
				}
			}
			//  2.派减办理成功  处理预估 (不管社保还是公积金办理失败)
			if (CommonConstants.ONE_STRING.equals(dis.getType())
					&& CommonConstants.ZERO_INT == flag
					&& (CommonConstants.EIGHT_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.SEVEN_STRING.equals(sf.getFundStatus()))) {
				// 同步预估库数据
				socialTask.asynchronousDisPatchHandle(socialMap, fundMap, sf, forecastFlag, null, null, CommonConstants.ZERO_INT);
			}
			//社保公积金派减办理成功
			if ((CommonConstants.ONE_STRING.equals(dis.getType()) && CommonConstants.ZERO_INT == flag
					&& (CommonConstants.EIGHT_STRING.equals(sf.getSocialStatus()) || CommonConstants.FIVE_STRING.equals(sf.getSocialStatus()))
					&& (CommonConstants.SEVEN_STRING.equals(sf.getFundStatus())
					|| CommonConstants.FOUR_STRING.equals(sf.getFundStatus())
					|| Common.isEmpty(sf.getFundStatus()))) ||
					(CommonConstants.ZERO_STRING.equals(dis.getType()) && CommonConstants.ONE_INT == flag &&
							CommonConstants.EIGHT_STRING.equals(sf.getSocialStatus())
							&& (CommonConstants.FOUR_STRING.equals(sf.getFundStatus())
							|| CommonConstants.NINE_STRING.equals(sf.getFundStatus())))) {
				UpProjectSocialFundVo vo = new UpProjectSocialFundVo();
				// 社保状态 社保状态（字典）: 0 无社保 1 处理中 2.部分购买 3.正常 4.已派减
				initSocialFundStatus(socialInfo, providentFund, vo, sf);
				vo.setEmpIdCard(dis.getEmpIdcard());
				vo.setDepartNo(dis.getSettleDomainCode());
				if (Common.isNotNull(dis.getChangeContractAndEmployee())
						&& CommonConstants.ZERO_STRING.equals(dis.getChangeContractAndEmployee())
						&& (Common.isNotNull(vo.getSocialStatus()) || Common.isNotNull(vo.getFundStatus()))) {
					vo.setChangeContractAndEmployee(dis.getChangeContractAndEmployee());
					vo.setUserId(user.getId());
					vo.setUserName(user.getNickname());
					vo.setEmpName(dis.getEmpName());
					vo.setDeptName(dis.getSettleDomainName());
					vo.setDetailId(dis.getId());
				}
				R<Boolean> resUp = archivesDaprUtil.updateProjectSocialFund(vo);
				if (Common.isEmpty(resUp) || !(CommonConstants.SUCCESS.intValue() == resUp.getCode()) || !resUp.getData().booleanValue()) {
					errorList.add(new ErrorMessage(-1, vo.getEmpIdCard() + DispatchConstants.DISPATCH_SYN_DOC_EXE, CommonConstants.RED, dis.getEmpName()));
					return true;
				}
				// 派减公积金办理失败不同步档案的相关字段信息
			} else if (!(CommonConstants.ONE_STRING.equals(dis.getType())
					&& CommonConstants.ONE_INT == flag
					&& CommonConstants.ONE_STRING.equals(typeSub))) {
				UpProjectSocialFundVo vo = new UpProjectSocialFundVo();
				// 社保状态 社保状态（字典）: 0 无社保 1 处理中 2.部分购买 3.正常 4.已派减
				initSocialFundStatus(socialInfo, providentFund, vo, sf);
				if (Common.isNotNull(vo.getSocialStatus()) || Common.isNotNull(vo.getFundStatus())) {
					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()) {
						errorList.add(new ErrorMessage(-1, vo.getEmpIdCard() + DispatchConstants.DISPATCH_SYN_DOC_EXE, CommonConstants.RED, dis.getEmpName()));
						return true;
					}
				}
			}
		} else {
			errorList.add(new ErrorMessage(-1, "派单数据错误！"));
		}
		return false;
	}


	// 审核或办理，更新离职待办
	// isSuccess 0：失败；1：成功
	private void sendLeave(String id, String doType, String doStatus, String isSuccess, String failRemark, YifuUser user) {

		BaseServiceParamListVO updateVo = new BaseServiceParamListVO();
		List<String> idList = new ArrayList<>();
		idList.add(id);
		updateVo.setListParam(idList);
		updateVo.setDoType(doType);
		updateVo.setDoStatus(doStatus);
		updateVo.setIsSuccess(isSuccess);
		if (Common.isNotNull(isSuccess) && CommonConstants.ZERO_STRING.equals(isSuccess)) {
			updateVo.setRemark(failRemark);
			if (user != null && Common.isNotNull(user.getNickname())) {
				updateVo.setUserName(user.getNickname());
			}
		}

		cspDaprUtil.reduceHandleToLeave(updateVo);
	}

	/**
	 * @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;
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 派增：
	 * * 1、派单处社保或公积金状态为待审核、待办理、办理中，项目档案处社保或公积金状态为处理中1；
	 * * 2、派单处社保或公积金状态为审核不通过或办理失败，项目档案处社保状态为无社保，公积金状态为无公积金0；
	 * * 3、派单处社保状态为部分办理失败，项目档案处社保状态为部分购买 2
	 * * 4、派单处社保或公积金状态为办理成功，项目档案处社保或公积金状态为正常 3
	 * * 派减：
	 * * 1、派减状态为待审核、待办理、审核不通过、办理失败，项目档案处社保或公积金状态不变；
	 * * 2、派减状态为办理成功，项目档案处社保或公积金状态变为已派减 4
	 * * 人员档案处社保或公积金状态根据身份证+项目进行整合：
	 * * 社保状态优先级：正常>部分购买>处理中>已派减>无社保
	 * * 公积金状态优先级：正常>处理中>已派减>无公积金
	 * @Date 15:18 2022/8/9
	 * @Param
	 **/
	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.FOUR_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.TWELVE_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.FOUR_STRING.equals(sf.getPensionHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
							|| CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle()))
			) {
				vo.setSocialStatus(CommonConstants.TWO_STRING);
			}
			// 待办理或办理中或部分办理失败或审核不通过部分办理成功或派减办理中为 处理中
			if (CommonConstants.ZERO_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.TWO_STRING.equals(sf.getSocialStatus())
					|| CommonConstants.ELEVEN_STRING.equals(sf.getSocialStatus())) {
				vo.setSocialStatus(CommonConstants.ONE_STRING);
			}
			if (CommonConstants.NINE_STRING.equals(sf.getSocialStatus())) {
				// 如果办理失败   全部派减失败为正常购买
				if (CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())
						&& CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
						&& CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
						&& CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
						&& CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
						&& (CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())
						|| Common.isEmpty(sf.getBigailmentHandle()))) {
					vo.setSocialStatus(CommonConstants.THREE_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);
			}
		}
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description
	 * @Date 14:34 2023/1/31
	 * @Param socialType 派单项（1养老 2医疗 3失业 4工伤 5生育 6大病），socialInfo 社保信息 type 0 派增  1 派减
	 **/
	private StringBuilder getHandleRemark(String socialType, TSocialInfo socialInfo, String type, TSocialFundInfo sf) {
		StringBuilder socialTypeRemark;
		socialTypeRemark = new StringBuilder();
		if (Common.isNotNull(socialType)) {
			String[] stArr = socialType.split(",");
			// 派增派单项处理
			if (CommonConstants.ZERO_STRING.equals(type)) {
				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("、");
					}
				}
				// 派减派单项处理
			} else if (CommonConstants.ONE_STRING.equals(type)) {
				for (String st : stArr) {
					// socialType （1养老 2医疗 3失业 4工伤 5生育 6大病）
					if (Integer.parseInt(st) == CommonConstants.ONE_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getPensionHandle())) {
						socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
					}
					if (Integer.parseInt(st) == CommonConstants.TWO_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getMedicalHandle())) {
						socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
					}
					if (Integer.parseInt(st) == CommonConstants.THREE_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getUnemployHandle())) {
						socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
					}
					if (Integer.parseInt(st) == CommonConstants.FOUR_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getWorkInjuryHandle())) {
						socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
					}
					if (Integer.parseInt(st) == CommonConstants.FIVE_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getBirthHandle())) {
						socialTypeRemark.append(CommonConstants.SOCIAL_HANDLE_TYPE[Integer.parseInt(st)]).append("、");
					}
					if (Integer.parseInt(st) == CommonConstants.SIX_INT
							&& CommonConstants.FIVE_STRING.equals(sf.getBigailmentHandle())) {
						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, boolean isAutoHandle) {
		// 办理成功 处理社保相关数据 （直接排除五险）
		updateSocialByHandle(flag, socialInfo, dis, sf);
		// 批量办理，或者办理选择对应的类型，修改对应的办理状态 (派增派减都改)
		this.setSocialSixStatus(handleStatus, socialType, socialInfo, sf, dis, isAutoHandle);
		boolean handing = CommonConstants.FOUR_STRING.equals(socialInfo.getHandleStatus());
		// HandleStatus办理状态 0 未办理 1 全部办理成功(原-已办理) 2 全部办理失败（原-办理失败） 3已派减 4办理中 5部分办理失败
		// 派减，审核不通过，社保状态不变更
		// 1.派减处理
		if (CommonConstants.ONE_STRING.equals(dis.getType())) {
			// 单个办理的时候处理派单和社保的办理状态  有办理成功也有办理失败的 为办理中

			// 位置不可变更，处理 全部派减成功  全部派减失败 部分派减成功的状态
			initReduceStatus(socialInfo, sf, dis);
			//位置不可变更 上面是状态初始化
			if (CommonConstants.SIX_STRING.equals(socialInfo.getHandleStatus())) {
				dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
				dis.setStatus(CommonConstants.TWO_STRING);
				socialInfo.setHandleStatus(CommonConstants.SIX_STRING);
				socialInfo.setReduceCan(CommonConstants.dingleDigitStrArray[1]);//改成不可派减状态
				sf.setSocialStatus(CommonConstants.ELEVEN_STRING);
				sf.setSocialReduceStatus(CommonConstants.FIVE_STRING);
			}
			// 有部分办理失败的多次派单 优化，存在办理失败的 更新为 部分办理失败
			if (CommonConstants.EIGHT_STRING.equals(sf.getSocialStatus()) &&
					(CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
							|| CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle()))) {
				sf.setSocialStatus(CommonConstants.TWELVE_STRING);
				sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
				sf.setSocialReduceDate(null);
			}
			if (CommonConstants.NINE_STRING.equals(sf.getSocialStatus()) &&
					(CommonConstants.THREE_STRING.equals(sf.getPensionHandle())
							|| CommonConstants.THREE_STRING.equals(sf.getMedicalHandle())
							|| CommonConstants.THREE_STRING.equals(sf.getUnemployHandle())
							|| CommonConstants.THREE_STRING.equals(sf.getWorkInjuryHandle())
							|| CommonConstants.THREE_STRING.equals(sf.getBirthHandle())
							|| CommonConstants.THREE_STRING.equals(sf.getBigailmentHandle()))) {
				sf.setSocialStatus(CommonConstants.TWELVE_STRING);
				sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
			}
		}
		// 2.派增处理 socialType  社保拆分的每一项（1养老 2医疗 3失业 4工伤 5生育 6大病）
		if (CommonConstants.ZERO_STRING.equals(dis.getType()) && Common.isNotNull(dis.getSocialId())) {
			//办理成功 flag=0 办理失败 flag=1
			// 派增： 2023-02-01 派减办理失败为新增状态  等同已办理成功
			if ((Common.isEmpty(sf.getPensionHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getPensionHandle())
					|| CommonConstants.FOUR_STRING.equals(sf.getPensionHandle()))
					&& (Common.isEmpty(sf.getMedicalHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getMedicalHandle())
					|| CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle()))
					&& (Common.isEmpty(sf.getUnemployHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getUnemployHandle())
					|| CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle()))
					&& (Common.isEmpty(sf.getWorkInjuryHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getWorkInjuryHandle())
					|| CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle()))
					&& (Common.isEmpty(sf.getBirthHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getBirthHandle())
					|| CommonConstants.FOUR_STRING.equals(sf.getBirthHandle()))
					&& (Common.isEmpty(sf.getBigailmentHandle())
					|| CommonConstants.ONE_STRING.equals(sf.getBigailmentHandle())
					|| CommonConstants.FOUR_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 (handing) {
				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 initReduceStatus(TSocialInfo socialInfo, TSocialFundInfo sf, TDispatchInfo dis) {
		// 全部失败
		if ((CommonConstants.FOUR_STRING.equals(socialInfo.getPensionHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getPensionHandle())
				|| Common.isEmpty(socialInfo.getPensionHandle()))
				&& (CommonConstants.FOUR_STRING.equals(socialInfo.getMedicalHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getMedicalHandle())
				|| Common.isEmpty(socialInfo.getMedicalHandle()))
				&& (CommonConstants.FOUR_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| Common.isEmpty(socialInfo.getWorkInjuryHandle()))
				&& (CommonConstants.FOUR_STRING.equals(socialInfo.getBirthHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getBirthHandle())
				|| Common.isEmpty(socialInfo.getBirthHandle()))
				&& (CommonConstants.FOUR_STRING.equals(socialInfo.getUnemployHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getUnemployHandle())
				|| Common.isEmpty(socialInfo.getUnemployHandle()))
				&& (
				((CommonConstants.FOUR_STRING.equals(socialInfo.getBigailmentHandle())
						|| CommonConstants.TWO_STRING.equals(socialInfo.getBigailmentHandle()))
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness())
				)
						|| Common.isEmpty(socialInfo.getBigailmentHandle()))
		) {
			if (partHandleStatus(socialInfo, sf, dis)) return;
			if (CommonConstants.TWO_STRING.equals(socialInfo.getPensionHandle())
					|| 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.TWO_STRING.equals(socialInfo.getMedicalHandle())) {
				// 派减部分办理失败
				if ((Common.isEmpty(sf.getPensionHandle()) || CommonConstants.TWO_STRING.equals(sf.getPensionHandle()) || CommonConstants.THREE_STRING.equals(sf.getPensionHandle()))
						&& (Common.isEmpty(sf.getMedicalHandle()) || CommonConstants.TWO_STRING.equals(sf.getMedicalHandle()) || CommonConstants.THREE_STRING.equals(sf.getMedicalHandle()))
						&& (Common.isEmpty(sf.getUnemployHandle()) || CommonConstants.TWO_STRING.equals(sf.getUnemployHandle()) || CommonConstants.THREE_STRING.equals(sf.getUnemployHandle()))
						&& (Common.isEmpty(sf.getWorkInjuryHandle()) || CommonConstants.TWO_STRING.equals(sf.getWorkInjuryHandle()) || CommonConstants.THREE_STRING.equals(sf.getWorkInjuryHandle()))
						&& (Common.isEmpty(sf.getBirthHandle()) || CommonConstants.TWO_STRING.equals(sf.getBirthHandle()) || CommonConstants.THREE_STRING.equals(sf.getBirthHandle()))
						&& (Common.isEmpty(sf.getBigailmentHandle()) || CommonConstants.TWO_STRING.equals(sf.getBigailmentHandle()) || CommonConstants.THREE_STRING.equals(sf.getBigailmentHandle()))) {
					sf.setSocialStatus(CommonConstants.EIGHT_STRING);
					sf.setSocialReduceStatus(CommonConstants.TWO_STRING);
					socialInfo.setReduceCan(CommonConstants.ONE_STRING);
					socialInfo.setHandleStatus(CommonConstants.THREE_STRING);
					dis.setSocialHandleStatus(CommonConstants.ONE_STRING);
				} else {
					socialInfo.setHandleStatus(CommonConstants.SEVEN_STRING);
					sf.setSocialStatus(CommonConstants.TWELVE_STRING);
					sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
					socialInfo.setReduceCan(CommonConstants.ZERO_STRING);
					dis.setSocialHandleStatus(CommonConstants.THREE_STRING);
				}
				return;
			}
			socialInfo.setHandleStatus(CommonConstants.ONE_STRING);
			sf.setSocialStatus(CommonConstants.NINE_STRING);
			sf.setSocialReduceStatus(CommonConstants.THREE_STRING);
			socialInfo.setReduceCan(CommonConstants.ZERO_STRING);
			dis.setSocialHandleStatus(CommonConstants.TWO_STRING);
			return;
		}
		// 全部成功
		if ((CommonConstants.THREE_STRING.equals(socialInfo.getPensionHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getPensionHandle())
				|| Common.isEmpty(socialInfo.getPensionHandle()))
				&& (CommonConstants.THREE_STRING.equals(socialInfo.getMedicalHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getMedicalHandle())
				|| Common.isEmpty(socialInfo.getMedicalHandle()))
				&& (CommonConstants.THREE_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getWorkInjuryHandle())
				|| Common.isEmpty(socialInfo.getWorkInjuryHandle()))
				&& (CommonConstants.THREE_STRING.equals(socialInfo.getBirthHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getBirthHandle())
				|| Common.isEmpty(socialInfo.getBirthHandle()))
				&& (CommonConstants.THREE_STRING.equals(socialInfo.getUnemployHandle())
				|| CommonConstants.TWO_STRING.equals(socialInfo.getUnemployHandle())
				|| Common.isEmpty(socialInfo.getUnemployHandle()))
				&& ((
				(CommonConstants.THREE_STRING.equals(socialInfo.getBigailmentHandle())
						|| CommonConstants.TWO_STRING.equals(socialInfo.getBigailmentHandle()))
						&& CommonConstants.ZERO_STRING.equals(socialInfo.getIsIllness()))
				|| Common.isEmpty(socialInfo.getBigailmentHandle()))
		) {
			// 针对增增减的情况 直接派减完成第二次派增后 无法继续办理第一次派单项的情况优化  2023-04-07 fxj
			if (partHandleStatus(socialInfo, sf, dis)) return;
			socialInfo.setHandleStatus(CommonConstants.THREE_STRING);
			sf.setSocialStatus(CommonConstants.EIGHT_STRING);
			sf.setSocialReduceStatus(CommonConstants.TWO_STRING);
			socialInfo.setSocialReduceDate(dis.getSocialReduceDate());
			sf.setSocialReduceDate(dis.getSocialReduceDate());
			dis.setSocialHandleStatus(CommonConstants.ONE_STRING);
			return;
		}
		/*if (CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())
				||CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())
				||CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())
				||CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())
				||CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())
				||CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())){
			// 派减部分办理失败
			socialInfo.setHandleStatus(CommonConstants.SEVEN_STRING);
			sf.setSocialStatus(CommonConstants.TWELVE_STRING);
			sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
			socialInfo.setReduceCan(CommonConstants.ZERO_STRING);
			dis.setSocialHandleStatus(CommonConstants.THREE_STRING);
		}*/
		if ((Common.isEmpty(sf.getPensionHandle()) || CommonConstants.FIVE_STRING.equals(sf.getPensionHandle()))
				|| (Common.isEmpty(sf.getMedicalHandle()) || CommonConstants.FIVE_STRING.equals(sf.getMedicalHandle()))
				|| (Common.isEmpty(sf.getUnemployHandle()) || CommonConstants.FIVE_STRING.equals(sf.getUnemployHandle()))
				|| (Common.isEmpty(sf.getWorkInjuryHandle()) || CommonConstants.FIVE_STRING.equals(sf.getWorkInjuryHandle()))
				|| (Common.isEmpty(sf.getBirthHandle()) || CommonConstants.FIVE_STRING.equals(sf.getBirthHandle()))
				|| (Common.isNotNull(sf.getBigailmentHandle()) && CommonConstants.FIVE_STRING.equals(sf.getBigailmentHandle())
		)) {
			//办理中
			socialInfo.setHandleStatus(CommonConstants.SIX_STRING);
			sf.setSocialStatus(CommonConstants.ELEVEN_STRING);
			sf.setSocialReduceStatus(CommonConstants.FIVE_STRING);
			socialInfo.setReduceCan(CommonConstants.ONE_STRING);
			dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
			return;
		}
		// 派减部分办理失败
		socialInfo.setHandleStatus(CommonConstants.SEVEN_STRING);
		sf.setSocialStatus(CommonConstants.TWELVE_STRING);
		sf.setSocialReduceStatus(CommonConstants.SIX_STRING);
		socialInfo.setReduceCan(CommonConstants.ZERO_STRING);
		dis.setSocialHandleStatus(CommonConstants.THREE_STRING);
	}

	private boolean partHandleStatus(TSocialInfo socialInfo, TSocialFundInfo sf, TDispatchInfo dis) {
		// 针对增增减的情况 直接派减完成第二次派增后 无法继续办理第一次派单项的情况优化  2023-04-07 fxj
		if (CommonConstants.FIVE_STRING.equals(sf.getPensionHandle())
				|| CommonConstants.FIVE_STRING.equals(sf.getMedicalHandle())
				|| CommonConstants.FIVE_STRING.equals(sf.getUnemployHandle())
				|| CommonConstants.FIVE_STRING.equals(sf.getWorkInjuryHandle())
				|| CommonConstants.FIVE_STRING.equals(sf.getBirthHandle())
				|| CommonConstants.FIVE_STRING.equals(sf.getBigailmentHandle())
		) {
			//办理中
			socialInfo.setHandleStatus(CommonConstants.SIX_STRING);
			sf.setSocialStatus(CommonConstants.ELEVEN_STRING);
			sf.setSocialReduceStatus(CommonConstants.FIVE_STRING);
			socialInfo.setReduceCan(CommonConstants.ONE_STRING);
			dis.setSocialHandleStatus(CommonConstants.FOUR_STRING);
			return true;
		}
		return false;
	}

	private void updateSocialByHandle(int flag, TSocialInfo socialInfo, TDispatchInfo dis, TSocialFundInfo sf) {
		if (CommonConstants.ZERO_INT == flag
				&& Common.isNotNull(dis.getSocialId())
				&& CommonConstants.ZERO_STRING.equals(dis.getType())) {
			// 派增处理
			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 1 办理成功 2 办理失败
	 * @param socialType
	 * @param socialInfo
	 * @param sf
	 * @param dis
	 * @Description: 填充社保的新的六个状态字段
	 * @Author: hgw
	 * @Date: 2021/6/9 17:12
	 * @return: void
	 **/
	private void setSocialSixStatus(String handleStatus, String socialType, TSocialInfo socialInfo,
									TSocialFundInfo sf, TDispatchInfo dis, boolean isAutoHandle) {
		if (Common.isNotNull(socialType)) {
			//派增处理
			if (CommonConstants.ZERO_STRING.equals(dis.getType())) {
				if (isAutoHandle || CommonConstants.ONE_STRING.equals(dis.getAutoFlag()) || CommonConstants.FIVE_STRING.equals(socialInfo.getYgsHandleStatus())) {
					if (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 (CommonConstants.ONE_STRING.equals(handleStatus)) {
							sf.setPensionReduceStart(null);
						}
					}
					if (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 (CommonConstants.ONE_STRING.equals(handleStatus)) {
							sf.setUnemployReduceStart(null);
						}
					}
					if (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 (CommonConstants.ONE_STRING.equals(handleStatus)) {
							sf.setWorkInjuryReduceStart(null);
						}
					}
				}

				if (isAutoHandle || CommonConstants.ONE_STRING.equals(dis.getAutoFlagYsd()) || CommonConstants.FIVE_STRING.equals(socialInfo.getYsdHandleStatus())) {
					if (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 (CommonConstants.ONE_STRING.equals(handleStatus)) {
							sf.setMedicalReduceStart(null);
						}
					}
					if (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 (CommonConstants.ONE_STRING.equals(handleStatus)) {
							sf.setBirthReduceStart(null);
						}
					}
					if (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(handleStatus)) {
							sf.setBigailmentReduceStart(null);
						}
					}
				}
				// 单个办理的时候处理派单和社保的办理状态  有办理成功也有办理失败的 为办理中
				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);
				}
			}
			// 派减处理 办理成功才变更为已派减 3 ，办理失败 为4
			if (CommonConstants.ONE_STRING.equals(dis.getType())) {
				String handleStatusTemp;
				if (CommonConstants.ONE_STRING.equals(handleStatus)) {
					handleStatusTemp = CommonConstants.THREE_STRING;
				} else {
					handleStatusTemp = CommonConstants.FOUR_STRING;
				}
				boolean flag = CommonConstants.THREE_STRING.equals(handleStatusTemp);
				if (isAutoHandle || CommonConstants.ONE_STRING.equals(dis.getAutoFlag()) || CommonConstants.FIVE_STRING.equals(socialInfo.getYgsHandleStatus())) {
					if (socialType.contains(CommonConstants.ONE_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getPensionHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getPensionHandle())) {
								socialInfo.setPensionHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setPensionReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setPensionHandle(handleStatusTemp);
							if (flag) {
								sf.setPensionReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getPensionHandle())){
						sf.setPensionHandle(handleStatusTemp);
					}*/
					}
					if (socialType.contains(CommonConstants.THREE_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getUnemployHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getUnemployHandle())) {
								socialInfo.setUnemployHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setUnemployReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setUnemployHandle(handleStatusTemp);
							if (flag) {
								sf.setUnemployReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getUnemployHandle())){
						sf.setUnemployHandle(handleStatusTemp);
					}*/
					}
					if (socialType.contains(CommonConstants.FOUR_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getWorkInjuryHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getWorkInjuryHandle())) {
								socialInfo.setWorkInjuryHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setWorkInjuryReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setWorkInjuryHandle(handleStatusTemp);
							if (flag) {
								sf.setWorkInjuryReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getWorkInjuryHandle())){
						sf.setWorkInjuryHandle(handleStatusTemp);
					}*/
					}
				}
				if (isAutoHandle || CommonConstants.ONE_STRING.equals(dis.getAutoFlagYsd()) || CommonConstants.FIVE_STRING.equals(socialInfo.getYsdHandleStatus())) {
					if (socialType.contains(CommonConstants.TWO_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getMedicalHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getMedicalHandle())) {
								socialInfo.setMedicalHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setMedicalReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setMedicalHandle(handleStatusTemp);
							if (flag) {
								sf.setMedicalReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getMedicalHandle())){
						sf.setMedicalHandle(handleStatusTemp);
					}*/
					}
					if (socialType.contains(CommonConstants.FIVE_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getBirthHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getBirthHandle())) {
								socialInfo.setBirthHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setBirthReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setBirthHandle(handleStatusTemp);
							if (flag) {
								sf.setBirthReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getBirthHandle())){
						sf.setBirthHandle(handleStatusTemp);
					}*/
					}
					if (socialType.contains(CommonConstants.SIX_STRING)) {
						if (CommonConstants.FIVE_STRING.equals(sf.getBigailmentHandle())) {
							if (CommonConstants.FIVE_STRING.equals(socialInfo.getBigailmentHandle())) {
								socialInfo.setBigailmentHandle(handleStatusTemp);
								if (flag) {
									socialInfo.setBigailmentReduceStart(dis.getSocialReduceDate());
								}
							}
							sf.setBigailmentHandle(handleStatusTemp);
							if (flag) {
								sf.setBigailmentReduceStart(dis.getSocialReduceDate());
							}
						}
					/*if (CommonConstants.FOUR_STRING.equals(sf.getBigailmentHandle())){
						sf.setBigailmentHandle(handleStatusTemp);
					}*/
					}
				}
			}
		}

	}

	/**
	 * @return
	 * @Author hgw
	 * @Description 自动化办理查询导出 count
	 * @Date 2024-5-13 11:30:12
	 * @Param
	 **/
	private int getSocialSoldierAllCount(SocialHandleSearchVo searchVo, String idStr) {
		List<String> ids = new ArrayList<>();
		if (Common.isNotNull(idStr)) {
			ids = Common.initStrToList(idStr, CommonConstants.COMMA_STRING);
		}
		return baseMapper.getSocialSoldierAllCount(searchVo, ids);
	}

	/**
	 * @Description: 自动化办理查询导出
	 * @Author: hgw
	 * @Date: 2025/4/25 18:33
	 * @return: java.util.List<com.yifu.cloud.plus.v1.yifu.social.vo.SocialSoldierExportVo>
	 **/
	private List<SocialSoldierExportVo> getSocialSoldierAllList(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.getSocialSoldierAllList(searchVo, Common.getList(idStr));
	}

	/**
	 * @return
	 * @Author hgw
	 * @Description 社保士兵导出 count
	 * @Date 2024-5-13 11:30:12
	 * @Param
	 **/
	private int getSocialSoldierCount(SocialHandleSearchVo searchVo, String idStr) {
		List<String> ids = new ArrayList<>();
		if (Common.isNotNull(idStr)) {
			ids = Common.initStrToList(idStr, CommonConstants.COMMA_STRING);
		}
		return baseMapper.getSocialSoldierCount(searchVo, ids);
	}

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

	/**
	 * @return
	 * @Author hgw
	 * @Description 导出 社保士兵
	 * @Date 2024-5-13 11:28:08
	 * @Param
	 **/
	@Override
	public void doExportSocialSoldier(HttpServletResponse response, SocialHandleSearchVo searchVo, String idStr, String[] exportFields) {
		String fileName = DispatchConstants.SOCIAL_SOLDIER_EXPORT + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<SocialSoldierExportVo> list = new ArrayList<>();
		long count = getSocialSoldierCount(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 = EasyExcelFactory.write(out, SocialSoldierExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				ExcelUtil<SocialSoldierExportVo> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getSocialSoldierList(searchVo, idStr);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(SocialSoldierExportVo.class);
						for (SocialSoldierExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet(DispatchConstants.SOCIAL_SOLDIER_EXPORT + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						i += CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
				excelWriter.finish();
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet(DispatchConstants.SOCIAL_SOLDIER_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);
			}
		}
	}

	/**
	 * @return
	 * @Author hgw
	 * @Description 自动化办理查询导出
	 * @Date 2025-4-25 18:29:18
	 * @Param
	 **/
	@Override
	public void doExportSocialSoldierAll(HttpServletResponse response, SocialHandleSearchVo searchVo, String idStr, String[] exportFields) {
		String fileName = DispatchConstants.SOCIAL_SOLDIER_EXPORT_ALL + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<SocialSoldierExportVo> list = new ArrayList<>();
		long count = getSocialSoldierAllCount(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 = EasyExcelFactory.write(out, SocialSoldierExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				ExcelUtil<SocialSoldierExportVo> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getSocialSoldierAllList(searchVo, idStr);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(SocialSoldierExportVo.class);
						for (SocialSoldierExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet(DispatchConstants.SOCIAL_SOLDIER_EXPORT + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						i += CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
				excelWriter.finish();
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet(DispatchConstants.SOCIAL_SOLDIER_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);
			}
		}
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 导出 社保花名册
	 * @Date 17:40 2022/7/27
	 * @Param
	 **/
	@Override
	public void doexportSocialRecordRoster(HttpServletResponse response, SocialHandleSearchVo searchVo, String idStr
			, String[] exportFields, YifuUser user) {
		String fileName = DispatchConstants.SOCIAL_RECORD_ROSTER_EXPORT + DateUtil.getThisTime() + 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;
			String userId = user.getId();
			String userName = user.getNickname();
			List<String> idString = null;
			if (count > CommonConstants.ZERO_INT) {

				// 加上非办理人，导出只有姓名身份证和异常
				Map<String, Integer> socialHuMap = tSocialfundHouseResService.getMapByHandleUser(userId);

				WriteSheet writeSheet;
				ExcelUtil<SocialHandleExportVo> util;
				String errorRemark = "暂无权限";
				// 导出日志list
				List<TDispatchExportLog> logList;
				TDispatchExportLog exportLog;
				SocialHandleExportVo newErrorVo;
				SocialHandleExportVo vo;
				for (int i = 0; i <= count; ) {
					logList = new ArrayList<>();
					idString = new ArrayList<>();
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getRecordRosterList(searchVo, idStr);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(SocialHandleExportVo.class);
						for (int j = 0; j < list.size(); j++) {
							vo = list.get(j);
							util.convertEntity(vo, null, null, null);
							if (Common.isNotNull(vo.getSocialHouseholdName())) {
								if (socialHuMap.get(vo.getSocialHouseholdName()) == null) {
									newErrorVo = new SocialHandleExportVo();
									newErrorVo.setEmpName(vo.getEmpName());
									newErrorVo.setEmpMobile(vo.getEmpMobile());
									newErrorVo.setErrorRemark(errorRemark);
									// 将list的该vo替换成新vo
									list.set(j, newErrorVo);
								} else {
									exportLog = new TDispatchExportLog();
									exportLog.setDispatchId(vo.getDispatchId());
									exportLog.setCreateTime(LocalDateTime.now());
									exportLog.setUserId(userId);
									exportLog.setUserName(userName);
									logList.add(exportLog);
									//有办理人权限导出数据后更新导出标识
									idString.add(vo.getId());
								}
							}
						}
					}
					if (Common.isNotNull(list)) {
						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();
					}
					if (Common.isNotNull(idString)){
						updateSocialRecords(idString);
					}
					// 新增导出人记录
					if (!logList.isEmpty()) {
						tDispatchExportLogService.saveBatch(logList);
					}
				}
				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();
			}
			if ( Common.isNotNull(idString)){
				idString.clear();
			}
			out.flush();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 社保花名册 count
	 * @Date 17:59 2022/7/27
	 * @Param
	 **/
	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);
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 社保花名册 list
	 * @Date 17:59 2022/7/27
	 * @Param
	 **/
	@Override
	public List<SocialHandleExportVo> getRecordRosterList(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.getSocialRecordRosterList(searchVo, Common.getList(idStr));
	}

	private boolean updateSocialRecords(List<String> idStr) {
		return baseMapper.updateSocialRecords(idStr) >= 0;
	}

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

	/**
	 * 获取税友自动化办理推送的条数，限制【社保办理权限】菜单的办理人权限
	 * @param userId
	 */
	@Override
	public Long countSocialFriendByAuth(String userId) {
		return baseMapper.countSocialFriendByAuth(userId);
	}

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

	@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);
	}

	/**
	 * 导出公积金补缴清册
	 *
	 * @param idStr
	 * @param searchVo
	 * @return
	 * @Author fxj
	 * @Date 2020-06-08
	 **/
	@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));
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 导出公积金补缴清册
	 * @Date 20:05 2022/7/27
	 * @Param
	 **/
	@Override
	public void doexportFundRecordChange(HttpServletResponse response, String idStr, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.SOCIAL_RECORD_EXPORT + DateUtil.getThisTime() + 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) {
				WriteSheet writeSheet;
				ExcelUtil<FundHandleExportVo> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = getFundRecordList(searchVo, idStr);
					if (Common.isNotNull(list)) {
						util = new ExcelUtil<>(FundHandleExportVo.class);
						for (FundHandleExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcel.writerSheet("公积金变更清册" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
					// 更新导出状态
					updateFundRecords(searchVo, idStr);
				}
				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);
			}
		}
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 10:05 2023/7/18
	 * @Param
	 **/
	@Override
	public void doexportSocialRecordNew(HttpServletResponse response, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.SOCIAL_MEDICAL_EXPORT + searchVo.getSocialHouseholdName() + "_" + searchVo.getDisMonth() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchSocialExportVo> list = new ArrayList<>();
		try (ServletOutputStream 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).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			TDispatchSocialExportVo vo;

			List<Integer> columnIndexes = Arrays.asList(0, 12);
			CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
			CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
			CustomCellStyleTwoStrategy customCellStyleStrategyTwo = new CustomCellStyleTwoStrategy(columnIndexes);
			CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);

			writeTable0 = EasyExcel.writerTable(0).
					head(headOne()).
					registerWriteHandler(customCellStyleStrategy).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(headTwo(searchVo.getSocialHouseholdName(), searchVo.getUnitCreditCode())).
					registerWriteHandler(customCellStyleStrategyOne).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(headThree()).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig()).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			writeTable3 = EasyExcel.writerTable(3).
					head(headFour()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 50, (short) 20))
					.build();
			writeTable4 = EasyExcel.writerTable(4).
					head(headFive()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			//派增的数据
			searchVo.setType(CommonConstants.ZERO_STRING);
			long count = getSocialDisRecordCount(searchVo);
			if (count > CommonConstants.ZERO_INT) {
				list = getSocialDisRecord(searchVo);
				if (Common.isNotNull(list)) {
					//判断list的大小是否大于10
					if (list.size() < 10) {
						int size = 10 - list.size();
						int num = list.size() + 1;
						for (int i = 1; i <= size; i++) {
							vo = new TDispatchSocialExportVo();
							vo.setNum(num);
							num++;
							list.add(vo);
						}
					}
					writeSheet = EasyExcel.writerSheet("增员").build();
					// 第一次写入会创建头
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			} else {
				writeSheet = EasyExcel.writerSheet("增员").build();
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				// 第二次写如也会创建头，然后在第一次的后面写入数据
				int num = 1;
				for (int i = 1; i <= 10; i++) {
					vo = new TDispatchSocialExportVo();
					vo.setNum(num);
					num++;
					list.add(vo);
				}
				excelWriter.write(list, writeSheet, writeTable2);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
			}
			//派减的数据
			searchVo.setType(CommonConstants.ONE_STRING);
			long count1 = getSocialDisRecordCount(searchVo);
			if (count1 > CommonConstants.ZERO_INT) {
				list = baseMapper.getSocialReduceDisRecord(searchVo);
				if (Common.isNotNull(list)) {
					//判断list的大小是否大于10
					if (list.size() < 10) {
						int size = 10 - list.size();
						int num = list.size() + 1;
						for (int i = 1; i <= size; i++) {
							vo = new TDispatchSocialExportVo();
							vo.setNum(num);
							num++;
							list.add(vo);
						}
					}
					writeSheet = EasyExcel.writerSheet("减员").build();
					// 第一次写入会创建头
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			} else {
				writeSheet = EasyExcel.writerSheet("减员").build();
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				// 第二次写如也会创建头，然后在第一次的后面写入数据
				int num = 1;
				list = new ArrayList<>();
				for (int i = 1; i <= 10; i++) {
					vo = new TDispatchSocialExportVo();
					vo.setNum(num);
					num++;
					list.add(vo);
				}
				excelWriter.write(list, writeSheet, writeTable2);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 14:05 2023/7/20
	 * @Param
	 **/
	@Override
	public void doexportSocialPensionRecord(HttpServletResponse response, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.SOCIAL_PERSION_EXPORT + searchVo.getSocialHouseholdName() + "_" + searchVo.getDisMonth() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchSocialPersionExportVo> list = new ArrayList<>();
		try (ServletOutputStream 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).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			TDispatchSocialPersionExportVo vo;
			TDispatchSocialPersionReduceExportVo reduceVo;
			//派增的数据
			searchVo.setType(CommonConstants.ZERO_STRING);
			long count = getSocialPersionDisCount(searchVo);
			List<Integer> columnIndexes = Arrays.asList(0, 17);
			CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
			CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
			CustomCellStyleTwoStrategy customCellStyleStrategyTwo = new CustomCellStyleTwoStrategy(columnIndexes);
			CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);

			writeTable0 = EasyExcel.writerTable(0).
					head(persionHeadOne()).
					registerWriteHandler(customCellStyleStrategy).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(persionHeadTwo(searchVo.getSocialHouseholdName(), searchVo.getCustomerNo())).
					registerWriteHandler(customCellStyleStrategyOne).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(persionHead()).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthOneConfig()).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 30, (short) 20))
					.build();
			writeTable3 = EasyExcel.writerTable(3).
					head(persionHeadThree()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 150, (short) 20))
					.build();
			writeTable4 = EasyExcel.writerTable(4).
					head(persionHead1()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20))
					.build();
			if (count > CommonConstants.ZERO_INT) {
				list = getSocialPersionDisRecord(searchVo);
				if (Common.isNotNull(list)) {
					//判断list的大小是否大于10
					if (list.size() < 10) {
						int size = 10 - list.size();
						int num = list.size() + 1;
						for (int i = 1; i <= size; i++) {
							vo = new TDispatchSocialPersionExportVo();
							vo.setNum(num);
							num++;
							list.add(vo);
						}
					}
					writeSheet = EasyExcel.writerSheet("增员").build();
					// 第一次写入会创建头
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			} else {
				writeSheet = EasyExcel.writerSheet("增员").build();
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				int num = 1;
				for (int i = 1; i <= 10; i++) {
					vo = new TDispatchSocialPersionExportVo();
					vo.setNum(num);
					num++;
					list.add(vo);
				}
				excelWriter.write(list, writeSheet, writeTable2);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
			}
			//派减的数据
			searchVo.setType(CommonConstants.ONE_STRING);
			long count1 = getSocialPersionReduceDisCount(searchVo);
			//获取要导出的列表
			List<TDispatchSocialPersionReduceExportVo> listReduce = new ArrayList<>();

			List<Integer> columnIndex = Arrays.asList(0, 24);
			CustomCellStyleStrategy customCellStyleStrategy1 = new CustomCellStyleStrategy(columnIndex);
			CustomCellStyleOneStrategy customCellStyleStrategy2 = new CustomCellStyleOneStrategy(columnIndex);
			CustomCellStyleTwoStrategy customCellStyleStrategy3 = new CustomCellStyleTwoStrategy(columnIndex);
			CustomCellStyleThreeStrategy customCellStyleStrategy4 = new CustomCellStyleThreeStrategy(columnIndex);

			writeTable0 = EasyExcel.writerTable(0).
					head(persionReduceHeadOne()).
					registerWriteHandler(customCellStyleStrategy1).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(persionReduceHeadTwo(searchVo.getSocialHouseholdName(), searchVo.getCustomerNo())).
					registerWriteHandler(customCellStyleStrategy2).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(persionReduceHead()).
					registerWriteHandler(customCellStyleStrategy4).
					registerWriteHandler(new CustomCellWriteWidthTwoConfig()).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 50, (short) 20))
					.build();
			writeTable3 = EasyExcel.writerTable(3).
					head(persionReduceHead1()).
					registerWriteHandler(customCellStyleStrategy3).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20))
					.build();
			if (count1 > CommonConstants.ZERO_INT) {
				listReduce = getSocialPersionReduceDisRecord(searchVo);
				if (Common.isNotNull(listReduce)) {
					//判断list的大小是否大于10
					if (listReduce.size() < 10) {
						int size = 10 - listReduce.size();
						int num = listReduce.size() + 1;
						for (int i = 1; i <= size; i++) {
							reduceVo = new TDispatchSocialPersionReduceExportVo();
							reduceVo.setNum(num);
							num++;
							listReduce.add(reduceVo);
						}
					}
					writeSheet = EasyExcel.writerSheet("减员").build();
					// 第一次写入会创建头
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					excelWriter.write(listReduce, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				}
			} else {
				writeSheet = EasyExcel.writerSheet("减员").build();
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				int num = 1;
				for (int i = 1; i <= 10; i++) {
					reduceVo = new TDispatchSocialPersionReduceExportVo();
					reduceVo.setNum(num);
					num++;
					listReduce.add(reduceVo);
				}
				excelWriter.write(listReduce, writeSheet, writeTable2);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

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

	private boolean updateFundRecords(SocialHandleSearchVo searchVo, String idStr) {
		return baseMapper.updateFundRecords(searchVo, Common.getList(idStr)) >= 0;
	}


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

	private long getSocialDisRecordCount(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialDisRecordCount(searchVo);
	}

	private long getFCount(SocialHandleSearchVo searchVo) {
		return baseMapper.getFCount(searchVo);
	}

	private List<TDispatchSocialExportVo> getSocialDisRecord(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialDisRecord(searchVo);
	}

	private List<TDispatchFundPersionExportVo> getDispatchFundPersion(SocialHandleSearchVo searchVo) {
		return baseMapper.getFundPersionExportVo(searchVo);
	}

	private List<TDispatchFundSupplementaryExportVo> getDispatchFundSupplementary(SocialHandleSearchVo searchVo) {
		return baseMapper.getFundSupplementarynExportVo(searchVo);
	}

	private TDispatchFundSumExportVo getFundSumExportVo(SocialHandleSearchVo searchVo) {
		return baseMapper.getFundSumExportVo(searchVo);
	}

	private TDispatchFundSumVo getFundSumVo(SocialHandleSearchVo searchVo) {
		return baseMapper.getFundSumExportVoOne(searchVo);
	}

	private CompanyProVo companyProVo(String houseName, SocialHandleSearchVo searchVo) {
		return baseMapper.getFundPersionExportVoOne(houseName, searchVo);
	}


	private HouseNameConfigVo getFundSumExportVoTwo(String houseName, SocialHandleSearchVo searchVo) {
		return baseMapper.getFundSumExportVoTwo(houseName, searchVo);
	}

	private long getSocialPersionDisCount(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialPersionDisCount(searchVo);
	}

	private List<TDispatchSocialPersionExportVo> getSocialPersionDisRecord(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialPersionDisRecord(searchVo);
	}

	private long getSocialPersionReduceDisCount(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialPersionReduceDisCount(searchVo);
	}

	private List<TDispatchSocialPersionReduceExportVo> getSocialPersionReduceDisRecord(SocialHandleSearchVo searchVo) {
		return baseMapper.getSocialPersionReduceDisRecord(searchVo);
	}

	/**
	 * @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;
	}

	/**
	 * 获取社保和公积金派减日期
	 *
	 * @param empId
	 * @return
	 * @Author hgw
	 * @Date 2023-1-5 11:00:47
	 **/
	@Override
	public SocialAndFundReduceVo getSocialAndFundReduceInfo(String empId) {
		SocialAndFundReduceVo vo = new SocialAndFundReduceVo();
		TSocialInfo socialInfo = socialMapper.selectOne(Wrappers.<TSocialInfo>query().lambda()
				.eq(TSocialInfo::getEmpId, empId)
				.eq(TSocialInfo::getHandleStatus, CommonConstants.THREE_STRING)
				.eq(TSocialInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
				.orderByDesc(TSocialInfo::getCreateTime)
				.last(CommonConstants.LAST_ONE_SQL));
		TProvidentFund fund = fundMapper.selectOne(Wrappers.<TProvidentFund>query().lambda()
				.eq(TProvidentFund::getEmpId, empId)
				.eq(TProvidentFund::getDeleteFlag, CommonConstants.ZERO_STRING)
				.eq(TProvidentFund::getHandleStatus, CommonConstants.THREE_STRING)
				.orderByDesc(TProvidentFund::getCreateTime)
				.last(CommonConstants.LAST_ONE_SQL));
		if (null != socialInfo && null != socialInfo.getSocialReduceDate()) {
			vo.setSocialReduceDate(DateUtil.formatDate(socialInfo.getSocialReduceDate()));
		}
		if (null != fund && null != fund.getFundReduceDate()) {
			vo.setFundReduceDate(DateUtil.formatDate(fund.getFundReduceDate()));
		}
		return vo;
	}

	/**
	 * @param errorMessageList
	 * @Description: 判断所有返回数据，是否全部为正确的
	 * @Author: hyc
	 * @Date: 2023/03/02 11:03
	 * @return: R<List < ErrorMessage>>
	 **/
	private R<List<ErrorMessage>> judgeAllMessage(List<ErrorMessage> errorMessageList) {
		if (!errorMessageList.isEmpty() && errorMessageList.stream().noneMatch(e -> e.getColor().equals(CommonConstants.RED))) {
			return R.ok();
		}
		if (!errorMessageList.isEmpty() && errorMessageList.stream().anyMatch(e -> CommonConstants.ONE_STRING.equals(e.getName()))) {
			return R.ok(errorMessageList, "error");
		}
		return R.ok(errorMessageList);
	}

	private void initAreaMap(Map<String, SysArea> areaHashMap, Map<String, SysArea> areaIdMap, R<AreaVo> areaListR) {
		AreaVo areaList = areaListR.getData();
		if (null != areaList && !areaList.getSysAreaList().isEmpty()) {
			for (SysArea area : areaList.getSysAreaList()) {
				areaHashMap.put(area.getAreaName(), area);
				areaIdMap.put(Integer.toString(area.getId()), area);
			}
		}
	}

	@Override
	public R<List<ErrorMessage>> dispatchAdd(TDispatchImportVo importVo) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		HashMap<String, SysArea> areaMap = new HashMap<>();
		HashMap<String, SysArea> areaIdMap = new HashMap<>();
		importVo.setRowIndex(CommonConstants.ONE_INT);
		List<TDispatchImportVo> importVoList = new ArrayList<>();
		importVoList.add(importVo);
		// 如果档案地市空  只能用缴纳地封装，如果缴纳地有问题直接返回
		if (null == importVo.getFileCity()) {
			R<AreaVo> areaListR = upmsDaprUtils.getAreaListR();
			if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
				return R.failed(PreDispatchConstants.GET_AREA_INFO);
			}
			initAreaMap(areaMap, areaIdMap, areaListR);
		}
		//  档案地市没问题 开始派单处理
		this.importTDispatchInfo(importVoList, errorMessageList, user, null, new HashMap<>(),null);
		if (errorMessageList.isEmpty() || CommonConstants.GREEN.equals(errorMessageList.get(0).getColor())) {
			return R.ok();
		} else {
			return R.failed(errorMessageList);
		}

	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 批量导入办理
	 * @Date 15:46 2023/5/8
	 * @Param
	 **/
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> fundImportHandle(InputStream inputStream, TDispatchInfo tDispatchInfo, boolean isAutoFlag) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)) {
			R.failed(CommonConstants.USER_FAIL);
		}
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<FundImportHandleVo> util1 = new ExcelUtil<>(FundImportHandleVo.class);
		ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, FundImportHandleVo.class, new ReadListener<FundImportHandleVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<FundImportHandleVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(FundImportHandleVo 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)) {
						errorMessage.setData(data);
						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());
					fundImportHandle(cachedDataList, errorMessageList, user, tDispatchInfo, map, isAutoFlag);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return this.judgeAllMessage(errorMessageList);
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 批量导入办理 处理逻辑
	 * @Date 16:45 2023/5/8
	 * @Param
	 **/
	public void fundImportHandle(List<FundImportHandleVo> excelVOList, List<ErrorMessage> errorMessageList,
								 YifuUser user, TDispatchInfo dispatchInfo, ConcurrentHashMap<String, String> map, boolean isAutoFlag) {
		if (!Common.isNotNull(excelVOList)) {
			return;
		}
		// 个性化校验逻辑
		FundImportHandleVo excel;
		int flag = 1;
		String handleStatus = "2";
		SocialHandleSearchVo tDispatchInfo = new SocialHandleSearchVo();
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		tDispatchInfo.setAuthSql(dispatchInfo.getAuthSql());
		tDispatchInfo.setCreateBy(dispatchInfo.getCreateBy());
		tDispatchInfo.setMId(dispatchInfo.getMId());
		tDispatchInfo.setMenuInfo(dispatchInfo.getMenuInfo());
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		tDispatchInfo.setCreateBy(user.getId());
		List<TDispatchInfo> dispatchInfos = baseMapper.getTDispatchFundHandleNoPage(tDispatchInfo, excelVOList.stream()
				.map(FundImportHandleVo::getEmpIdcard).collect(Collectors.toList()), null);
		Map<String, TDispatchInfo> dispatchMap = new HashMap<>();
		if (Common.isNotNull(dispatchInfos)) {
			dispatchMap = dispatchInfos.stream().collect(Collectors.toMap(TDispatchInfo::getEmpIdcard, TDispatchInfo -> TDispatchInfo));
		}
		TDispatchInfo dispatch;
		ErrorMessage errorMessage = null;
		List<ErrorMessage> messageList = null;
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if (Common.isEmpty(excel)
					|| (!CommonConstants.ZERO_STRING.equals(excel.getHandleStatus())
					&& !CommonConstants.ONE_STRING.equals(excel.getHandleStatus()))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(CommonConstants.PARAM_INFO_ERROR), excel));
				continue;
			}
			//表内数据重复 员工身份证
			if (null == map.get(excel.getEmpIdcard())) {
				map.put(excel.getEmpIdcard(), excel.getRowIndex().toString());
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_IMPORT_SAME_INFO), excel));
				continue;
			}
			// 办理失败，原因必填
			if (CommonConstants.ONE_STRING.equals(excel.getHandleStatus()) && Common.isEmpty(excel.getReasonType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.FUND_IMPORT_HANDLE_REASON_NOT_EMPY), excel));
				continue;
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getHandleStatus())) {
				flag = CommonConstants.ZERO_INT;
				handleStatus = CommonConstants.ONE_STRING;
				excel.setReasonType(CommonConstants.EMPTY_STRING);
			}
			if (CommonConstants.ONE_STRING.equals(excel.getHandleStatus())) {
				flag = CommonConstants.ONE_INT;
				handleStatus = CommonConstants.TWO_STRING;
			}
			dispatch = dispatchMap.get(excel.getEmpIdcard());
			//批量办理增加派单类型 fxj 2025-04-24 V1.7.10
			if (Common.isEmpty(dispatch) || !excel.getType().equals(dispatch.getType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.FUND_IMPORT_HANDLE_NOT_EXITS), excel));
				continue;
			}
			if (Common.isEmpty(excel.getRemark())) {
				excel.setRemark(CommonConstants.EMPTY_STRING);
			}
			try {
				// 执行数据插入操作 组装
				messageList = addBatchApplyHandle(null, null, Collections.singletonList(dispatch.getId()), CommonConstants.ONE_STRING, user
						, flag, handleStatus, (Common.isEmpty(excel.getReasonType()) ? "" : excel.getReasonType() + CommonConstants.COLON_STRING)
								+ excel.getRemark(), null, excel.getReasonType(), isAutoFlag);
				if (Common.isNotNull(messageList)) {
					errorMessage = messageList.get(CommonConstants.ZERO_INT);
					errorMessage.setData(excel);
				} else {
					errorMessage = new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN, excel);
				}
				errorMessageList.add(errorMessage);
			} catch (Exception e) {
				log.error("批量导入办理异常：", e);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_FAILED, excel));
			}
		}
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 社保批量导入办理
	 * @Date 15:46 2023/5/15
	 * @Param
	 **/
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> importSocialHandler(InputStream inputStream, String mId, boolean isAutoHandle) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)) {
			R.failed(CommonConstants.USER_FAIL);
		}
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<SocialImportHandleVo> util1 = new ExcelUtil<>(SocialImportHandleVo.class);
		ConcurrentHashMap<String, String> idcardMap = new ConcurrentHashMap<>();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, SocialImportHandleVo.class, new ReadListener<SocialImportHandleVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<SocialImportHandleVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(SocialImportHandleVo 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)) {
						errorMessage.setData(data);
						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());
					socialImportHandle(cachedDataList, errorMessageList, user, mId, idcardMap, isAutoHandle);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return this.judgeAllMessage(errorMessageList);
	}

	/**
	 * @return
	 * @Author huych
	 * @Description 社保批量导入办理（1养老 2医疗 3失业 4工伤 5生育 6大病）
	 * @Date 16:45 2023/5/15
	 * @Param
	 **/
	public void socialImportHandle(List<SocialImportHandleVo> excelVOList, List<ErrorMessage> errorMessageList,
								   YifuUser user, String mId, ConcurrentHashMap<String, String> map, boolean isAutoHandle) {
		if (!Common.isNotNull(excelVOList)) {
			return;
		}
		// 个性化校验逻辑
		SocialImportHandleVo excel;
		SocialHandleSearchVo tDispatchInfo = new SocialHandleSearchVo();
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		tDispatchInfo.setMId(mId);
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		tDispatchInfo.setCreateBy(user.getId());
		List<TDispatchInfo> dispatchInfos = baseMapper.getTDispatchSocialHandleNoPage(tDispatchInfo, excelVOList.stream()
				.map(SocialImportHandleVo::getEmpIdcard).collect(Collectors.toList()), null);
		Map<String, TDispatchInfo> dispatchMap = new HashMap<>();
		if (Common.isNotNull(dispatchInfos)) {
			dispatchMap = dispatchInfos.stream().collect(Collectors.toMap(TDispatchInfo::getEmpIdcard, TDispatchInfo -> TDispatchInfo));
		}

		TDispatchInfo dispatch;
		ErrorMessage errorMessage;
		List<ErrorMessage> messageList;

		String handlerRemaek;

		List<TDispatchInfo> failueList = new ArrayList<>();
		ConcurrentHashMap<String, String> socialMap = new ConcurrentHashMap<>();
		ConcurrentHashMap<String, String> fundMap = new ConcurrentHashMap<>();
		for (int i = 0; i < excelVOList.size(); i++) {
			StringBuilder socialSucessType = new StringBuilder();
			StringBuilder socialFailureType = new StringBuilder();
			excel = excelVOList.get(i);

			//表内数据重复 员工身份证
			if (null == map.get(excel.getEmpIdcard())) {
				map.put(excel.getEmpIdcard(), excel.getRowIndex().toString());
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_IMPORT_SAME_INFO), excel));
				continue;
			}
			//身份证加任一险种必填
			if (Common.isEmpty(excel.getDbHandleStatus()) && Common.isEmpty(excel.getGsHandleStatus())
					&& Common.isEmpty(excel.getSjHandleStatus()) && Common.isEmpty(excel.getSyHandleStatus())
					&& Common.isEmpty(excel.getYbHandleStatus()) && Common.isEmpty(excel.getYlHandleStatus())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_IMPORT_HANDLE_NOT_EMPY), excel));
				continue;
			}
			// 任一险种办理失败，失败类型必填
			if (Common.isEmpty(excel.getReasonType()) && (CommonConstants.ONE_STRING.equals(excel.getDbHandleStatus())
					|| CommonConstants.ONE_STRING.equals(excel.getGsHandleStatus()) || CommonConstants.ONE_STRING.equals(excel.getSjHandleStatus())
					|| CommonConstants.ONE_STRING.equals(excel.getSyHandleStatus()) || CommonConstants.ONE_STRING.equals(excel.getYbHandleStatus())
					|| CommonConstants.ONE_STRING.equals(excel.getYlHandleStatus()))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_IMPORT_HANDLE_REASON_NOT_EMPY), excel));
				continue;
			}

			dispatch = dispatchMap.get(excel.getEmpIdcard());
			//批量办理增加派单类型 fxj 2025-04-24 V1.7.10
			if (Common.isEmpty(dispatch) || !excel.getType().equals(dispatch.getType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.SOCIAL_IMPORT_HANDLE_NOT_EXITS), excel));
				continue;
			}

			//判断办理的险种
			if (CommonConstants.ZERO_STRING.equals(excel.getYlHandleStatus())) {
				socialSucessType.append("1,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getYlHandleStatus())) {
				socialFailureType.append("1,");
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getYbHandleStatus())) {
				socialSucessType.append("2,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getYbHandleStatus())) {
				socialFailureType.append("2,");
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getSyHandleStatus())) {
				socialSucessType.append("3,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getSyHandleStatus())) {
				socialFailureType.append("3,");
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getGsHandleStatus())) {
				socialSucessType.append("4,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getGsHandleStatus())) {
				socialFailureType.append("4,");
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getSjHandleStatus())) {
				socialSucessType.append("5,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getSjHandleStatus())) {
				socialFailureType.append("5,");
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getDbHandleStatus())) {
				socialSucessType.append("6,");
			} else if (CommonConstants.ONE_STRING.equals(excel.getDbHandleStatus())) {
				socialFailureType.append("6,");
			}
			try {
				if (Common.isNotNull(excel.getReasonType())) {
					handlerRemaek = excel.getReasonType() + CommonConstants.COLON_STRING;
				} else {
					handlerRemaek = "";
				}
				//办理成功处理
				if (socialSucessType.length() > 1) {
					if (!CommonConstants.TWO_STRING.equals(dispatch.getStatus())) {
						continue;
					}
					// 执行数据插入操作 组装
					messageList = addBatchApplyHandle(socialMap, fundMap, Collections.singletonList(dispatch.getId()), CommonConstants.ZERO_STRING, user
							, 0, CommonConstants.ONE_STRING, ServiceUtil.ifNullToEmpty(excel.getRemark()), socialSucessType.substring(0, socialSucessType.length() - 1), ServiceUtil.ifNullToEmpty(excel.getRemark()), isAutoHandle);
					if (Common.isNotNull(messageList)) {
						errorMessage = messageList.get(CommonConstants.ZERO_INT);
						errorMessage.setData(excel);
					} else {
						errorMessage = new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN, excel);
					}
					errorMessageList.add(errorMessage);
				}

				//办理失败处理
				if (socialFailureType.length() > 1) {
					if (!CommonConstants.TWO_STRING.equals(dispatch.getStatus())) {
						continue;
					}
					dispatch.setHandlerRemaek(handlerRemaek);
					dispatch.setSocialFailureType(socialFailureType.toString());
					dispatch.setExcel(excel);
					failueList.add(dispatch);
				}
			} catch (Exception e) {
				log.error("批量导入办理异常：", e);
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_FAILED, excel));
			}
		}
		if (!Common.isEmpty(failueList)) {
			SocialImportHandleVo vo;
			for (TDispatchInfo dispatchInfo : failueList) {
				vo = dispatchInfo.getExcel();
				// 执行数据插入操作 组装
				messageList = addBatchApplyHandle(socialMap, fundMap, Collections.singletonList(dispatchInfo.getId()), CommonConstants.ZERO_STRING, user
						, 1, CommonConstants.TWO_STRING, dispatchInfo.getHandlerRemaek() + ServiceUtil.ifNullToEmpty(vo.getRemark()), dispatchInfo.getSocialFailureType().substring(0, dispatchInfo.getSocialFailureType().length() - 1), dispatchInfo.getHandlerRemaek() + ServiceUtil.ifNullToEmpty(vo.getRemark()), isAutoHandle);
				if (Common.isNotNull(messageList)) {
					errorMessage = messageList.get(CommonConstants.ZERO_INT);
					errorMessage.setData(vo);
				} else {
					errorMessage = new ErrorMessage(vo.getRowIndex(), CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN, vo);
				}
				errorMessageList.add(errorMessage);
			}
		}
	}

	@Override
	public R<Boolean> updateExportSocialFlagById(String id, String status) {
		return R.ok(baseMapper.updateExportSocialFlagById(id, status) >= 0);
	}

	@Override
	public R<Boolean> updateExportFundFlagById(String id, String status) {
		return R.ok(baseMapper.updateExportFundFlagById(id, status) >= 0);
	}

	/**
	 * @param user
	 * @param roleId
	 * @Description: 判断用户是否含有某个角色
	 * @Author: hgw
	 * @Date: 2023/5/18 15:49
	 * @return: boolean
	 **/
	@Override
	public boolean haveRole(YifuUser user, long roleId) {
		if (user.getClientRoleMap() == null) {
			return false;
		}
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void doexportFundInfo(HttpServletResponse response, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.FUND_RECORD_EXPORT + "_" + searchVo.getProvidentHouseholdName() + "_" + searchVo.getDisMonth() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchFundPersionExportVo> list = new ArrayList<>();
		try (ServletOutputStream 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).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			WriteTable writeTable5;
			TDispatchFundPersionExportVo vo;

			List<Integer> columnIndexes = Arrays.asList(0, 7);
			CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
			CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
			CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);
			CustomCellStyleFourStrategy customCellStyleStrategyFour = new CustomCellStyleFourStrategy(columnIndexes);
			CustomCellStyleFiveStrategy customCellStyleStrategyFive = new CustomCellStyleFiveStrategy(columnIndexes);
			writeTable0 = EasyExcel.writerTable(0).
					head(headFisrt()).
					registerWriteHandler(customCellStyleStrategy).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 100)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(headSecond(searchVo.getProvidentHouseholdName(), searchVo)).
					registerWriteHandler(customCellStyleStrategyOne).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 100)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(headW()).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig() {
						@Override
						protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
							boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
							if (needSetWidth) {
								Sheet sheet = writeSheetHolder.getSheet();
								int columnIndex = cell.getColumnIndex();
								// 单元格文本长度大于45换行
								if (columnIndex == 3) {
									//要求将当前列的列宽设置为33英寸，理论值应该是33×256=8448，
									//但是这里的设值是8648，具体原因请看下面的计算逻辑
									sheet.setColumnWidth(0, 3000);
									sheet.setColumnWidth(1, 4000);
									sheet.setColumnWidth(2, 4000);
									sheet.setColumnWidth(3, 6000);
									sheet.setColumnWidth(4, 4000);
									sheet.setColumnWidth(6, 5000);
									sheet.setColumnWidth(5, 5000);
									sheet.setColumnWidth(7, 3500);
								}
							}
						}

					}).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			writeTable3 = EasyExcel.writerTable(3).
					head(headQ(searchVo)).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			writeTable4 = EasyExcel.writerTable(4).
					head(FundHeadR()).
					registerWriteHandler(customCellStyleStrategyFour).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20))
					.build();
			writeTable5 = EasyExcel.writerTable(5).
					head(FundHeadT()).
					registerWriteHandler(customCellStyleStrategyFive).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			//派增的数据
			long count = getFCount(searchVo);
			if (count > CommonConstants.ZERO_INT) {
				list = getDispatchFundPersion(searchVo);
				if (Common.isNotNull(list)) {
					//判断list的大小是否大于10
					if (list.size() < 10) {
						int size = 10 - list.size();
						int num = list.size() + 1;
						for (int i = 1; i <= size; i++) {
							vo = new TDispatchFundPersionExportVo();
							vo.setNum(num);
							num++;
							list.add(vo);
						}
					}
					writeSheet = EasyExcel.writerSheet(searchVo.getDisMonth()).build();
					// 第一次写入会创建头
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable5);
				}
			} else {
				list = getDispatchFundPersion(searchVo);
				if (list.size() < 10) {
					int size = 10 - list.size();
					int num = list.size() + 1;
					for (int i = 1; i <= size; i++) {
						vo = new TDispatchFundPersionExportVo();
						vo.setNum(num);
						num++;
						list.add(vo);
					}
				}
				writeSheet = EasyExcel.writerSheet(searchVo.getDisMonth()).build();
				// 第一次写入会创建头
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				// 第二次写如也会创建头，然后在第一次的后面写入数据
				excelWriter.write(list, writeSheet, writeTable2);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable5);
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}


	@Override
	public void doexportFundInfoOne(HttpServletResponse response, SocialHandleSearchVo searchVo) {
		String fileName = DispatchConstants.FUND_SUPPLEMENTARY_EXPORT + "_" + searchVo.getProvidentHouseholdName() + "_" + searchVo.getDisMonth() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TDispatchFundSupplementaryExportVo> list = new ArrayList<>();
		try (ServletOutputStream 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).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			WriteTable writeTable5;
			WriteTable writeTable6;
			WriteTable writeTable7;

			TDispatchFundSupplementaryExportVo vo;

			List<Integer> columnIndexes = Arrays.asList(0, 6);
			CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
			CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
			CustomCellStyleTwoStrategy customCellStyleStrategyTwo = new CustomCellStyleTwoStrategy(columnIndexes);
			CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);
			CustomCellStyleFourStrategy customCellStyleStrategyFour = new CustomCellStyleFourStrategy(columnIndexes);
			writeTable0 = EasyExcel.writerTable(0).
					head(headFisrtOne()).
					registerWriteHandler(customCellStyleStrategy).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 100
					)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(headQOne(searchVo.getProvidentHouseholdName())).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig() {
						@Override
						protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
							boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
							if (needSetWidth) {
								Sheet sheet = writeSheetHolder.getSheet();
								int columnIndex = cell.getColumnIndex();
								// 单元格文本长度大于45换行
								if (columnIndex == 2) {
									//要求将当前列的列宽设置为33英寸，理论值应该是33×256=8448，
									//但是这里的设值是8648，具体原因请看下面的计算逻辑
									sheet.setColumnWidth(0, 1000);
									sheet.setColumnWidth(2, 1000);
									sheet.setColumnWidth(6, 2000);
									sheet.setColumnWidth(4, 1500);
								}
							}
						}

					}).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 25)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(headQTwo(searchVo.getProvidentHouseholdName(), searchVo)).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig() {
						@Override
						protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
							boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
							if (needSetWidth) {
								Sheet sheet = writeSheetHolder.getSheet();
								int columnIndex = cell.getColumnIndex();
								// 单元格文本长度大于45换行
								if (columnIndex == 3) {
									//要求将当前列的列宽设置为33英寸，理论值应该是33×256=8448，
									//但是这里的设值是8648，具体原因请看下面的计算逻辑
									sheet.setColumnWidth(0, 2000);
									sheet.setColumnWidth(1, 4000);
									sheet.setColumnWidth(2, 6000);
									sheet.setColumnWidth(3, 6000);
									sheet.setColumnWidth(6, 5000);
									sheet.setColumnWidth(5, 5000);
									sheet.setColumnWidth(4, 4500);
								}
							}
						}

					}).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 25)).
					build();
			writeTable3 = EasyExcel.writerTable(3).
					head(headWone(searchVo)).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig() {
						@Override
						protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
							boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
							if (needSetWidth) {
								Sheet sheet = writeSheetHolder.getSheet();
								int columnIndex = cell.getColumnIndex();
								// 单元格文本长度大于45换行
								if (columnIndex == 4) {
									//要求将当前列的列宽设置为33英寸，理论值应该是33×256=8448，
									//但是这里的设值是8648，具体原因请看下面的计算逻辑
									sheet.setColumnWidth(0, 3000);
									sheet.setColumnWidth(1, 4000);
									sheet.setColumnWidth(2, 6000);
									sheet.setColumnWidth(3, 6000);
									sheet.setColumnWidth(6, 6000);
									sheet.setColumnWidth(5, 6000);
									sheet.setColumnWidth(4, 6000);
								}
							}
						}

					}).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			writeTable4 = EasyExcel.writerTable(4).
					head(headQThree(searchVo)).
					registerWriteHandler(customCellStyleStrategyFour).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 25)).
					build();
			writeTable5 = EasyExcel.writerTable(5).
					head(headQFour(searchVo)).
					registerWriteHandler(customCellStyleStrategyFour).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 25)).
					build();
			writeTable6 = EasyExcel.writerTable(6).
					head(headQFive()).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20)).
					build();
			writeTable7 = EasyExcel.writerTable(7).
					head(FundSix()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 40)).
					build();
			//派增的数据
			long count = getFCount(searchVo);
			if (count > CommonConstants.ZERO_INT) {
				list = getDispatchFundSupplementary(searchVo);
				if (Common.isNotNull(list)) {
					//判断list的大小是否大于10
					if (list.size() < 10) {
						int size = 10 - list.size();
						int num = list.size() + 1;
						for (int i = 1; i <= size; i++) {
							vo = new TDispatchFundSupplementaryExportVo();
							vo.setNum(num);
							num++;

							list.add(vo);
						}
					}
					writeSheet = EasyExcel.writerSheet(searchVo.getDisMonth()).build();
					// 第一次写入会创建头
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable2);
					excelWriter.write(list, writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable5);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable6);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable7);
				}
			} else {

				if (list.size() < 10) {
					int size = 10 - list.size();
					int num = list.size() + 1;
					for (int i = 1; i <= size; i++) {
						vo = new TDispatchFundSupplementaryExportVo();
						vo.setNum(num);
						num++;
						list.add(vo);
					}
				}
				writeSheet = EasyExcel.writerSheet(searchVo.getDisMonth()).build();
				// 第一次写入会创建头
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
				// 第二次写如也会创建头，然后在第一次的后面写入数据
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable2);
				excelWriter.write(list, writeSheet, writeTable3);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable5);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable6);
				excelWriter.write(new ArrayList<>(), writeSheet, writeTable7);
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headOne() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "合肥市基本医疗保险参保登记表";
		//第一列-第十三列
		for (int i = 1; i <= 13; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headTwo(String houseName, String cusNo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String b = "单位名称(盖章): " + houseName + "   单位统一信用代码:" + (null == cusNo ? " " : cusNo);
		String c = "人员类型： □√单位职工      □灵活就业人员";
		for (int i = 1; i <= 13; i++) {
			list.add(Lists.newArrayList(b, c));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headThree() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String d = "变更类别";
		//第一列
		list.add(Lists.newArrayList("序号", "序号"));
		//第二列
		list.add(Lists.newArrayList("姓名", "姓名"));
		//第三列
		list.add(Lists.newArrayList("身份证件类型", "身份证件类型"));
		//第四列
		list.add(Lists.newArrayList("身份证件号码", "身份证件号码"));
		//第五列
		list.add(Lists.newArrayList("参报/停保时间", "参报/停保时间"));
		//第六列
		list.add(Lists.newArrayList("申报工资（元）", "申报工资（元）"));
		//变更类别
		List<String> orderSpeaces = Lists.newArrayList("新增", "续保", "中断", "终止");
		orderSpeaces.forEach(e -> {
			list.add(Lists.newArrayList(d, e));
		});
		//第十一列
		list.add(Lists.newArrayList("手机号码", "手机号码"));
		//第十二列
		list.add(Lists.newArrayList("学历", "学历"));
		//第十三列
		list.add(Lists.newArrayList("备注", "备注"));
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headFour() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "备注： 1.身份证类型填写：身份证、护照、港澳台通行证等； \n" +
				"       2.增加人员勾选新增或续保，减少人员勾选中断或终止，按相应类型进行勾选；\n" +
				"       3.联系电话务必填写准确的手机号码；";
		//第一列-第十三列
		for (int i = 1; i <= 13; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headFive() {
		List<List<String>> list = new ArrayList<>();
		String b = "填报人：                 联系电话：                  经办人（盖章）：            " +
				DateUtil.getYear(DateUtil.getCurrentDateTime()) + " 年" + " " +
				DateUtil.getMonth(DateUtil.getCurrentDateTime()) + " 月" + " " +
				DateUtil.getDay(DateUtil.getCurrentDateTime()) + " 日";
		//第一列-第十三列
		for (int i = 1; i <= 13; i++) {
			list.add(Lists.newArrayList(b));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> persionHeadOne() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "职 工 社 会 保 险 增 加 花 名 册";
		//第一列-第十八列
		for (int i = 1; i <= 18; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> persionHeadTwo(String houseName, String cusNo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "单位名称(签章): " + houseName + "                        单位编码:" + (null == cusNo ? " " : cusNo);
		//第一列-第十八列
		for (int i = 1; i <= 18; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> persionHead() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String c = "参加保险险种";
		//第一列
		list.add(Lists.newArrayList("序号", "序号"));
		//第二列
		list.add(Lists.newArrayList("姓名", "姓名"));
		//第三列
		list.add(Lists.newArrayList("职工编码", "职工编码"));
		//第四列
		list.add(Lists.newArrayList("社会保障号码   （身份证号码）", "社会保障号码   （身份证号码）"));
		//第五列
		list.add(Lists.newArrayList("性别", "性别"));
		//第六列
		list.add(Lists.newArrayList("民族", "民族"));
		//第七列
		list.add(Lists.newArrayList("参加工作时间", "参加工作时间"));
		//第八列
		list.add(Lists.newArrayList("户口性质", "户口性质"));
		//第九列
		list.add(Lists.newArrayList("个人身份", "个人身份"));
		//参加保险险种
		List<String> orderSpeaces = Lists.newArrayList("养老", "失业", "医疗", "工伤", "生育");
		orderSpeaces.forEach(e -> {
			list.add(Lists.newArrayList(c, e));
		});
		//第十五列
		list.add(Lists.newArrayList("月工资收入(元)", "月工资收入(元)"));
		//第十六列
		list.add(Lists.newArrayList("补缴保险属期", "补缴保险属期"));
		//第十七列
		list.add(Lists.newArrayList("户籍所在地", "户籍所在地"));
		//第十八列
		list.add(Lists.newArrayList("备注", "备注"));
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 11:12 2023/7/21
	 */
	public List<List<String>> persionHeadThree() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "1、“户口性质”栏按下列类别填写：非农业户口（城镇）、本地非农业户口（本地城镇）、外地非农业户口（外地城镇）、农业户口（农村）、 \n" +
				"          本地农业户口（本地农村）、外地农业户口（外地农村）、港澳台、外籍 \n" +
				"2、“个人身份”栏按下列类别填写：“企业职工”、“国家公务员”、“事业单位在编人员”、“编外人员”、“现役军人”、“协保人员”、“公益性岗位”“农民工医保” \n" +
				"3、“参加保险险种”栏可对应选项打“√” \n" +
				"4、新增人员（含断保再次缴费人员），个人月工资收入按起薪工资额申报。\n" +
				"5、补缴时段超过3个月的，缴费基数为历年安徽省社平工资，同时加征利息(含参保当月的缴费基数)。\n" +
				"6、如属军队退役人员或劳模人员在备注栏中填写，“退役军人类别”栏按下列类别填写：军队转业干部、计划分配的军队转业干部、自主择业的军队转业干部、退伍复员军人、转业复员士官、退伍 \n" +
				"义务兵（含伤病残义务兵）、复员干部，“劳模级别”栏按下列类别填写：国家级、省（自治区、直辖市）级、部（委）级、地（市、厅、局）级、其他 \n" +
				"7、本表需填制一式两份，经办机构审核盖章后方可有效，一份单位自存，一份报市社会保险经办机构。";
		//第一列-第十八列
		for (int i = 1; i <= 18; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 11:12 2023/7/21
	 */
	public List<List<String>> persionHead1() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String b = "填表人：                   单位联系电话：                    社保经办机构审核人：                  " + "填报日期:  " + DateUtil.getYear(DateUtil.getCurrentDateTime()) + " 年" + " " + DateUtil.getMonth(DateUtil.getCurrentDateTime()) + " 月" + " " + DateUtil.getDay(DateUtil.getCurrentDateTime()) + " 日";
		//第一列-第十八列
		for (int i = 1; i <= 18; i++) {
			list.add(Lists.newArrayList(b));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> persionReduceHeadOne() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "社 会 保 险 缴 费 单 位 人 员 减 少 花 名 册";
		//第一列-第二十五列
		for (int i = 1; i <= 25; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> persionReduceHeadTwo(String houseName, String cusNo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "单位名称(签章): " + houseName + "                   单位编码:" + (null == cusNo ? " " : cusNo);
		//第一列-第二十五列cusNo
		for (int i = 1; i <= 25; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> persionReduceHead() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String c = "减少原因";
		//第一列
		list.add(Lists.newArrayList("序号", "序号"));
		//第二列
		list.add(Lists.newArrayList("职工编码", "职工编码"));
		//第三列
		list.add(Lists.newArrayList("姓名", "姓名"));
		//第四列
		list.add(Lists.newArrayList("社会保障号码   （身份证号码）", "社会保障号码   （身份证号码）"));
		//第五列
		list.add(Lists.newArrayList("停止缴费时间", "停止缴费时间"));
		//减少原因
		List<String> orderSpeaces = Lists.newArrayList("辞职", "辞退", "参军", "上学", "劳改", "劳教", "除名", "人员失踪", "停薪留职", "合同期满", "解除合同", "统筹内调出", "调出统筹范围", "退休", "死亡", "出国定居", "港澳台定居", "退保", "其他");
		orderSpeaces.forEach(e -> {
			list.add(Lists.newArrayList(c, e));
		});
		list.add(Lists.newArrayList("备注", "备注"));
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 11:12 2023/7/21
	 */
	public List<List<String>> persionReduceHead1() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "说明1、“减少原因”栏可对应选项打“√”； \n" +
				"2、本表需填制一式二份，经办机构审核盖章后方可有效，一份单位自存，一份报市社会保险经办机构。";
		String b = "填表人：              单位联系电话：                社保经办机构审核人：             " + "填报日期:  " + DateUtil.getYear(DateUtil.getCurrentDateTime()) + " 年" + " " + DateUtil.getMonth(DateUtil.getCurrentDateTime()) + " 月" + " " + DateUtil.getDay(DateUtil.getCurrentDateTime()) + " 日";
		//第一列-第十八列
		for (int i = 1; i <= 25; i++) {
			list.add(Lists.newArrayList(a, b));
		}
		return list;
	}


	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headFisrt() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "合肥市住房公积金变更清册";
		//第一列-第十三列
		for (int i = 1; i <= 8; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headSecond(String houseName, SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = null;
		if (houseName != null) {
			HouseNameConfigVo vo = getFundSumExportVoTwo(houseName, searchVo);
			if (vo == null) {
				a = "单位名称(签章): " + houseName + "                       单位公积金账号:" + "" + "                    单边缴纳比例:" + "";
			} else {

				if (vo.getCustomerNo() == null) {
					vo.setCustomerNo("");
				}
				if (vo.getCompanyPro() == null) {
					vo.setCompanyPro("");
				}
				a = "单位名称(签章): " + houseName + "         单位公积金账号:" + vo.getCustomerNo() + "      单边缴纳比例:" + vo.getCompanyPro() + "%";
			}
			//第一列-第十八列
			for (int i = 1; i <= 8; i++) {
				list.add(Lists.newArrayList(a));
			}
		}
		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headW() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String c = "月缴存金额";
		//第一列
		list.add(Lists.newArrayList("序号", "序号"));
		//第二列
		list.add(Lists.newArrayList("个人帐号", "个人帐号"));
		//第三列
		list.add(Lists.newArrayList("姓  名", "姓  名"));
		//第四列
		list.add(Lists.newArrayList("身份证号码", "身份证号码"));
		//第五列
		list.add(Lists.newArrayList("缴存基数", "缴存基数"));
		//第六列
		list.add(Lists.newArrayList("月缴存金额", "本月增加"));
		//第七列
		list.add(Lists.newArrayList("月缴存金额", "本月减少"));
		//第八列
		list.add(Lists.newArrayList("变更原因", "变更原因"));

		return list;
	}


	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQ(SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "";
		String b = " ";
		String c = "  ";
		String d = "   ";
		//第一列
		TDispatchFundSumExportVo dispatchFundSumExportVo = getFundSumExportVo(searchVo);
		if (Common.isNotNull(dispatchFundSumExportVo)) {
			if (dispatchFundSumExportVo.getNumOne() != null) {
				a = dispatchFundSumExportVo.getNumOne().toString();
			}
			if (dispatchFundSumExportVo.getNumTwo() != null) {
				b = dispatchFundSumExportVo.getNumTwo().toString();
			}
			if (dispatchFundSumExportVo.getMonenyOne() != null) {
				c = dispatchFundSumExportVo.getMonenyOne().toString();
			}
			if (dispatchFundSumExportVo.getMonenyTwo() != null) {
				d = dispatchFundSumExportVo.getMonenyTwo().toString();
			}

			if (dispatchFundSumExportVo.getNumOne() == 0) {
				a = "";

			}
			if (dispatchFundSumExportVo.getNumTwo() == 0) {
				b = " ";

			}
			if (dispatchFundSumExportVo.getMonenyOne() == null) {
				c = "";

			}
			if (dispatchFundSumExportVo.getMonenyTwo() == null) {
				d = " ";

			}

		}
		list.add(Lists.newArrayList("项目合计", "项目合计", "本月小计"));
		//第二列
		list.add(Lists.newArrayList("项目合计", "项目合计", "本月小计"));
		//第三列

		list.add(Lists.newArrayList("本月增加汇款", "人数", b));

		list.add(Lists.newArrayList("本月增加汇款", "金额", c));
		//第四列
		list.add(Lists.newArrayList("本月减少汇款", "人数", a));
		//第五列
		list.add(Lists.newArrayList("本月减少汇款", "金额", d));
		//第六列
		list.add(Lists.newArrayList("本月汇款", "人数", ""));
		//第七列
		list.add(Lists.newArrayList("本月汇款", "金额", " "));
		return list;
	}

	/**
	 * @return
	 * @Author huyc
	 * @Description 导出社保派单花名册
	 * @Date 11:12 2023/7/21
	 */
	public List<List<String>> FundHeadT() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String b = "制表人:                 电话:                   " + "制表时间:  " + DateUtil.getYear(DateUtil.getCurrentDateTime()) + " 年" + " " + DateUtil.getMonth(DateUtil.getCurrentDateTime()) + " 月" + " " + DateUtil.getDay(DateUtil.getCurrentDateTime()) + " 日";
		//第一列-第十八列
		for (int i = 1; i <= 8; i++) {
			list.add(Lists.newArrayList(b));
		}
		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出社保派单花名册
	 * @Date 11:12 2023/7/21
	 */
	public List<List<String>> FundHeadR() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		list.add(Lists.newArrayList("          备注", "          备注"));
		list.add(Lists.newArrayList("          备注", "          备注"));
		String a = "1.新增人员必须填写身份证号码。\n" +
				"2.本表只提供单位缴存人数变动使用。\n" +
				"3.对于工资基数调整及个人补缴业务不得使用此表。\n" +
				"4.单位封存人员启封时，如缴存基数发生变化须附基数调整清册\n" + "本单位承诺变更清册中所填内容均真实、合法、有效，如有不实之处，单位承担相应的法律责任及由此产生的一切后果。";
		for (int i = 2; i <= 7; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}


	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/19
	 */
	public List<List<String>> headFisrtOne() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String a = "合肥市住房公积金补缴申请书";
		//第一列-第十三列
		for (int i = 1; i <= 7; i++) {
			list.add(Lists.newArrayList(a));
		}
		return list;
	}


	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQOne(String houseName) {
		List<List<String>> list = new ArrayList<>();
		list.add(Lists.newArrayList("单位名称（公章）", "单位名称（公章）"));

		//第二列
		if (houseName == null) {
			houseName = "";

		}
		list.add(Lists.newArrayList(houseName, houseName));

		list.add(Lists.newArrayList(houseName, houseName));
		//第三列
		list.add(Lists.newArrayList("经 办 人", "电话"));

		list.add(Lists.newArrayList("经 办 人", "电话"));

		list.add(Lists.newArrayList("赵云", "63432400"));

		list.add(Lists.newArrayList("赵云", "63432400"));

		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQTwo(String houseName, SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		HouseNameConfigVo houseNameConfigVo = getFundSumExportVoTwo(houseName, searchVo);
		if (Common.isNotNull(houseNameConfigVo)) {
			if (houseNameConfigVo.getFundBank() == null) {
				houseNameConfigVo.setFundBank("");

			}
			if (houseNameConfigVo.getCustomerNo() == null) {
				houseNameConfigVo.setCustomerNo("");

			}
			String h = houseNameConfigVo.getCompanyPro() + "%";
			if (houseNameConfigVo.getCompanyPro() == null) {
				h = "";
			}

			list.add(Lists.newArrayList("公积金承办银行", "公积金承办银行"));
			list.add(Lists.newArrayList(houseNameConfigVo.getFundBank(), houseNameConfigVo.getFundBank()));
			list.add(Lists.newArrayList(houseNameConfigVo.getFundBank(), houseNameConfigVo.getFundBank()));
			//第二列
			//第三列
			list.add(Lists.newArrayList("单位公积金账号", "单边缴存比例"));

			list.add(Lists.newArrayList("单位公积金账号", "单边缴存比例"));


			list.add(Lists.newArrayList(houseNameConfigVo.getCustomerNo(), h));

			list.add(Lists.newArrayList(houseNameConfigVo.getCustomerNo(), h));
		} else {

			list.add(Lists.newArrayList("公积金承办银行", "公积金承办银行"));
			list.add(Lists.newArrayList("", ""));
			list.add(Lists.newArrayList("", ""));
			//第二列
			//第三列
			list.add(Lists.newArrayList("单位公积金账号", "单边缴存比例"));

			list.add(Lists.newArrayList("单位公积金账号", "单边缴存比例"));


			list.add(Lists.newArrayList("", " "));

			list.add(Lists.newArrayList("", " "));

		}

		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headWone(SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		String c = "补缴时间";
		//第一列
		list.add(Lists.newArrayList("序号", "序号"));
		//第二列
		list.add(Lists.newArrayList("个人帐号", "个人帐号"));
		//第三列
		list.add(Lists.newArrayList("姓  名", "姓  名"));
		//第四列

		//第五列
		list.add(Lists.newArrayList("缴存基数", "缴存基数"));
		//第六列
		list.add(Lists.newArrayList("补缴金额", "补缴金额"));
		//第七列
		list.add(Lists.newArrayList("补缴时间", "起始（年月日）"));

		list.add(Lists.newArrayList("补缴时间", "截至（年月日）"));
		//第八列


		return list;
	}

	private String int2big(int b) {
		final String num[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
		final String unit[] = {"圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
		String dst = "";
		int count = 0;
		while (b > 0) {
			dst = (num[b % 10] + unit[count]) + dst;
			b = b / 10;
			count++;
		}
		return dst.replaceAll("零[仟佰拾]", "零").replaceAll("零+万", "万")
				.replaceAll("零+亿", "亿").replaceAll("亿万", "亿零")
				.replaceAll("零+", "零").replaceAll("零圆", "圆");
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQThree(SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		//第一列
		String a = "";
		HouseNameConfigVo houseNameConfigVo = getFundSumExportVoTwo(searchVo.getProvidentHouseholdName(), searchVo);
		if (houseNameConfigVo != null) {

			TDispatchFundSumVo tDispatchFundSumVo = getFundSumVo(searchVo);
			if (tDispatchFundSumVo != null) {
				if (tDispatchFundSumVo.getSupplementaryAmountSum() != null) {
					a = tDispatchFundSumVo.getSupplementaryAmountSum().toString();
				} else {
					a = "0";

				}
			}
		} else {
			a = "0";
		}
		list.add(Lists.newArrayList("", ""));
		//第二列

		list.add(Lists.newArrayList("", ""));
		list.add(Lists.newArrayList("合计补缴金额（大写）：", "合计补缴金额（大写）："));
		//第三列
		//第四列
		int b = Double.valueOf(a).intValue();
		String c = int2big(b);
		//第五列
		list.add(Lists.newArrayList(c, c));
		list.add(Lists.newArrayList(c, c));
		list.add(Lists.newArrayList(c, c));
		list.add(Lists.newArrayList(c, c));

		//第八列


		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQFour(SocialHandleSearchVo searchVo) {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		//第一列

		TDispatchFundSumVo dispatchFundSumVo = getFundSumVo(searchVo);
		String F = dispatchFundSumVo.getNumber();
		list.add(Lists.newArrayList("         单位申请\n" + "         补缴意见"));

		list.add(Lists.newArrayList("         单位申请\n" + "         补缴意见"));

		//第二列
		list.add(Lists.newArrayList("", "", "", "", "", "         负责人：", "           年    月    日"));

		list.add(Lists.newArrayList("", "", "", "", "", "         负责人：", "           年    月    日"));
		//第三列

		list.add(Lists.newArrayList("        补缴合计", "        补缴合计", "        补缴合计", "        补缴原因", "        补缴原因", "        补缴原因"));
		if (dispatchFundSumVo.getNumber() == null) {
			dispatchFundSumVo.setNumber("0");
		}
		if (dispatchFundSumVo.getSupplementaryAmountSum() == null) {
			dispatchFundSumVo.setSupplementaryAmountSum(BigDecimal.ZERO);
		}
		list.add(Lists.newArrayList("此次申请补缴共有" + dispatchFundSumVo.getNumber() + "人", "补缴总额" + dispatchFundSumVo.getSupplementaryAmountSum().toString() + "元", ""));
		list.add(Lists.newArrayList("此次申请补缴共有" + dispatchFundSumVo.getNumber() + "人", "补缴总额" + dispatchFundSumVo.getSupplementaryAmountSum().toString() + "元", ""));
		//第四列


		//第八列


		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> headQFive() {
		List<List<String>> list = new ArrayList<>();
		//表头数据
		//第一列

		list.add(Lists.newArrayList("市住房公积金管理中\n" + "心审核意见"));


		list.add(Lists.newArrayList("市住房公积金管理中\n" + "心审核意见"));


		//第二列
		list.add(Lists.newArrayList("", "", "", "", "", "审批人：", "      年    月    日"));
		list.add(Lists.newArrayList("", "", "", "", "", "审批人：", "      年    月    日"));

		//第三列


		list.add(Lists.newArrayList("承办银行\n" + "审核意见"));
		list.add(Lists.newArrayList("", "", "", "", "", "审批人:", "      年    月    日"));
		list.add(Lists.newArrayList("", "", "", "", "", "审批人:", "      年    月    日"));

		//第四列


		//第八列


		return list;
	}

	/**
	 * @return
	 * @Author wzb
	 * @Description 导出公积金派单花名册
	 * @Date 09:05 2023/7/21
	 */
	public List<List<String>> FundSix() {
		List<List<String>> list = new ArrayList<>();
		//表头数据

		String b = "网址：www.hfgjj.com               咨询电话：0551-12329";
		//第一列-第十八列
		for (int i = 1; i <= 7; i++) {
			list.add(Lists.newArrayList(b));
		}
		return list;
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 查询当月已经审核通过的未办理完成的社保或医保 增减信息
	 * @Date 15:58 2024/12/10
	 * @Param socialId：社保明细ID type：  1 社保增  2社保减  3 医保增 4 医保减 unitCreditCode：单位统一信用代码
	 **/
	@Override
	public R<URL> doExportRoster(String socialId, String type, String unitCreditCode) {
		SocialHandleSearchVo searchVo = new SocialHandleSearchVo();
		if (Common.isEmpty(socialId) || Common.isEmpty(type) || Common.isEmpty(unitCreditCode)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		TSocialInfo socialInfo = socialMapper.selectById(socialId);
		if (Common.isEmpty(socialInfo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR + "：未获取到社保明细信息");
		}
		//查询户名称对应的户配置 以获取公章信息
		SysHouseHoldInfo holdInfo = houseHoldInfoMapper.selectOne(Wrappers.<SysHouseHoldInfo>query().lambda()
				.eq(SysHouseHoldInfo::getName, socialInfo.getSocialHouseholdName())
				.eq(SysHouseHoldInfo::getType, 0)
				.eq(SysHouseHoldInfo::getDelFlag, 0)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(holdInfo)) {
			return R.failed(CommonConstants.RESULT_DATA_FAIL + ":获取户配置信息失败");
		}
		TAttaInfo att = attaInfoMapper.selectOne(Wrappers.<TAttaInfo>query().lambda()
				.eq(TAttaInfo::getDomainId, holdInfo.getId()).last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(att)) {
			return R.failed(CommonConstants.RESULT_DATA_FAIL + ":获取电子印章信息失败");
		}
		searchVo.setSocialHouseholdName(socialInfo.getSocialHouseholdName());
		searchVo.setDisMonth(DateUtil.getThisMonth());
		searchVo.setSyFlag(CommonConstants.ONE_STRING);
		//税友特殊处理标识

		searchVo.setSocialId(socialId);
		String fileName = DispatchConstants.SOCIAL_MEDICAL_EXPORT + searchVo.getSocialHouseholdName() + "_" + socialId + CommonConstants.XLS;
		String projectRoot = System.getProperty(CommonConstants.USER_DIR);
		String filePath = projectRoot + CommonConstants.DOUBLE_LINE + fileName;
		//社保增减
		if (CommonConstants.ONE_STRING.equals(type) || CommonConstants.TWO_STRING.equals(type)) {
			return doExportRosterSocial(searchVo, type, fileName, projectRoot, filePath, att.getAttaSrc(), unitCreditCode);
		}
		//医保增减
		if (CommonConstants.THREE_STRING.equals(type) || CommonConstants.FOUR_STRING.equals(type)) {
			return doExportRosterMedical(searchVo, type, fileName, projectRoot, filePath, att.getAttaSrc(), unitCreditCode);
		}
		return null;
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 医保增加花名册
	 * @Date 16:29 2024/12/10
	 * @Param
	 **/
	public R<URL> doExportRosterMedical(SocialHandleSearchVo searchVo,
										String type,
										String fileName,
										String projectRoot,
										String filePath,
										String src,
										String unitCreditCode) {

		//获取要导出的列表
		List<TDispatchSocialExportVo> list = new ArrayList<>();
		File createFile = null;
		ExcelWriter excelWriter = null;
		try {
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			createFile = new File(filePath);
			excelWriter = EasyExcel.write(createFile).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			TDispatchSocialExportVo vo;

			List<Integer> columnIndexes = Arrays.asList(0, 12);
			CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
			CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
			CustomCellStyleTwoStrategy customCellStyleStrategyTwo = new CustomCellStyleTwoStrategy(columnIndexes);
			CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);

			writeTable0 = EasyExcel.writerTable(0).
					head(headOne()).
					registerWriteHandler(customCellStyleStrategy).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
					build();
			writeTable1 = EasyExcel.writerTable(1).
					head(headTwo(searchVo.getSocialHouseholdName(), unitCreditCode)).
					registerWriteHandler(customCellStyleStrategyOne).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20)).
					build();
			writeTable2 = EasyExcel.writerTable(2).
					head(headThree()).
					registerWriteHandler(customCellStyleStrategyThree).
					registerWriteHandler(new CustomCellWriteWidthConfig()).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			writeTable3 = EasyExcel.writerTable(3).
					head(headFour()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 50, (short) 20))
					.build();
			writeTable4 = EasyExcel.writerTable(4).
					head(headFive()).
					registerWriteHandler(customCellStyleStrategyTwo).
					registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 20))
					.build();
			//派增的数据--医保增员
			if (CommonConstants.THREE_STRING.equals(type)) {
				searchVo.setType(CommonConstants.ZERO_STRING);
				long count = getSocialDisRecordCount(searchVo);
				if (count > CommonConstants.ZERO_INT) {
					list = getSocialDisRecord(searchVo);
					if (Common.isNotNull(list)) {
						//判断list的大小是否大于10
						if (list.size() < 10) {
							int size = 10 - list.size();
							int num = list.size() + 1;
							for (int i = 1; i <= size; i++) {
								vo = new TDispatchSocialExportVo();
								vo.setNum(num);
								num++;
								list.add(vo);
							}
						}
						writeSheet = EasyExcel.writerSheet("增员").build();
						// 第一次写入会创建头
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
						// 第二次写如也会创建头，然后在第一次的后面写入数据
						excelWriter.write(list, writeSheet, writeTable2);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
					}
				} else {
					writeSheet = EasyExcel.writerSheet("增员").build();
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					int num = 1;
					for (int i = 1; i <= 10; i++) {
						vo = new TDispatchSocialExportVo();
						vo.setNum(num);
						num++;
						list.add(vo);
					}
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			} else if (CommonConstants.FOUR_STRING.equals(type)) {
				//派减的数据--医保减员
				searchVo.setType(CommonConstants.ONE_STRING);
				long count1 = getSocialDisRecordCount(searchVo);
				if (count1 > CommonConstants.ZERO_INT) {
					list = baseMapper.getSocialReduceDisRecord(searchVo);
					if (Common.isNotNull(list)) {
						//判断list的大小是否大于10
						if (list.size() < 10) {
							int size = 10 - list.size();
							int num = list.size() + 1;
							for (int i = 1; i <= size; i++) {
								vo = new TDispatchSocialExportVo();
								vo.setNum(num);
								num++;
								list.add(vo);
							}
						}
						writeSheet = EasyExcel.writerSheet("减员").build();
						// 第一次写入会创建头
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
						// 第二次写如也会创建头，然后在第一次的后面写入数据
						excelWriter.write(list, writeSheet, writeTable2);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
					}
				} else {
					writeSheet = EasyExcel.writerSheet("减员").build();
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					// 第二次写如也会创建头，然后在第一次的后面写入数据
					int num = 1;
					list = new ArrayList<>();
					for (int i = 1; i <= 10; i++) {
						vo = new TDispatchSocialExportVo();
						vo.setNum(num);
						num++;
						list.add(vo);
					}
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
			File outFile = null;
			File inputFile = null;
			File tempFile = null;
			FileInputStream inputStream = null;
			FileOutputStream fileOUt = null;
			InputStream inStream = null;
			FileInputStream inputStreamOut = null;
			try {

				//读取文件 生成电子章
				inputFile = new File(filePath);
				inputStream = new FileInputStream(inputFile);
				String tempPath = projectRoot + "//temp_" + fileName;
				tempFile = new File(tempPath);
				fileOUt = new FileOutputStream(tempFile);
				URL url = ossUtil.getObjectUrl(null, src);
				if (Common.isEmpty(url)) {
					return R.failed(CommonConstants.RESULT_DATA_FAIL + ":电子印章OSS获取URL异常");
				}
				inStream = url.openStream();
				if (Common.isEmpty(inStream)) {
					return R.failed(CommonConstants.RESULT_DATA_FAIL + ":电子印章OSS获取流异常");
				}
				// 添加电子章 完成后关闭所有流
				excelMergeImage.addPictureToExcel(inputStream, inStream, fileOUt, 0, type);
				outFile = new File(tempPath);
				inputStreamOut = new FileInputStream(outFile);
				// 转换成图片 完成后清理流
				return excelToImage.excelToImg(inputStreamOut, ossUtil);
			} catch (Exception e) {
				return R.failed("税友附件生成异常：" + e.getMessage());
			} finally {
				// 清理文件
				finallyClose(inputFile, tempFile, outFile, inputStream, fileOUt, inStream, inputStreamOut);
			}
		} catch (Exception e) {
			if (excelWriter != null) {
				excelWriter.finish();
			}
			log.error("税友附件生成异常", e);
			return R.failed("税友附件生成异常：" + e.getMessage());
		} finally {
			if (null != createFile && createFile.exists()) {
				createFile.delete();
			}
			if (null != list) {
				list.clear();
			}
		}
	}

	private void finallyClose(File inputFile,
							  File tempFile,
							  File outFile,
							  FileInputStream inputStream,
							  FileOutputStream fileOUt,
							  InputStream inStream,
							  FileInputStream inputStreamOut) throws IOException {
		if (inputFile.exists()) {
			inputFile.delete();
		}
		if (tempFile.exists()) {
			tempFile.delete();
		}
		if (outFile.exists()) {
			outFile.delete();
		}
		if (null != inputStream) {
			inputStream.close();
		}
		if (null != fileOUt) {
			fileOUt.close();
		}
		if (null != inStream) {
			inStream.close();
		}
		if (null != inputStreamOut) {
			inputStreamOut.close();
		}
	}

	/**
	 * @return
	 * @Author fxj
	 * @Description 社保增减花名册
	 * @Date 16:28 2024/12/10
	 * @Param
	 **/
	public R<URL> doExportRosterSocial(SocialHandleSearchVo searchVo,
									   String type,
									   String fileName,
									   String projectRoot,
									   String filePath,
									   String src,
									   String unitCreditCode) {
		//获取要导出的列表
		List<TDispatchSocialPersionExportVo> list = new ArrayList<>();
		ExcelWriter excelWriter = null;
		File createFile = null;
		try {
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			createFile = new File(filePath);
			excelWriter = EasyExcel.write(createFile).build();
			WriteSheet writeSheet;
			WriteTable writeTable0;
			WriteTable writeTable1;
			WriteTable writeTable2;
			WriteTable writeTable3;
			WriteTable writeTable4;
			TDispatchSocialPersionExportVo vo;
			TDispatchSocialPersionReduceExportVo reduceVo;
			if (CommonConstants.ONE_STRING.equals(type)) {
				//派增的数据--社保
				searchVo.setType(CommonConstants.ZERO_STRING);
				long count = getSocialPersionDisCount(searchVo);
				List<Integer> columnIndexes = Arrays.asList(0, 17);
				CustomCellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(columnIndexes);
				CustomCellStyleOneStrategy customCellStyleStrategyOne = new CustomCellStyleOneStrategy(columnIndexes);
				CustomCellStyleTwoStrategy customCellStyleStrategyTwo = new CustomCellStyleTwoStrategy(columnIndexes);
				CustomCellStyleThreeStrategy customCellStyleStrategyThree = new CustomCellStyleThreeStrategy(columnIndexes);

				writeTable0 = EasyExcel.writerTable(0).
						head(persionHeadOne()).
						registerWriteHandler(customCellStyleStrategy).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
						build();
				writeTable1 = EasyExcel.writerTable(1).
						head(persionHeadTwo(searchVo.getSocialHouseholdName(), unitCreditCode)).
						registerWriteHandler(customCellStyleStrategyOne).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20)).
						build();
				writeTable2 = EasyExcel.writerTable(2).
						head(persionHead()).
						registerWriteHandler(customCellStyleStrategyThree).
						registerWriteHandler(new CustomCellWriteWidthOneConfig()).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 30, (short) 20))
						.build();
				writeTable3 = EasyExcel.writerTable(3).
						head(persionHeadThree()).
						registerWriteHandler(customCellStyleStrategyTwo).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 150, (short) 20))
						.build();
				writeTable4 = EasyExcel.writerTable(4).
						head(persionHead1()).
						registerWriteHandler(customCellStyleStrategyTwo).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20))
						.build();
				if (count > CommonConstants.ZERO_INT) {
					list = getSocialPersionDisRecord(searchVo);
					if (Common.isNotNull(list)) {
						//判断list的大小是否大于10
						if (list.size() < 10) {
							int size = 10 - list.size();
							int num = list.size() + 1;
							for (int i = 1; i <= size; i++) {
								vo = new TDispatchSocialPersionExportVo();
								vo.setNum(num);
								num++;
								list.add(vo);
							}
						}
						writeSheet = EasyExcel.writerSheet("增员").build();
						// 第一次写入会创建头
						// 第二次写如也会创建头，然后在第一次的后面写入数据
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
						excelWriter.write(list, writeSheet, writeTable2);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
					}
				} else {
					writeSheet = EasyExcel.writerSheet("增员").build();
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					int num = 1;
					for (int i = 1; i <= 10; i++) {
						vo = new TDispatchSocialPersionExportVo();
						vo.setNum(num);
						num++;
						list.add(vo);
					}
					excelWriter.write(list, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable4);
				}
			} else if (CommonConstants.TWO_STRING.equals(type)) {
				//派减的数据--社保
				searchVo.setType(CommonConstants.ONE_STRING);
				long count1 = getSocialPersionReduceDisCount(searchVo);
				//获取要导出的列表
				List<TDispatchSocialPersionReduceExportVo> listReduce = new ArrayList<>();

				List<Integer> columnIndex = Arrays.asList(0, 24);
				CustomCellStyleStrategy customCellStyleStrategy1 = new CustomCellStyleStrategy(columnIndex);
				CustomCellStyleOneStrategy customCellStyleStrategy2 = new CustomCellStyleOneStrategy(columnIndex);
				CustomCellStyleTwoStrategy customCellStyleStrategy3 = new CustomCellStyleTwoStrategy(columnIndex);
				CustomCellStyleThreeStrategy customCellStyleStrategy4 = new CustomCellStyleThreeStrategy(columnIndex);

				writeTable0 = EasyExcel.writerTable(0).
						head(persionReduceHeadOne()).
						registerWriteHandler(customCellStyleStrategy1).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20)).
						build();
				writeTable1 = EasyExcel.writerTable(1).
						head(persionReduceHeadTwo(searchVo.getSocialHouseholdName(), unitCreditCode)).
						registerWriteHandler(customCellStyleStrategy2).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 20, (short) 20)).
						build();
				writeTable2 = EasyExcel.writerTable(2).
						head(persionReduceHead()).
						registerWriteHandler(customCellStyleStrategy4).
						registerWriteHandler(new CustomCellWriteWidthTwoConfig()).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 50, (short) 20))
						.build();
				writeTable3 = EasyExcel.writerTable(3).
						head(persionReduceHead1()).
						registerWriteHandler(customCellStyleStrategy3).
						registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 40, (short) 20))
						.build();
				if (count1 > CommonConstants.ZERO_INT) {
					listReduce = getSocialPersionReduceDisRecord(searchVo);
					if (Common.isNotNull(listReduce)) {
						//判断list的大小是否大于10
						if (listReduce.size() < 10) {
							int size = 10 - listReduce.size();
							int num = listReduce.size() + 1;
							for (int i = 1; i <= size; i++) {
								reduceVo = new TDispatchSocialPersionReduceExportVo();
								reduceVo.setNum(num);
								num++;
								listReduce.add(reduceVo);
							}
						}
						writeSheet = EasyExcel.writerSheet("减员").build();
						// 第一次写入会创建头
						// 第二次写如也会创建头，然后在第一次的后面写入数据
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
						excelWriter.write(listReduce, writeSheet, writeTable2);
						excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
					}
				} else {
					writeSheet = EasyExcel.writerSheet("减员").build();
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable0);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable1);
					int num = 1;
					for (int i = 1; i <= 10; i++) {
						reduceVo = new TDispatchSocialPersionReduceExportVo();
						reduceVo.setNum(num);
						num++;
						listReduce.add(reduceVo);
					}
					excelWriter.write(listReduce, writeSheet, writeTable2);
					excelWriter.write(new ArrayList<>(), writeSheet, writeTable3);
				}
				if (Common.isNotNull(listReduce)) {
					listReduce.clear();
				}
			}
			if (excelWriter != null) {
				excelWriter.finish();
			}
			File inputFile = null;
			File tempFile = null;
			File outFile = null;
			FileInputStream inputStream = null;
			FileOutputStream fileOUt = null;
			InputStream inStream = null;
			FileInputStream inputStreamOut = null;
			try {
				//读取文件 生成电子章
				inputFile = new File(filePath);
				inputStream = new FileInputStream(inputFile);
				String tempPath = projectRoot + "//temp_" + fileName;
				tempFile = new File(tempPath);
				fileOUt = new FileOutputStream(tempFile);
				URL url = ossUtil.getObjectUrl(null, src);
				if (Common.isEmpty(url)) {
					return R.failed(CommonConstants.RESULT_DATA_FAIL + ":电子印章OSS获取URL异常");
				}
				inStream = url.openStream();
				if (Common.isEmpty(inStream)) {
					return R.failed(CommonConstants.RESULT_DATA_FAIL + ":电子印章OSS获取流异常");
				}
				// 添加电子章 完成后关闭所有流
				excelMergeImage.addPictureToExcel(inputStream, inStream, fileOUt, 0, type);
				outFile = new File(tempPath);
				inputStreamOut = new FileInputStream(outFile);
				// 转换成图片 完成后清理流
				return excelToImage.excelToImg(inputStreamOut, ossUtil);
			} catch (Exception e) {
				return R.failed("税友附件生成异常：" + e.getMessage());
			} finally {
				// 清理文件
				finallyClose(inputFile, tempFile, outFile, inputStream, fileOUt, inStream, inputStreamOut);
			}
		} catch (Exception e) {
			if (excelWriter != null) {
				excelWriter.finish();
			}
			log.error("税友附件生成异常", e);
			return R.failed("税友附件生成异常：" + e.getMessage());
		} finally {
			finallyClear(list, createFile);
		}
	}

	private void finallyClear(List<TDispatchSocialPersionExportVo> list, File createFile) {
		if (null != createFile && createFile.exists()) {
			createFile.delete();
		}
		if (null != list) {
			list.clear();
		}
	}
	// 自定义错误响应方法
	public void sendErrorResponse(HttpServletResponse response,String msg) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		JsonObject json = new JsonObject();
		json.addProperty("success", false);
		json.addProperty("message",msg );
		PrintWriter out = response.getWriter();
		out.print(json.toString());
		out.flush();
	}
	/**
	 * @Author fxj
	 * @Description 下载自动化办理反馈文件  目前只有办理成功 增员 的有反馈照片，减员或办理失败的增员没有反馈照片
	 * @Date 15:23 2025/7/15
	 **/
	@Override
	public void doExportSocialSoldierAllBackFile(HttpServletResponse response, SocialHandleSearchVo searchVo, String idStr) {
		try {
			List<SocialSoldierBackVo> list = null;
			if (!Common.isEmpty(idStr)) {
				list = baseMapper.getSocialSoldierAllListBackFile(searchVo, Common.getList(idStr));
			}
			// 收集所有需要下载的 URL
			Map<String, FeedBackUrlVo> urlMap = new HashMap<>();
			Map<String, SocialSoldierBackVo> socialMap = new HashMap<>();
			if (!CollectionUtils.isEmpty(list)) {
				// 获取社保户信息
				List<SysHouseHoldInfo> zhangList = houseHoldInfoMapper.getHouseInfoAutoDoc();
				Map<String, SysHouseHoldInfo> holdInfoMap = zhangList.stream()
						.collect(Collectors.toMap(SysHouseHoldInfo::getName, info -> info, (existing, replacement) -> existing));

				socialMap = list.stream()
						.collect(Collectors.toMap(SocialSoldierBackVo::getSocialId, vo -> vo, (existing, replacement) -> existing));

				HashMap<String,String> requestIdMap = new HashMap<>();
				// 获取URL前先获取下载反馈的requestId
				for (SocialSoldierBackVo item : list) {
					//查询到24内有处理中或请求成功的数据直接用历史数据区请求
					if (StringUtils.isNotBlank(item.getRequestId())){
						requestIdMap.put(item.getSocialId(),item.getRequestId());
						continue;
					}
					String householdName = item.getSocialHouseholdName();
					if (StringUtils.isNotBlank(householdName)) {
						SysHouseHoldInfo holdInfo = holdInfoMap.get(householdName);
						if (holdInfo != null) {
							requestIdMap.putAll(socialFriendConfig.getDownloadEmployeeAsync(restTemplate, holdInfo, item));
						}
					}
				}
				// 通过requestIdMap 获取反馈的URL  因为对方是异步请求
				if (CollectionUtils.isNotEmpty(requestIdMap)) {
					// 循环 requestIdMap
					List<String> urls;
					//请求反馈日志
					List<TSocialFriendBackLog> backLogList = new ArrayList<>();
					FeedBackUrlVo backUrlVo = null;
					for (Map.Entry<String, String> entry : requestIdMap.entrySet()){
						backUrlVo =socialFriendConfig.getDownloadFeedbackUrls(restTemplate,entry.getValue(),backLogList,entry.getKey());
						if (Common.isNotNull(backUrlVo)){
							urlMap.put(entry.getKey(), backUrlVo);
						}
					}
					// 记录反馈文件下载失败信息
					if (Common.isNotNull(backLogList)){
						socialFriendBackLogService.saveOrUpdateBatch(backLogList);
					}
				}
				if (CollectionUtils.isEmpty(urlMap)){
					sendErrorResponse(response,"无附件可下载");
					return;
				}
				// 更新反馈文件状态
				updateBackFileFlage(socialMap, urlMap);
			}else {
				sendErrorResponse(response,"无附件可下载");
				return;
			}
			// 设置响应头
			response.setContentType("application/zip");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +
					URLEncoder.encode("下载自动化办理反馈文件", "UTF-8") + ".zip");

			// 下载并打包 ZIP
			try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(response.getOutputStream());
				 CloseableHttpClient httpClient = HttpClients.createDefault()) {
				SocialSoldierBackVo socialVo;
				List<String> urlList;
				HttpGet httpGet;
				FeedBackUrlVo backUrlVo = null;
				for (Map.Entry<String, FeedBackUrlVo> entry : urlMap.entrySet()) {
					String socialId = entry.getKey();
					backUrlVo = entry.getValue();
					if (null == backUrlVo)continue;
					urlList = backUrlVo.getUrls();

					if (CollectionUtils.isEmpty(urlList)) continue;
					socialVo = socialMap.get(socialId);
					for (int i = 0; i < urlList.size(); i++) {
						String url = urlList.get(i);
						try {
							httpGet = new HttpGet(url);
							try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
								HttpEntity entity = httpResponse.getEntity();
								if (entity == null) continue;

								byte[] data = EntityUtils.toByteArray(entity);
								String entryName =socialId;
								if (null != socialVo){
									if (i==0){
										entryName = generateFileName(url, socialVo.getEmpName() + "_" + socialVo.getEmpIdcard() + "_社保");
									}else {
										entryName = generateFileName(url, socialVo.getEmpName() + "_" + socialVo.getEmpIdcard() + "_社保"  + "_" + (i + 1));
									}

								}
								ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
								zipOutput.putArchiveEntry(zipEntry);
								zipOutput.write(data);
								zipOutput.closeArchiveEntry();
							}
						} catch (Exception e) {
							log.error("下载附件失败: {}", url, e);
							throw new RuntimeException("下载附件失败:", e);
						}
					}
				}
				zipOutput.finish();

			} catch (IOException e) {
				log.error("压缩文件流异常", e);
				throw new RuntimeException("压缩文件失败", e);
			}

		} catch (Exception e) {
			log.error("下载自动化办理反馈文件异常", e);
			throw new RuntimeException("下载自动化办理反馈文件失败，请联系管理员", e);
		}
	}

	private void updateBackFileFlage(Map<String, SocialSoldierBackVo> socialMap, Map<String, FeedBackUrlVo> urlMap) {
		if (null != urlMap && !urlMap.isEmpty()){
			SocialSoldierBackVo socialVo;
			List<String> dispatchIds = new ArrayList<>();
			FeedBackUrlVo backUrlVo = null;
			for (Map.Entry<String, FeedBackUrlVo> entry : urlMap.entrySet()) {
				String socialId = entry.getKey();
				socialVo = socialMap.get(socialId);
				backUrlVo = entry.getValue();
				if (null != socialVo && null != backUrlVo && !backUrlVo.getUrls().isEmpty()) {
					dispatchIds.add(socialVo.getDispatchId());
				}
			}
			if (null != dispatchIds && !dispatchIds.isEmpty()){
				baseMapper.updateBackFileFlag(dispatchIds);
			}
		}
	}
	/**
	 * 生成文件名：自定义名称 + 原始扩展名
	 */
	private String generateFileName(String ossUrl, String customName) {
		try {
			// 从URL路径中提取原始文件名
			String path = new URI(ossUrl).getPath();
			if (path == null) return customName;

			// 获取最后一个斜杠后的文件名
			int lastSlashIndex = path.lastIndexOf('/');
			String originalFileName = lastSlashIndex >= 0
					? path.substring(lastSlashIndex + 1)
					: path;

			// 提取扩展名
			int dotIndex = originalFileName.lastIndexOf('.');
			if (dotIndex > 0) {
				String extension = originalFileName.substring(dotIndex);
				return customName + extension;
			}
		} catch (Exception e) {
			// 解析失败时返回自定义名称
			log.error("解析文件名异常", e);
		}
		return customName;
	}

	@Override
	public R<String> doExportSocialSoldierBackFileById(String idStr) {
		List<SocialSoldierBackVo> list = null;
		if (!Common.isEmpty(idStr)) {
			list = baseMapper.getSocialSoldierAllListBackFile(null, Common.getList(idStr));
		}
		// 收集所有需要下载的 URL
		if (!CollectionUtils.isEmpty(list)) {
			// 获取社保户信息
			List<SysHouseHoldInfo> zhangList = houseHoldInfoMapper.getHouseInfoAutoDoc();
			Map<String, SysHouseHoldInfo> holdInfoMap = zhangList.stream()
					.collect(Collectors.toMap(SysHouseHoldInfo::getName, info -> info, (existing, replacement) -> existing));
			HashMap<String,String> requestIdMap = new HashMap<>();
			// 获取URL前先获取下载反馈的requestId
			for (SocialSoldierBackVo item : list) {
				//查询到24内有处理中或请求成功的数据直接用历史数据区请求
				if (StringUtils.isNotBlank(item.getRequestId())){
					requestIdMap.put(item.getSocialId(),item.getRequestId());
					continue;
				}
				String householdName = item.getSocialHouseholdName();
				if (StringUtils.isNotBlank(householdName)) {
					SysHouseHoldInfo holdInfo = holdInfoMap.get(householdName);
					if (holdInfo != null) {
						requestIdMap.putAll(socialFriendConfig.getDownloadEmployeeAsync(restTemplate, holdInfo, item));
					}
				}
			}
			// 通过requestId 获取反馈的URL  因为对方是异步请求
			List<String> urls = null;
			//请求反馈日志
			List<TSocialFriendBackLog> backLogList = new ArrayList<>();
			FeedBackUrlVo backUrlVo = null;
			if (CollectionUtils.isNotEmpty(requestIdMap)) {
				backUrlVo = socialFriendConfig.getDownloadFeedbackUrls(restTemplate,requestIdMap.get(list.get(0).getSocialId()),backLogList,list.get(0).getSocialId());
				urls = null==backUrlVo?null:backUrlVo.getUrls();
			}
			// 记录反馈文件下载失败信息
			if (Common.isNotNull(backLogList)){
				socialFriendBackLogService.saveOrUpdateBatch(backLogList);
			}
			if (Common.isNotNull(urls)){
				// 更新反馈文件状态
				List<String> dispatchIds = new ArrayList<>();
				dispatchIds.add(list.get(0).getDispatchId());
				baseMapper.updateBackFileFlag(dispatchIds);
				return R.ok(urls.get(0));
			}
			if (Common.isNotNull(backUrlVo) && Common.isNotNull(backUrlVo.getMsg())){
				return R.failed("下载失败："+backUrlVo.getMsg() +" (requestId:"+backUrlVo.getRequestId()+")");
			}
		}
		return R.failed("未找到反馈文件");
	}

	//发送企业微信待办
	private void sendDisFalureMessageToWx(TDispatchInfoPre pre,String id) {
		String code = "68";
		String item = "社保";
		if (CommonConstants.ONE_STRING.equals(pre.getTypeSub())){
			code = "75";
			item = "公积金";
		}
		//获取前端客服
		SysUser user;
		if (Common.isEmpty(pre.getCustomerUserLoginName())) {
			return;
		}
		R<SysUser> res = upmsDaprUtils.getSimpleUserByLoginName(pre.getCustomerUserLoginName());
		if (Common.isNotNull(res) && Common.isNotNull(res.getData())) {
			user = res.getData();
		} else {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(user.getWxMessage())) {
			sendUser = new StringBuilder(user.getWxMessage());
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			String authUrl = String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid()
					, wxConfig.getDomainName() + "/auth/oauth/wxLogin", code + id);
			StringBuilder description = new StringBuilder();
			String title = "作业自动化——"+item+"办理失败提醒";
			description.append(pre.getEmpName()).append("-").append(pre.getEmpIdcard()).append("-")
					.append(pre.getPhone()).append("，"+item+"派单审核/办理失败").append("<br>");
			description.append("请及时处理，以免产生用工风险！").append("<br>");
			textcard.put("title", title);
			textcard.put("url", authUrl);
			textcard.put("description", description.toString());
			requestMap.put("touser", sendUser);
			requestMap.put("agentid", wxConfig.getAgentid());
			requestMap.put("msgtype", "textcard");
			requestMap.put("textcard", textcard);
			// 必须加上header说明
			if (!wxConfig.sendTextCard(restTemplate, requestMap)) {
				wxConfig.sendTextCard(restTemplate, requestMap);
			}
		}
	}
}
