/*
 *    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 com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysArea;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AreaVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainListVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.ValidityUtil;
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.TDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TPreDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.util.ServiceUtil;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 预派单记录
 *
 * @author huyc
 * @date 2022-07-14 18:53:42
 */
@Service
@RequiredArgsConstructor
public class TPreDispatchInfoServiceImpl extends ServiceImpl<TPreDispatchInfoMapper, TPreDispatchInfo> implements TPreDispatchInfoService {

	@Autowired
	private SysBaseSetInfoMapper sysBaseSetInfoMapper;

	@Autowired
	private TDispatchDayConfMapper dispatchDayConfMapper;

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private TProvidentFundMapper providentFundMapper;

	@Autowired
	private TSocialInfoMapper socialInfoMapper;

	@Autowired
	private TDispatchInfoService dispatchInfoService;

	/**
	 * 预派单记录简单分页查询
	 *
	 * @param tPreDispatchInfo 预派单记录
	 * @return
	 */
	@Override
	public IPage<TPreDispatchInfo> getTPreDispatchInfoPage(Page<TPreDispatchInfo> page, TPreDispatchInfo tPreDispatchInfo) {
		return baseMapper.getTPreDispatchInfoPage(page, tPreDispatchInfo);
	}

	/**
	 * 修改资料是否提交状态  0 是 1 否
	 *
	 * @param ids
	 * @param status
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	@Override
	public R<Boolean> modifyDataSubmitStatus(String ids, String status) {
		//  验证传参
		if (Common.isEmpty(ids) ||
				Common.isEmpty(status) ||
				(!CommonConstants.ZERO_STRING.equals(status) && !CommonConstants.ONE_STRING.equals(status))) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		List<String> idList = Common.initStrToList(ids, CommonConstants.COMMA_STRING);
		if (null == idList || idList.isEmpty()) {
			return R.ok(null, CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		baseMapper.modifyDataSubmitStatus(idList, status);
		return R.ok();
	}

	/**
	 * 清空预派单默认的派单合同信息
	 * @param ids
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	@Override
	public R<Boolean> clearContractInfo(String ids) {
		if (Common.isEmpty(ids)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		List<String> idList = Common.initStrToList(ids, CommonConstants.COMMA_STRING);
		if (null == idList || idList.isEmpty()) {
			return R.ok(null, CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		baseMapper.clearContractInfo(idList);
		return R.ok();
	}

	/**
	 * 获取社保和公积金基数
	 * @param baseSocialTimeMap
	 * @param baseFundTimeMap
	 * @param baseSocialSetMap
	 * @param baseFundSetMap
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initBaseSetMap(Map<String, TPreDispatchInfo> baseSocialTimeMap,
								Map<String, TPreDispatchInfo> baseFundTimeMap,
								Map<String, SysBaseSetInfo> baseSocialSetMap,
								Map<String, SysBaseSetInfo> baseFundSetMap) {
		/************************获取社保公积金基数开始************************/
		SysBaseSetInfo baseSetInfo = new SysBaseSetInfo();
		// 处理社保基数
		handleSocialBase(baseSocialTimeMap, baseSocialSetMap, baseSetInfo);
		// 处理公积金基数
		handleFundBase(baseFundTimeMap, baseFundSetMap, baseSetInfo);
		/************************获取社保公积金基数结束************************/
	}

	/**
	 * 获取社保基数
	 * @param baseFundTimeMap
	 * @param baseFundSetMap
	 * @param baseSetInfo
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void handleFundBase(Map<String, TPreDispatchInfo> baseFundTimeMap, Map<String, SysBaseSetInfo> baseFundSetMap, SysBaseSetInfo baseSetInfo) {
		LocalDateTime dateTime;
		List<SysBaseSetInfo> baseSetInfoList;
		if (Common.isNotNull(baseFundTimeMap)) {
			HashMap<String, SysBaseSetInfo> baseFundSetMapT = null;
			baseSetInfo.setBaseType(CommonConstants.ONE_STRING);
			for (TPreDispatchInfo vo : baseFundTimeMap.values()) {
				baseFundSetMapT = null;
				if (null != vo.getFundStart()) {
					dateTime = LocalDateTimeUtils.dateOfYearAndMonth(vo.getFundStart(), LocalDateTimeUtils.DATE_SHORT_PATTERN);
					baseSetInfo.setApplyStartDate(LocalDateTimeUtils.convertLDTToDate(dateTime));
					baseSetInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
					baseSetInfo.setStatus(CommonConstants.ZERO_INT);
					baseSetInfoList = sysBaseSetInfoMapper.getAllByEntity(baseSetInfo);
					if (Common.isNotNull(baseSetInfoList)) {
						baseFundSetMapT = Common.listToHashMapByKey(baseSetInfoList,
								LocalDateTimeUtils.formatTime(dateTime, ValidityConstants.DATEFORMAT3_PATTERN),
								ExcelAttributeConstants.DEPARTID_PROVINCE_CITY_TOWN);
					}
				}
				if (Common.isNotNull(baseFundSetMapT)) {
					baseFundSetMap.putAll(baseFundSetMapT);
				}
			}
		}
	}

	/**
	 * 获取公积金基数
	 * @param baseSocialTimeMap
	 * @param baseSocialSetMap
	 * @param baseSetInfo
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private void handleSocialBase(Map<String, TPreDispatchInfo> baseSocialTimeMap, Map<String, SysBaseSetInfo> baseSocialSetMap, SysBaseSetInfo baseSetInfo) {
		LocalDateTime dateTime;
		List<SysBaseSetInfo> baseSetInfoList;
		if (Common.isNotNull(baseSocialTimeMap)) {
			HashMap<String, SysBaseSetInfo> baseSocialSetMapT = null;
			baseSetInfo.setBaseType(CommonConstants.ZERO_STRING);
			for (TPreDispatchInfo vo : baseSocialTimeMap.values()) {
				baseSocialSetMapT = null;
				if (null != vo.getPensionStart()) {
					dateTime = LocalDateTimeUtils.dateOfYearAndMonth(vo.getPensionStart(), LocalDateTimeUtils.DATE_SHORT_PATTERN);
					baseSetInfo.setApplyStartDate(LocalDateTimeUtils.convertLDTToDate(dateTime));
					baseSetInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
					baseSetInfo.setStatus(CommonConstants.ZERO_INT);
					baseSetInfoList = sysBaseSetInfoMapper.getAllByEntity(baseSetInfo);
					if (Common.isNotNull(baseSetInfoList) && null != dateTime) {
						baseSocialSetMapT = Common.listToHashMapByKey(baseSetInfoList,
								LocalDateTimeUtils.formatTime(dateTime, ValidityConstants.DATEFORMAT3_PATTERN),
								ExcelAttributeConstants.DEPARTID_PROVINCE_CITY_TOWN);
					}
				}
				if (Common.isNotNull(baseSocialSetMapT)) {
					baseSocialSetMap.putAll(baseSocialSetMapT);
				}
			}
		}
	}

	/**
	 * 查看公积金起缴时间是否符合政策
	 * @param newEntity
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private String checkFundStartDate(TPreDispatchInfo newEntity, SysBaseSetInfo baseSetInfo) {
		if (null == baseSetInfo) {
			return PreDispatchConstants.NO_FUND_BASE_SET_INFO;
		}
		// 查看是否符合公积金补缴政策
		if (checkDispatchDate(
				LocalDateTimeUtils.dateOfYearAndMonth(newEntity.getFundStart(), DateUtil.ISO_DATE_FORMAT),
				baseSetInfo.getCanOverpay(), baseSetInfo.getOverpayNumber(), baseSetInfo.getHaveThisMonth())) {
			return PreDispatchConstants.FUND_START_DATE_ERROR;
		}
		return null;
	}

	/**
	 * 查看公积金起缴时间是否符合政策
	 * @param newEntity
	 * @param oldEntity
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private R<Boolean> checkFundStartDate(TPreDispatchInfo newEntity, TPreDispatchInfo oldEntity) {
		// 公积金确实要派增且时间有变动要判断是否符合派单政策
		if (Common.isNotNull(newEntity.getFundAddress()) &&
				Common.isNotNull(newEntity.getFundStart()) &&
				!newEntity.getFundStart().equals(oldEntity.getFundStart())) {
			SysBaseSetInfo baseSetFund = null;
			if (null != newEntity.getFundProvince()) {
				baseSetFund = getSysBaseSetInfo(newEntity.getFundProvince(), newEntity.getFundCity(),
						newEntity.getFundTown(), oldEntity.getFundHouseAdd(), CommonConstants.ONE_STRING);
			} else {
				baseSetFund = getSysBaseSetInfo(oldEntity.getFundProvince(), oldEntity.getFundCity(),
						oldEntity.getFundTown(), oldEntity.getFundHouseAdd(), CommonConstants.ONE_STRING);
			}
			if (null == baseSetFund) {
				return R.failed(PreDispatchConstants.NO_FUND_BASE_SET_INFO);
			}
			// 查看是否符合公积金补缴政策
			if (checkDispatchDate(
					LocalDateTimeUtils.dateOfYearAndMonth(newEntity.getFundStart(), DateUtil.ISO_DATE_FORMAT),
					baseSetFund.getCanOverpay(), baseSetFund.getOverpayNumber(), baseSetFund.getHaveThisMonth())) {
				return R.failed(PreDispatchConstants.FUND_START_DATE_ERROR);
			}
		}
		return null;
	}

	/**
	 * 更新预派单是否派单状态
	 * @param id
	 * @param dispatchFlag
	 * @param cancelRemark
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	@Override
	public R<Boolean> updateDispatchFlag(String id, String dispatchFlag, String cancelRemark) {
		TPreDispatchInfo dispatchInfo = baseMapper.selectById(id);
		if (null == dispatchFlag) {
			return R.failed("无此实体！");
		}
		if (!CommonConstants.ZERO_STRING.equals(dispatchFlag) && !CommonConstants.ONE_STRING.equals(dispatchFlag)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		dispatchInfo.setDispatchFlag(dispatchFlag);
		dispatchInfo.setCancelRemark(cancelRemark);
		baseMapper.updateById(dispatchInfo);
		return R.ok();
	}

	/**
	 * 单个派单
	 * @param id
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	@Override
	public R<Boolean> dispatchById(String id) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		if (Common.isEmpty(id)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		List<TSettleDomainSelectVo> settleDomainR = null;
		R<TSettleDomainListVo> listVo = null;
		listVo = archivesDaprUtil.selectAllSettleDomainSelectVos();
		if (Common.isNotNull(listVo)) {
			TSettleDomainListVo tSettleDomainListVo = listVo.getData();
			if (Common.isNotNull(tSettleDomainListVo) && Common.isNotEmpty(tSettleDomainListVo.getListSelectVO())) {
				settleDomainR = tSettleDomainListVo.getListSelectVO();
			}
		}
		TPreDispatchInfo preInfo = baseMapper.selectById(id);
		if (null == preInfo){
			return R.failed(CommonConstants.ERROR_NO_DOMAIN);
		}
		if (!CommonConstants.ZERO_STRING.equals(preInfo.getPreStatus())
				||CommonConstants.ONE_STRING.equals(preInfo.getStatus())
				|| CommonConstants.ONE_STRING.equals(preInfo.getDispatchFlag())){
			return R.failed(PreDispatchConstants.PRESTATUS_ERROR);
		}
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		R<Boolean> errorMessage = null;
		HashMap<String,SysArea> areaMap = new HashMap<>();
		HashMap<String,SysArea> areaIdMap = new HashMap<>();
		// 派单派增处理
		if (CommonConstants.ZERO_STRING.equals(preInfo.getType())) {
			TDispatchImportVo importVo = new TDispatchImportVo();
			//  初始化派增的派单数据
			initDispatchAddVo(preInfo, importVo);
			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);
				// 处理 档案地市
				errorMessageList = handleFileAddress(1, preInfo, areaMap, areaIdMap, importVo, errorMessageList);
			}
			//  档案地市没问题 开始派单处理
			if (errorMessageList.size() == CommonConstants.ZERO_INT) {
				dispatchInfoService.importTDispatchInfo(importVoList, errorMessageList, user);
			}
			//  处理派增结果
			errorMessage = handleDispatchAddRes(preInfo, errorMessageList);
			if (null != errorMessage) {
				return errorMessage;
			}
		}

		// 派单派减处理
		if (CommonConstants.ONE_STRING.equals(preInfo.getType())){
			TDispatchReduceVo dispatchReduceVo = new TDispatchReduceVo();
			dispatchReduceVo.setEmpName(preInfo.getEmpName());
			dispatchReduceVo.setEmpIdcard(preInfo.getEmpIdcard());
			if (Common.isNotNull(preInfo.getLeaveDate())){
				dispatchReduceVo.setLeaveDate(DateUtil.stringToDate(preInfo.getLeaveDate()));
			}
			dispatchReduceVo.setReasonType(preInfo.getLeaveReasonAdd());
			dispatchReduceVo.setTrustRemark(preInfo.getLeaveReason());
			if (Common.isNotNull(preInfo.getPensionEndReduce())) {
				dispatchReduceVo.setSocialReduceDate(DateUtil.getFirstDay(preInfo.getPensionEndReduce()));
			}
			if (Common.isNotNull(preInfo.getFundEndReduce())){
				dispatchReduceVo.setFundReduceDate(DateUtil.getFirstDay(preInfo.getFundEndReduce()));
			}
			List<TDispatchReduceVo> dispatchImportList = new ArrayList<>();
			dispatchImportList.add(dispatchReduceVo);
			dispatchInfoService.batchReduceDispatch(dispatchImportList, errorMessageList, user);
			//  处理派减结果
			errorMessage = handleDispatchAddRes(preInfo,errorMessageList);
			if (null != errorMessage){
				return errorMessage;
			}
		}
		return R.ok();
	}

	/**
	 * 一键派单
	 * @param idStr
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	@Override
	public R oneKeyToDispatch(String idStr) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		List<TSettleDomainSelectVo> settleDomainR = null;
		R<TSettleDomainListVo> listVo = null;
		//项目名称map key:项目id value:项目名称
		Map<String, String> settleDomainNameMap = new HashMap<>();
		//客户名称map key:客户id value:客户名称
		Map<String, String> customerNameMap = new HashMap<>();
		//项目客户关系map key:项目id value:客户id
		Map<String, String> settleIdAndCustomerIdMap = new HashMap<>();
		listVo = archivesDaprUtil.selectAllSettleDomainSelectVos();
		if (Common.isNotNull(listVo)) {
			TSettleDomainListVo tSettleDomainListVo = listVo.getData();
			if (Common.isNotNull(tSettleDomainListVo) && Common.isNotEmpty(tSettleDomainListVo.getListSelectVO())) {
				settleDomainR = tSettleDomainListVo.getListSelectVO();
			}
		}
		//map数据封装
		initSettleDomainMaps(settleDomainR, settleDomainNameMap, customerNameMap, settleIdAndCustomerIdMap);
		// 获取当前创建人 截止到当前时间的 正常未派单 未删除的预派单数据
		List<TPreDispatchInfo> preList;
		if (Common.isEmpty(idStr)) {
			preList = baseMapper.selectList(Wrappers.<TPreDispatchInfo>query().lambda()
					.eq(TPreDispatchInfo::getCreateBy, user.getId())
					.le(TPreDispatchInfo::getCreateTime, LocalDateTime.now())
					.eq(TPreDispatchInfo::getStatus, CommonConstants.ZERO_STRING)
					.eq(TPreDispatchInfo::getDispatchFlag, CommonConstants.ZERO_STRING)
					.eq(TPreDispatchInfo::getPreStatus, CommonConstants.ZERO_STRING));
		} else {
			List<String> idList = Common.initStrToList(idStr, ",");
			preList = baseMapper.selectList(Wrappers.<TPreDispatchInfo>query().lambda()
					.in(TPreDispatchInfo::getId, idList)
					.eq(TPreDispatchInfo::getCreateBy, user.getId())
					.le(TPreDispatchInfo::getCreateTime, LocalDateTime.now())
					.eq(TPreDispatchInfo::getStatus, CommonConstants.ZERO_STRING)
					.eq(TPreDispatchInfo::getDispatchFlag, CommonConstants.ZERO_STRING)
					.eq(TPreDispatchInfo::getPreStatus, CommonConstants.ZERO_STRING));
		}
		if (!Common.isNotNull(preList)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		//  找出所有需要派减的社保或公积金数据 主要用于派减是获取项目相关数据
		HashMap<String, TSocialInfo> socialMap = new HashMap<>();
		HashMap<String, TProvidentFund> fundMap = new HashMap<>();
		// 封装需要派减的社保或公积金信息
		initReduceSocialFundInfo(preList, socialMap, fundMap);
		// 开始处理派增
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		List<ErrorMessage> errorMsgList = new ArrayList<>();
		R<Boolean> res;
		HashMap<String, SysArea> areaMap = new HashMap<>();
		HashMap<String, SysArea> areaIdMap = new HashMap<>();
		int i = 1;
		for (TPreDispatchInfo pre : preList) {
			i++;
			if (checkLimit(pre)) {
				continue;
			}
			// 派单派增处理
			batchDispatchAdd(settleDomainNameMap, customerNameMap, settleIdAndCustomerIdMap, user, errorMsgList, i, pre,
					areaMap, areaIdMap);
			// 派单派减处理
			if (CommonConstants.ONE_STRING.equals(pre.getType())) {
				TDispatchReduceVo dispatchReduceVo = new TDispatchReduceVo();
				dispatchReduceVo.setEmpName(pre.getEmpName());
				dispatchReduceVo.setEmpIdcard(pre.getEmpIdcard());
				if (null != pre.getLeaveDate()){
					dispatchReduceVo.setLeaveDate(DateUtil.stringToDate(pre.getLeaveDate()));
				}
				dispatchReduceVo.setReasonType(pre.getLeaveReasonAdd());
				dispatchReduceVo.setTrustRemark(pre.getLeaveReason());
				// 处理派减派单时间
				dispatchReduce(dispatchReduceVo, pre);
				List<TDispatchReduceVo> dispatchImportList = new ArrayList<>();
				dispatchImportList.add(dispatchReduceVo);
				dispatchInfoService.batchReduceDispatch(dispatchImportList, errorMessageList, user);

				//处理派减结果
				handleDispatchAddRes(pre, errorMessageList);
				//重新组装数据
				resetMessageList(pre, errorMessageList, errorMsgList, i + 1);
			}
		}
		if (Common.isNotNull(errorMsgList)) {
			return R.failed(errorMsgList);
		}
		return R.ok();
	}

	@Override
	public R update(TPreDispatchInfo tPreDispatchInfo) {

		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		ExcelAttributeValidityUtil<TPreDispatchInfo> validity = new ExcelAttributeValidityUtil<>(TPreDispatchInfo.class);
		validity.ValidityObj(tPreDispatchInfo);
		if (null != validity.getErrorInfo() && !validity.getErrorInfo().isEmpty()) {
			return R.failed(validity.getErrorInfo(), ResultConstants.VALIDITY_FAIL);
		}
		HashMap<String, SysArea> areaHashMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		HashMap<String, SysArea> areaIdMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		TPreDispatchInfo preDispatchTemp = baseMapper.selectById(tPreDispatchInfo.getId());
		tPreDispatchInfo.setType(preDispatchTemp.getType());

		// 初步校验  如果合同时间变更 同步更新 派单的时间
		R<Boolean> errorMessage1 = checkUpdate(tPreDispatchInfo, areaHashMap, areaIdMap, preDispatchTemp);
		if (errorMessage1 != null) {
			return errorMessage1;
		}
		// 社保缴纳地变更 同步更新 社保的省市县数据
		R<Boolean> areaErrorMessage = handleSocialArea(areaHashMap, areaIdMap, tPreDispatchInfo, preDispatchTemp);
		if (null != areaErrorMessage) {
			return areaErrorMessage;
		}
		// 公积金缴纳地变更 同步更新 公积金的省市县数据
		areaErrorMessage = handleFundArea(areaHashMap, areaIdMap, tPreDispatchInfo, preDispatchTemp);
		if (null != areaErrorMessage) {
			return areaErrorMessage;
		}
		// 派增要派单时间  派减不需要
		if (CommonConstants.ZERO_STRING.equals(tPreDispatchInfo.getType())) {
			// 社保起缴日期变更 验证是否可派增
			R<Boolean> x = checkSocialStartDate(tPreDispatchInfo, preDispatchTemp);
			if (x != null) {
				return x;
			}
			// 公积金起缴日期变更 验证是否可派增
			x = checkFundStartDate(tPreDispatchInfo, preDispatchTemp);
			if (x != null) {
				return x;
			}
			// 手机号码必填及格式校验
			if (Common.isEmpty(tPreDispatchInfo.getTelTwo())){
				return R.failed(PreDispatchConstants.TEL_NOT_EMPTY);
			}
		}
		if (CommonConstants.ONE_STRING.equals(tPreDispatchInfo.getType())) {
			initLeaveReason(tPreDispatchInfo);
			tPreDispatchInfo.setPensionAddress(tPreDispatchInfo.getPensionAddressReduce());
			tPreDispatchInfo.setFundAddress(tPreDispatchInfo.getFundAddressReduce());
		}
		// 合同开始截止时间 同步更新派单的合同时间
//		tPreDispatchInfo.setContractEndAdd(tPreDispatchInfo.getContractEnd());
//		tPreDispatchInfo.setContractStartAdd(tPreDispatchInfo.getContractStart());
		// 没问题重置异常状态，有问题 在前面就返回了
		tPreDispatchInfo.setExceptionContent(CommonConstants.EMPTY_STRING);
		tPreDispatchInfo.setPreStatus(CommonConstants.ZERO_STRING);
		baseMapper.updatePreDispatchInfoById(tPreDispatchInfo);
		return R.ok();
	}

	@Override
	public List<ErrorMessage> batchSavePreDisPatchAdd(List<TPreDispatchInfo> listInfo, YifuUser user, String socialHouse, String fundHouse, String departId) {
		List<ErrorMessage> errorList = new ArrayList<>();
		R<TSettleDomainSelectVo> domainR = archivesDaprUtil.getSettleDomainSelectVoById(departId);
		// 获取区域数据MAP
		HashMap<String, SysArea> areaHashMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		HashMap<String, SysArea> areaIdMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		if (dataCheck(listInfo, errorList, areaHashMap, areaIdMap)) {
			return errorList;
		}
		if (dataCheckDepart(errorList, domainR)) {
			return errorList;
		}
		TSettleDomainSelectVo selectVo = domainR.getData();
		// 获取基数配置信息
		HashMap<String, SysBaseSetInfo> baseSocialSetMap = new HashMap<>();
		HashMap<String, SysBaseSetInfo> baseFundSetMap = new HashMap<>();
		HashMap<String, TPreDispatchInfo> baseSocialTimeMap = new HashMap<>();
		HashMap<String, TPreDispatchInfo> baseFundTimeMap = new HashMap<>();
		initSocialAndFundBaseSet(listInfo, baseSocialSetMap, baseFundSetMap, baseSocialTimeMap, baseFundTimeMap);
		//  查询当月对应身份证是否已经派增或派减了 后面做判重处理
		HashMap<String, TPreDispatchInfo> existsMap = new HashMap<>();
		initExistsMapByIdCards(listInfo, existsMap, CommonConstants.ZERO_STRING);
		// 获取所有地市的最迟派单日限制
		HashMap<String, Integer> dayConfMap = new HashMap<>();
		initDayConfMap(dayConfMap);
		int i = 1;
		for (TPreDispatchInfo info : listInfo) {
			i++;
			if (Common.isNotNull(info.getTelNotice()) && (!CommonConstants.IS_TRUE.equals(info.getTelNotice()) &&
					!CommonConstants.IS_FALSE.equals(info.getTelNotice()))) {
				errorList.add(new ErrorMessage(i,"是否电话通知不允许导入【是】和【否】之外的内容"));
				continue;
			}
			// 1.验重
			if (checkAddRepeat(errorList, existsMap, i, info)) {
				continue;
			}
			// 基础封装 其他
			initBaseInfo(socialHouse, fundHouse, selectVo, info);
			// 2.先校验已有数据
			checkBatchSave(info, CommonConstants.ZERO_STRING);
			// 3.封装 社保缴纳地  公积金缴纳地
			initBatchAreaAdd(areaHashMap, areaIdMap, info);
			// 4.验证缴纳地和补缴日期是否符合政策
			if (Common.isEmpty(info.getExceptionContent())) {
				checkStartTime(baseSocialSetMap, baseFundSetMap, null, info);
			}
			// 5.封装地市派单限制日
			initDayLimit(dayConfMap, info);
			// 6.保存 有异常也保存 要标识
			info.setUserDeptName(selectVo.getDepartName());
			info.setPreStatus(CommonConstants.ZERO_STRING);
			// 为验重添加到MAP
			existsMap.put(info.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + info.getPayAddress(), info);
			if (Common.isEmpty(info.getExceptionContent())) {
				errorList.add(new ErrorMessage(i, "保存成功！", CommonConstants.GREEN));
			} else {
				info.setPreStatus(CommonConstants.ONE_STRING);
				errorList.add(new ErrorMessage(i, "保存成功！" +
						info.getExceptionContent(), CommonConstants.RED));
			}
			baseMapper.insert(info);
		}
		return errorList;
	}

	/**
	 * 预派单批量新增派减
	 * @param list
	 * @param user
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	@Transactional
	@Override
	public List<ErrorMessage> batchSavePreDisPatchReduce(List<TPreDispatchReduceVo> list, YifuUser user) {

		List<ErrorMessage> errorList = new ArrayList<>();
		// 获取区域数据MAP
		HashMap<String, SysArea> areaIdMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		HashMap<String, SysArea> areaHashMap = new HashMap<>(CommonConstants.SIXTEEN_INT);

		// 做下转换
		List<TPreDispatchInfo> listInfo = changePreRes(list);
		if (dataCheck(listInfo, errorList, areaHashMap, areaIdMap)) {
			return errorList;
		}
		// 查询当月对应身份证是否已经派增或派减了 后面做判重处理
		HashMap<String, TPreDispatchInfo> existsMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		initExistsMapByIdCards(listInfo, existsMap, CommonConstants.ONE_STRING);
		// 获取所有地市的最迟派单日限制
		HashMap<String, Integer> dayConfMap = new HashMap<>();
		initDayConfMap(dayConfMap);
		// 获取系统中未派单的派增预派单
		HashMap<String, String> preAddMap = new HashMap<>();
		getPreAddMap(preAddMap);
		int i = 1;
		for (TPreDispatchInfo info : listInfo) {
			i++;
			// 1.验重
			if (checkAddRepeat(errorList, existsMap, i, info)) {
				continue;
			}
			// 2.基础封装 其他
			initReduceBaseInfo(null, info);
			// 3.先校验已有数据
			checkBatchSave(info, CommonConstants.ONE_STRING);
			if (Common.isEmpty(info.getExceptionContent())) {
				// 封装社保或公积金的部门数据
				initAndCheckArea(areaIdMap, areaHashMap, info);
			}
			// 4.封装地市派单限制日
			initDayLimit(dayConfMap, info);
			// 5.保存  有异常也保存  要做标识
			R<TSettleDomainSelectVo> domainR = archivesDaprUtil.getSettleDomainSelectVoById(user.getDeptId().toString());
			if (Common.isNotNull(domainR) && Common.isNotNull(domainR.getData())) {
				TSettleDomainSelectVo selectVo = domainR.getData();
				info.setUserDeptName(selectVo.getDepartName());
			}
			info.setPreStatus(CommonConstants.ZERO_STRING);
			// 如果已经存在未派单的派增 这个时候派减 直接标记异常 客服自行判断是否派单
			if (null != preAddMap.get(info.getEmpIdcard())) {
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent("当月已存在派增，请确认并处理此人是否取消增减预派单！");
			}
			// 为验重添加到MAP
			existsMap.put(info.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + info.getPayAddress(), info);
			if (Common.isEmpty(info.getExceptionContent())) {
				errorList.add(new ErrorMessage(i, CommonConstants.SAVE_SUCCESS, CommonConstants.GREEN));
			} else {
				info.setPreStatus(CommonConstants.ONE_STRING);
				errorList.add(new ErrorMessage(i, CommonConstants.SAVE_SUCCESS +
						info.getExceptionContent(), CommonConstants.RED));
			}
			baseMapper.insert(info);
		}
		return errorList;
	}

	/**
	 * 预派单批量更新
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param list
	 * @param user
	 * @return
	 **/
	@Override
	public List<ErrorMessage> batchUpdatePreDisPatch(List<TPreDispatchUpdateVo> list, YifuUser user) {
		List<ErrorMessage> errorList = new ArrayList<>();
		// 获取区域数据MAP
		HashMap<String, SysArea> areaHashMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		HashMap<String,SysArea> areaIdMap = new HashMap<>(CommonConstants.SIXTEEN_INT);
		// 做下转换
		List<TPreDispatchInfo> listInfo = changeRes(list);
		if (dataCheckSub(listInfo, errorList, areaHashMap, areaIdMap)) {
			return errorList;
		}
		// 获取基数配置信息
		HashMap<String, SysBaseSetInfo> baseSocialSetMap = new HashMap<>();
		HashMap<String, SysBaseSetInfo> baseFundSetMap = new HashMap<>();
		HashMap<String, TPreDispatchInfo> baseSocialTimeMap = new HashMap<>();
		HashMap<String, TPreDispatchInfo> baseFundTimeMap = new HashMap<>();
		HashMap<String,TPreDispatchInfo> existsMap  = new HashMap<>();
		HashMap<String,TPreDispatchInfo> repeatMap  = new HashMap<>();
		initSocialAndFundBaseSet(listInfo, baseSocialSetMap, baseFundSetMap, baseSocialTimeMap, baseFundTimeMap);
		initExistsMapByIds(listInfo,existsMap,repeatMap);
		// 获取所有地市的最迟派单日限制
		HashMap<String,Integer> dayConfMap = new HashMap<>();
		initDayConfMap(dayConfMap);
		TPreDispatchInfo  temp  = null;
		TPreDispatchInfo  repeat  = null;
		int i=1;
		String str = null;
		for (TPreDispatchInfo info:listInfo){
			i++;
			if (Common.isNotNull(info.getTelNotice()) && (!CommonConstants.IS_TRUE.equals(info.getTelNotice()) &&
					!CommonConstants.IS_FALSE.equals(info.getTelNotice()))) {
				errorList.add(new ErrorMessage(i,"是否电话通知不允许导入【是】和【否】之外的内容"));
				continue;
			}
			// 重置异常状态
			info.setExceptionContent("");
			info.setPreStatus(CommonConstants.ZERO_STRING);
			temp = existsMap.get(info.getId());
			repeat = repeatMap.get(info.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+info.getPayAddress());
			// 判重 及身份证不可更新
			if (checkRepeatOrIdcard(errorList, temp, i+1, info,repeat)) {
				continue;
			}
			// 验证派单类型
			checkDispatchType(info);
			// 1.先校验已有数据
			str = checkBatchSave(info,info.getType());
			if (null != str) {
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent(str);
			}
			// 2.封装 社保缴纳地  公积金缴纳地
			initBatchUpdateArea(areaHashMap, areaIdMap, info);
			if (Common.isEmpty(info.getExceptionContent())){
				// 3.验证补缴时间是否异常  派增验证 派减日期不处理
				checkStartTime(baseSocialSetMap, baseFundSetMap, temp, info);
			}
			// 4.如果派增缴纳地有变更重新变更派单限制日期
			initDayLimitForUpdate(dayConfMap, temp, info);
			// 5.更新
			updateInfoByIdSub(errorList, temp, i, info);
		}
		return errorList;
	}

	@Override
	public void doexportPreDispatch(HttpServletResponse response, TPreDispatchInfo tPreDispatchInfo) {
		String fileName = "导出预派单" + DateUtil.getThisTime() + ".xlsx";

		//获取要导出的列表
		List<TPreDispatchExportVo> list = new ArrayList<>();

		//获取记录
		list = baseMapper.getListForExport(tPreDispatchInfo);

		ServletOutputStream out = null;
		if (list == null || list.isEmpty()) {
			list = new ArrayList<>();
		}
		try {
			out = response.getOutputStream();
			ExcelUtil<TPreDispatchExportVo> util = new ExcelUtil<>(TPreDispatchExportVo.class);
			for (TPreDispatchExportVo vo : list) {
				util.convertEntity(vo, null, null, null);
			}
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			EasyExcel.write(out, TPreDispatchExportVo.class).includeColumnFiledNames(tPreDispatchInfo.getExportFields()).sheet("预派单")
					.doWrite(list);
			out.flush();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * 派单类型校验
	 * @Author fxj
	 * @Date 2020-12-31
	 * @param info
	 * @return
	 **/
	private String checkDispatchType(TPreDispatchInfo info) {
		if (Common.isEmpty(info.getType()) ||
				(!CommonConstants.ZERO_STRING.equals(info.getType()) && !CommonConstants.ONE_STRING.equals(info.getType()))){
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(PreDispatchConstants.DISPATCH_TYPE_ERROR);
			return PreDispatchConstants.DISPATCH_TYPE_ERROR;
		}
		return null;
	}

	private List<TPreDispatchInfo> changeRes(List<TPreDispatchUpdateVo> list) {
		List<TPreDispatchInfo> listInfo = new ArrayList<>();
		if (Common.isNotNull(list)){
			for (TPreDispatchInfo info:list){
				listInfo.add(info);
			}
		}
		return listInfo;
	}

	private List<TPreDispatchInfo> changePreRes(List<TPreDispatchReduceVo> list) {
		List<TPreDispatchInfo> listInfo = new ArrayList<>();
		TPreDispatchInfo preInfo = new TPreDispatchInfo();
		if (Common.isNotNull(list)){
			for (TPreDispatchReduceVo info:list){
				BeanUtils.copyProperties(info,preInfo);
				listInfo.add(preInfo);
			}
		}
		return listInfo;
	}

	private void initBatchUpdateArea(HashMap<String, SysArea> areaHashMap, HashMap<String, SysArea> areaIdMap, TPreDispatchInfo info) {
		R<Boolean> x;
		if (CommonConstants.ZERO_STRING.equals(info.getType())){
			initBatchAreaAdd(areaHashMap, areaIdMap, info);
		}else if (CommonConstants.ONE_STRING.equals(info.getType())){
			// 初始化离职原因
			initLeaveReason(info);
			x = handleSocialAreaAdd(areaHashMap,areaIdMap,info,info.getPensionAddressReduce());
			if (null != x){
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent(x.getMsg());
				return;
			}
			x = handleFundAreaAdd(areaHashMap,areaIdMap,info,info.getFundAddressReduce());
			if (null != x){
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent(x.getMsg());
			}
		}
	}

	/**
	 * 通过IDS封装已存在的社保数
	 * @Author fxj
	 * @Date 2021-01-04
	 * @param listInfo
	 * @param existsMap
	 * @return
	 **/
	private void initExistsMapByIds(List<TPreDispatchInfo> listInfo,
									Map<String,TPreDispatchInfo> existsMap,Map<String,TPreDispatchInfo> repeatMap) {
		List<String>  idList = new ArrayList<>();
		List<String>  idcarList = new ArrayList<>();
		if (Common.isNotNull(listInfo)) {
			for (TPreDispatchInfo info:listInfo){
				idList.add(info.getId());
				idcarList.add(info.getEmpIdcard());
			}
		}
		// 初始化要更新的数据MAP
		initExistsMapByIds(existsMap, idList);
		// 初始化要验重的数据Map
		initRepeatMap(repeatMap, idcarList);
	}
	/**
	 * 初始化要更新的数据MAP
	 * @Author fxj
	 * @Date 2021-01-04
	 * @param existsMap
	 * @param idList
	 * @return
	 **/
	private void initExistsMapByIds(Map<String, TPreDispatchInfo> existsMap, List<String> idList) {
		if (Common.isNotNull(idList)){
			List<TPreDispatchInfo> preDispatchInfoList = baseMapper.
					selectList(Wrappers.<TPreDispatchInfo>query().lambda().in(TPreDispatchInfo::getId,idList));
			if (Common.isNotNull(preDispatchInfoList)){
				for (TPreDispatchInfo info:preDispatchInfoList){
					existsMap.put(info.getId(),info);
				}
			}
		}
	}

	private void initRepeatMap(Map<String, TPreDispatchInfo> repeatMap, List<String> idcarList) {
		if (Common.isNotNull(idcarList)){
			List<TPreDispatchInfo> preDispatchInfoList = baseMapper.
					selectList(Wrappers.<TPreDispatchInfo>query().lambda().in(TPreDispatchInfo::getEmpIdcard,idcarList)
							.ne(TPreDispatchInfo::getPreStatus, CommonConstants.TWO_STRING));
			if (Common.isNotNull(preDispatchInfoList)){
				for (TPreDispatchInfo info:preDispatchInfoList){
					repeatMap.put(info.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+info.getPayAddress(),info);
				}
			}
		}
	}

	/**
	 * 更新代码处理
	 * @Author fxj
	 * @Date 2021-01-12
	 * @param errorList
	 * @param temp
	 * @param i
	 * @param info
	 * @return
	 **/
	private void updateInfoByIdSub(List<ErrorMessage> errorList, TPreDispatchInfo temp, int i, TPreDispatchInfo info) {
		if (Common.isNotNull(info.getPreStatus()) && info.getPreStatus().length() > CommonConstants.ONE_INT){
			info.setPreStatus(null);
		}
		if (CommonConstants.TWO_STRING.equals(temp.getPreStatus())){
			info.setPreStatus(CommonConstants.TWO_STRING);
		}
		if (PreDispatchConstants.YES_CH.equals(info.getDataSubStatus())){
			info.setDataSubStatus(CommonConstants.ZERO_STRING);
		}
		if (PreDispatchConstants.NO_CH.equals(info.getDataSubStatus())){
			info.setDataSubStatus(CommonConstants.ONE_STRING);
		}
		info.setContractNameAdd(temp.getContractNameAdd());
		info.setContractTypeAdd(temp.getContractTypeAdd());
		info.setContractTermAdd(temp.getContractTermAdd());
		info.setContractStartAdd(temp.getContractStart());
		info.setContractEndAdd(temp.getContractEnd());
		// 合同开始截止时间 同步更新派单的合同时间
		info.setContractEndAdd(info.getContractEnd());
		info.setContractStartAdd(info.getContractStart());
		baseMapper.updatePreDispatchInfoById(info);
		if (Common.isNotNull(info.getExceptionContent())){
			errorList.add(new ErrorMessage(i, CommonConstants.SAVE_SUCCESS+info.getExceptionContent(),CommonConstants.RED));
		}else {
			errorList.add(new ErrorMessage(i, CommonConstants.SAVE_SUCCESS,CommonConstants.GREEN));
		}
	}

	private static boolean isaBoolean(LocalDateTime temp, LocalDateTime now) {
		return temp.getYear() == now.getYear() && temp.getMonthValue() < now.getMonthValue();
	}
	private boolean checkRepeatOrIdcard(List<ErrorMessage> errorList, TPreDispatchInfo temp, int i,
										TPreDispatchInfo info,TPreDispatchInfo  repeat) {
		if (null == temp){
			errorList.add(new ErrorMessage(i, CommonConstants.DATA_CAN_NOT_EMPTY));
			return true;
		}
		info.setType(temp.getType());
		if (null != repeat && !repeat.getId().equals(info.getId())){
			errorList.add(new ErrorMessage(i, "已存在身份证对应缴费地的数据！"));
			return true;
		}
		info.setSocialHouseAdd(temp.getSocialHouseAdd());
		info.setFundHouseAdd(temp.getFundHouseAdd());
		// 身份证不可更新
		if (!temp.getEmpIdcard().equals(info.getEmpIdcard())){
			errorList.add(new ErrorMessage(i+1, PreDispatchConstants.EMPIDCARD_IS_EMPTY));
			return true;
		}
		return false;
	}

	/**
	 * 更新的时候派增缴纳地有变更时重新更新派增限制日期
	 * @Author fxj
	 * @Date 2021-01-04
	 * @param dayConfMap
	 * @param temp
	 * @param info
	 * @return
	 **/
	private void initDayLimitForUpdate(HashMap<String, Integer> dayConfMap, TPreDispatchInfo temp, TPreDispatchInfo info) {
		if (CommonConstants.ZERO_STRING.equals(info.getType())){
			boolean flag = (Common.isNotNull(info.getPensionAddress()) && !info.getPensionAddress().equals(temp.getPensionAddress())) ||
					(Common.isNotNull(info.getFundAddress()) && !info.getFundAddress().equals(temp.getFundAddress()));
			if (flag){
				initDayLimit(dayConfMap, info);
			}
		}
	}

	/**
	 * 预派单更新前校验
	 *
	 * @param tPreDispatchInfo
	 * @param areaHashMap
	 * @param areaIdMap
	 * @param preDispatchTemp
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> checkUpdate(TPreDispatchInfo tPreDispatchInfo, Map<String, SysArea> areaHashMap,
								   Map<String, SysArea> areaIdMap, TPreDispatchInfo preDispatchTemp) {
		if (null == tPreDispatchInfo || Common.isEmpty(tPreDispatchInfo.getId())) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		if (null == preDispatchTemp) {
			return R.failed(CommonConstants.ERROR_NO_DOMAIN);
		}
		// 先验证必填项
		String errorMessage = checkField(tPreDispatchInfo);
		if (null != errorMessage) {
			return R.failed(errorMessage);
		}
		R<AreaVo> areaListR = upmsDaprUtils.getAreaListR();
		if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
			return R.failed(PreDispatchConstants.GET_AREA_INFO);
		}
		initAreaMap(areaHashMap, areaIdMap, areaListR);
		return null;
	}

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

	private void initAndCheckArea(HashMap<String, SysArea> areaIdMap, HashMap<String, SysArea> areaHashMap, TPreDispatchInfo info) {
		R<Boolean> x = handleSocialAreaAdd(areaHashMap, areaIdMap, info, info.getPensionAddressReduce());
		if (null != x) {
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(x.getMsg());
		}
		x = handleFundAreaAdd(areaHashMap, areaIdMap, info, info.getFundAddressReduce());
		if (null != x) {
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(x.getMsg());
		}
	}

	/**
	 * 初始化基础数据  如  各种状态 合同数据等
	 * @param socialHouse
	 * @param selectVo
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initBaseInfo(String socialHouse, String fundHouse, TSettleDomainSelectVo selectVo, TPreDispatchInfo info) {
		info.setType(CommonConstants.ZERO_STRING);
		info.setDataSubStatus(CommonConstants.ONE_STRING);
		info.setStatus(CommonConstants.ZERO_STRING);
		info.setPreStatus(CommonConstants.ZERO_STRING);
		// 默认社保代理 4
		info.setEmpTypeAdd(CommonConstants.FOUR_STRING);
		info.setPositionAdd(PreDispatchConstants.POSITION);
		if (Common.isNotNull(selectVo)) {
			info.setDepartIdAdd(selectVo.getId());
			info.setDepartNameAdd(selectVo.getDepartName());
			info.setUnitIdAdd(selectVo.getCustomerId());
			info.setUnitNameAdd(selectVo.getCustomerName());
		}
		// 默认合同名称为代理社保 合同类型为其他
		info.setContractNameAdd(PreDispatchConstants.CONTRACT_NAME);
		info.setContractTypeAdd(CommonConstants.THREE_STRING);
		info.setContractStartAdd(info.getContractStart());
		// 默认为开始时间后的两年时间
		info.setContractEndAdd(info.getContractEnd());
		// 默认合同期限2年
		info.setContractTermAdd(Integer.toString(Common.getYearOfTime(info.getContractStart(), info.getContractEnd())));
		// 默认工时制 综合工时制2
		info.setWorkingHoursAdd(CommonConstants.TWO_STRING);
		info.setSocialHouseAdd(socialHouse);
		info.setFundHouseAdd(fundHouse);
	}

	/**
	 * 校验修改派增派减
	 *
	 * @param tPreDispatchInfo
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private String checkField(TPreDispatchInfo tPreDispatchInfo) {
		// 姓名  身份证  缴费地 必填验证
		String x2 = updateOrSaveBaseCheck(tPreDispatchInfo);
		if (x2 != null) {
			return x2;
		}
		// 派增验证
		String x = checkAddPreDispatch(tPreDispatchInfo);
		if (x != null) {
			return x;
		}
		// 派减验证
		String x1 = checkReducePreDispatch(tPreDispatchInfo);
		if (x1 != null) {
			return x1;
		}
		return null;
	}

	private String updateOrSaveBaseCheck(TPreDispatchInfo tPreDispatchInfo) {
		if (Common.isEmpty(tPreDispatchInfo.getEmpName())) {
			return "员工姓名不可为空！";
		}
		if (Common.isEmpty(tPreDispatchInfo.getEmpIdcard())) {
			return "身份证号不可为空！";
		}
		if (Common.isEmpty(tPreDispatchInfo.getPayAddress())) {
			return "缴费地不可为空！";
		}
		// 派增或派减的缴纳地不可同时为空
		if (Common.isEmpty(tPreDispatchInfo.getPensionAddress())
				&& Common.isEmpty(tPreDispatchInfo.getFundAddress())
				&& CommonConstants.ZERO_STRING.equals(tPreDispatchInfo.getType())) {
			return "派增的养老数据和公积金数据不能同时为空,请完善！";
		}
		if (Common.isEmpty(tPreDispatchInfo.getPensionAddressReduce())
				&& Common.isEmpty(tPreDispatchInfo.getFundAddressReduce())
				&& CommonConstants.ONE_STRING.equals(tPreDispatchInfo.getType())) {
			return "派减的养老数据和公积金数据不能同时为空,请完善！";
		}
		return null;
	}

	private String checkAddPreDispatch(TPreDispatchInfo tPreDispatchInfo) {
		if (CommonConstants.ZERO_STRING.equals(tPreDispatchInfo.getType())) {
			if (Common.isEmpty(tPreDispatchInfo.getContractStart()) || Common.isEmpty(tPreDispatchInfo.getContractEnd())){
				return "派增的合同开始日期和合同终止日期不可为空！";
			}
			if (Common.isEmpty(tPreDispatchInfo.getTelTwo())){
				return PreDispatchConstants.TEL_NOT_EMPTY;
			}
			if (Common.isEmpty(tPreDispatchInfo.getPensionAddress()) &&
					Common.isEmpty(tPreDispatchInfo.getFundAddress())) {
				return PreDispatchConstants.NO_SOCIAL_FUND_ADDRESS_ADD;
			}
			// 派单按养老的基数缴纳地和起缴月来 其他险种只保存数据 不做数据校验
			if (Common.isNotNull(tPreDispatchInfo.getPensionAddress())) {
				if (Common.isEmpty(tPreDispatchInfo.getPensionStart())) {
					return "养老起缴月不可为空！";
				}
				if (Common.isNullOrZero(tPreDispatchInfo.getPensionBase())) {
					return "养老基数不可为空！";
				}
			}
			String x = checkFundForMod(tPreDispatchInfo);
			if (x != null) {
				return x;
			}
		}
		return null;
	}

	private String checkReducePreDispatch(TPreDispatchInfo tPreDispatchInfo) {
		if (CommonConstants.ONE_STRING.equals(tPreDispatchInfo.getType())) {
			if (Common.isEmpty(tPreDispatchInfo.getPensionAddressReduce()) &&
					Common.isEmpty(tPreDispatchInfo.getFundAddressReduce())) {
				return PreDispatchConstants.NO_SOCIAL_FUND_ADDRESS_REDUCE;
			}
			// 派单按养老的基数缴纳地和起缴月来 其他险种只保存数据 不做数据校验
			if (Common.isNotNull(tPreDispatchInfo.getPensionAddressReduce()) &&
					Common.isEmpty(tPreDispatchInfo.getPensionEndReduce())) {
				return "派减养老时间不可为空！";
			}
			if (Common.isNotNull(tPreDispatchInfo.getFundAddressReduce()) &&
					Common.isEmpty(tPreDispatchInfo.getFundEndReduce())) {
				return "派减公积金时间不可为空！";
			}
			if (Common.isNotNull(tPreDispatchInfo.getLeaveReason()) &&
					Common.isEmpty(tPreDispatchInfo.getLeaveReason())) {
				return "离职原因不可为空！";
			}
		}
		return null;
	}

	private String checkFundForMod(TPreDispatchInfo tPreDispatchInfo) {
		if (Common.isNotNull(tPreDispatchInfo.getFundAddress())) {
			if (Common.isEmpty(tPreDispatchInfo.getFundStart())) {
				return "公积金起缴月不可为空！";
			}
			if (Common.isNullOrZero(tPreDispatchInfo.getFundBase())) {
				return "公积金基数不可为空！";
			}
			if (Common.isNullOrZero(tPreDispatchInfo.getFundCompanyPer())) {
				return "公积金企业比例不可为空！";
			}
			if (Common.isNullOrZero(tPreDispatchInfo.getFundPersonalPer())) {
				return "公积个人比例不可为空！";
			}
		}
		return null;
	}

	/**
	 * 查看社保起缴日期是否符合补缴政策
	 *
	 * @param newEntity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private String checkSocialStartDate(TPreDispatchInfo newEntity, SysBaseSetInfo baseSetInfo) {
		// 社保确实要派增且时间有变动要判断是否符合派单政策
		if (null == baseSetInfo) {
			return PreDispatchConstants.NO_SOCIAL_BASE_SET_INFO;
		}
		// 查看是否符合社保补缴政策
		if (checkDispatchDate(
				LocalDateTimeUtils.dateOfYearAndMonth(newEntity.getPensionStart(), DateUtil.ISO_DATE_FORMAT),
				baseSetInfo.getCanOverpay(), baseSetInfo.getOverpayNumber(), baseSetInfo.getHaveThisMonth())) {
			return PreDispatchConstants.SOCIAL_START_DATE_ERROR;
		}
		return null;
	}

	/**
	 * 查看社保起缴日期是否符合补缴政策
	 *
	 * @param newEntity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> checkSocialStartDate(TPreDispatchInfo newEntity, TPreDispatchInfo oldEntity) {
		// 社保确实要派增且时间有变动要判断是否符合派单政策
		if (Common.isNotNull(newEntity.getPensionAddress()) &&
				Common.isNotNull(newEntity.getPensionStart()) &&
				!newEntity.getPensionStart().equals(oldEntity.getPensionStart())) {
			SysBaseSetInfo baseSetSocial = null;
			if (null != newEntity.getSocialProvince()) {
				baseSetSocial = getSysBaseSetInfo(newEntity.getSocialProvince(), newEntity.getSocialCity(),
						newEntity.getSocialTown(), oldEntity.getSocialHouseAdd(), CommonConstants.ZERO_STRING);
			} else {
				baseSetSocial = getSysBaseSetInfo(oldEntity.getSocialProvince(), oldEntity.getSocialCity(),
						oldEntity.getSocialTown(), oldEntity.getSocialHouseAdd(), CommonConstants.ZERO_STRING);
			}
			if (null == baseSetSocial) {
				return R.failed(PreDispatchConstants.NO_SOCIAL_BASE_SET_INFO);
			}
			// 查看是否符合社保补缴政策
			if (checkDispatchDate(
					LocalDateTimeUtils.dateOfYearAndMonth(newEntity.getPensionStart(), DateUtil.ISO_DATE_FORMAT),
					baseSetSocial.getCanOverpay(), baseSetSocial.getOverpayNumber(), baseSetSocial.getHaveThisMonth())) {
				return R.failed(PreDispatchConstants.SOCIAL_START_DATE_ERROR);
			}
		}
		return null;
	}

	/**
	 * 查看社保公积金起缴日期是否符合补缴逻辑
	 *
	 * @param socialStartDate 起缴日期
	 * @param canOverpay      是否可补缴 0：是，1：否
	 * @param overpayNumber   补缴期限 整数
	 * @param haveThisMonth   是否含当月 0：是，1：否   如果无符合条件默认不含当月
	 * @return 符合 false  不符合 true
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	public static boolean checkDispatchDate(LocalDateTime socialStartDate, String canOverpay, Integer overpayNumber, String haveThisMonth) {
		if (null == socialStartDate) {
			return false;
		}
		LocalDateTime temp = null;
		LocalDateTime now = LocalDateTime.now();
		if (CommonConstants.ZERO_STRING.equals(canOverpay)) {
			temp = socialStartDate.plusMonths(CommonConstants.ZERO_STRING.equals(haveThisMonth) ? (long) overpayNumber : (long) (overpayNumber + 1));
		} else if (CommonConstants.ONE_STRING.equals(canOverpay)) {
			temp = socialStartDate;
		}
		return (null != temp && (temp.getYear() < now.getYear() || isaBoolean(temp, now)));
	}

	/**
	 * 0 个人辞职 = 合同主动解除  1单位辞退 = 合同被动解除  15  死亡 = 死亡  19 其他
	 *
	 * @param tPreDispatchInfo
	 * @return
	 * @Author fxj
	 * @Date 2021-01-07
	 **/
	private void initLeaveReason(TPreDispatchInfo tPreDispatchInfo) {
		if ("合同主动解除".equals(tPreDispatchInfo.getLeaveReason())) {
			tPreDispatchInfo.setLeaveReasonAdd(CommonConstants.ZERO_STRING);
		} else if ("合同被动解除".equals(tPreDispatchInfo.getLeaveReason())) {
			tPreDispatchInfo.setLeaveReasonAdd(CommonConstants.ONE_STRING);
		} else if ("死亡".equals(tPreDispatchInfo.getLeaveReason())) {
			tPreDispatchInfo.setLeaveReasonAdd(CommonConstants.FIFTEEN);
		} else {
			tPreDispatchInfo.setLeaveReasonAdd(CommonConstants.NINETEEN);
		}
	}

	private SysBaseSetInfo getSysBaseSetInfo(String province, String city, String town, String houseId, String type) {
		SysBaseSetInfo queryEntity = new SysBaseSetInfo();
		queryEntity.setBaseType(type);
		queryEntity.setStatus(CommonConstants.ZERO_INT);
		queryEntity.setDepartId(houseId);
		if (Common.isNotNull(province)) {
			queryEntity.setProvince(Integer.valueOf(province));
		}
		if (Common.isNotNull(city)) {
			queryEntity.setCity(Integer.valueOf(city));
		}
		if (Common.isNotNull(town)) {
			queryEntity.setTown(Integer.valueOf(town));
		}
		queryEntity.setDeleteFlag(CommonConstants.ZERO_STRING);
		QueryWrapper<SysBaseSetInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.setEntity(queryEntity);
		if (Common.isEmpty(city)) {
			queryWrapper.isNull(PreDispatchConstants.CITY);
		}
		if (Common.isEmpty(town)) {
			queryWrapper.isNull(PreDispatchConstants.TOWN);
		}
		queryWrapper.last(CommonConstants.LAST_ONE_SQL);
		return sysBaseSetInfoMapper.selectOne(queryWrapper);
	}

	/**
	 * 重新获取公积金缴纳地数据
	 *
	 * @param areaMap
	 * @param areaIdMap
	 * @param newEntity
	 * @param oldEntity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> handleFundArea(Map<String, SysArea> areaMap,
									  Map<String, SysArea> areaIdMap, TPreDispatchInfo newEntity, TPreDispatchInfo oldEntity) {
		// 为空由更新语句清空缴纳地  不为空且有变化的要重新获取数据
		if (Common.isNotNull(newEntity.getFundAddress()) &&
				(!newEntity.getFundAddress().equals(oldEntity.getFundAddress())
						|| null == oldEntity.getFundProvince())) {
			return initFundArea(areaMap, areaIdMap, newEntity, newEntity.getFundAddress());
		}
		if (Common.isNotNull(newEntity.getFundAddressReduce()) &&
				(!newEntity.getFundAddressReduce().equals(oldEntity.getFundAddressReduce())
						|| null == oldEntity.getFundProvince())) {
			return initFundArea(areaMap, areaIdMap, newEntity, newEntity.getFundAddressReduce());
		}
		return null;
	}

	private R<Boolean> initFundArea(Map<String, SysArea> areaMap,
									Map<String, SysArea> areaIdMap, TPreDispatchInfo entity, String address) {
		SysArea area = areaMap.get(address);
		SysArea areaTemp;
		if (null != area) {
			// 处理省数据
			if (null == area.getParentId() || CommonConstants.ZERO_INT == area.getParentId().intValue()) {
				entity.setFundProvince(area.getId().toString());
				entity.setFundCity(null);
				entity.setFundTown(null);
				return null;
			}
			areaTemp = areaIdMap.get(Integer.toString(area.getParentId()));
			// 处理市县数据
			if (handleFundAreaSub(entity, area, areaTemp)) {
				return R.failed(getAreaErrorInfo(entity.getType()));
			}

		} else {
			return R.failed(getAreaErrorInfo(entity.getType()));
		}
		return null;
	}

	/**
	 * 获取公积金市县 数据
	 *
	 * @param newEntity
	 * @param area
	 * @param areaTemp
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean handleFundAreaSub(TPreDispatchInfo newEntity, SysArea area, SysArea areaTemp) {
		if (null != areaTemp) {
			if (null == areaTemp.getParentId() || CommonConstants.ZERO_INT == areaTemp.getParentId().intValue()) {
				newEntity.setFundProvince(areaTemp.getId().toString());
				newEntity.setFundCity(area.getId().toString());
				newEntity.setFundTown(null);
			} else {
				newEntity.setFundProvince(areaTemp.getParentId().toString());
				newEntity.setFundCity(areaTemp.getId().toString());
				newEntity.setFundTown(area.getId().toString());
			}
		} else {
			return true;
		}
		return false;
	}

	private String getAreaErrorInfo(String type) {
		if (CommonConstants.ZERO_STRING.equals(type)) {
			return PreDispatchConstants.NO_PENSION_AREA_ADD;
		}
		if (CommonConstants.ONE_STRING.equals(type)) {
			return PreDispatchConstants.NO_PENSION_AREA_REDUCE;
		}
		return CommonConstants.EMPTY_STRING;
	}

	/**
	 * 重新获取社保缴纳地
	 *
	 * @param areaMap
	 * @param newEntity
	 * @param oldEntity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> handleSocialArea(Map<String, SysArea> areaMap, Map<String, SysArea> areaIdMap,
										TPreDispatchInfo newEntity, TPreDispatchInfo oldEntity) {
		// 为空由更新语句清空缴纳地  不为空且有变化的要重新获取数据 不为空且不相等 更新缴纳地
		if (Common.isNotNull(newEntity.getPensionAddress()) &&
				(!newEntity.getPensionAddress().equals(oldEntity.getPensionAddress())
						|| null == oldEntity.getSocialProvince())) {
			return initSocialArea(areaMap, areaIdMap, newEntity, newEntity.getPensionAddress());
		}
		//  处理派减 不为空且不相等 更新缴纳地
		if (Common.isNotNull(newEntity.getPensionAddressReduce()) &&
				(!newEntity.getPensionAddressReduce().equals(oldEntity.getPensionAddressReduce())
						|| null == oldEntity.getSocialProvince())) {
			return initSocialArea(areaMap, areaIdMap, newEntity, newEntity.getPensionAddressReduce());
		}
		return null;
	}

	private R<Boolean> initSocialArea(Map<String, SysArea> areaMap,
									  Map<String, SysArea> areaIdMap, TPreDispatchInfo entity, String address) {
		SysArea area = areaMap.get(address);
		SysArea areaTemp;
		if (null != area) {
			// 处理省数据
			if (null == area.getParentId() || CommonConstants.ZERO_INT == area.getParentId().intValue()) {
				entity.setSocialProvince(area.getId().toString());
				entity.setSocialCity(null);
				entity.setSocialTown(null);
				return null;
			}
			areaTemp = areaIdMap.get(Integer.toString(area.getParentId()));
			// 处理市县数据
			if (handleSocialAreaSub(entity, area, areaTemp)) {
				return R.failed(getAreaErrorInfo(entity.getType()));
			}
		} else {
			return R.failed(getAreaErrorInfo(entity.getType()));
		}
		return null;
	}

	/**
	 * 获取社保市县 数据
	 *
	 * @param newEntity
	 * @param area
	 * @param areaTemp
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean handleSocialAreaSub(TPreDispatchInfo newEntity, SysArea area, SysArea areaTemp) {
		if (null != areaTemp) {
			if (null == areaTemp.getParentId() || CommonConstants.ZERO_INT == areaTemp.getParentId().intValue()) {
				newEntity.setSocialProvince(areaTemp.getId().toString());
				newEntity.setSocialCity(area.getId().toString());
				newEntity.setSocialTown(null);
			} else {
				newEntity.setSocialProvince(areaTemp.getParentId().toString());
				newEntity.setSocialCity(areaTemp.getId().toString());
				newEntity.setSocialTown(area.getId().toString());
			}
		} else {
			return true;
		}
		return false;
	}

	/**
	 * 验证数据完整性
	 *
	 * @param listInfo
	 * @param errorList
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean dataCheck(List<TPreDispatchInfo> listInfo, List<ErrorMessage> errorList,
							  Map<String, SysArea> areaHashMap,
							  Map<String, SysArea> areaIdMap) {
		return dataCheckSub(listInfo, errorList, areaHashMap, areaIdMap);
	}

	private boolean dataCheckDepart(List<ErrorMessage> errorList, R<TSettleDomainSelectVo> domainR) {
		if (null == domainR || null == domainR.getData()) {
			errorList.add(new ErrorMessage(-1, "访问员工基础服务异常："));
			return true;
		}
		return false;
	}

	/**
	 * 初始化区域 及验证 待处理数据是否空
	 *
	 * @param listInfo
	 * @param errorList
	 * @param areaHashMap
	 * @param areaIdMap
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean dataCheckSub(List<TPreDispatchInfo> listInfo, List<ErrorMessage> errorList,
								 Map<String, SysArea> areaHashMap, Map<String, SysArea> areaIdMap) {
		if (null == listInfo || listInfo.isEmpty()) {
			errorList.add(new ErrorMessage(-1, CommonConstants.DATA_CAN_NOT_EMPTY));
			return true;
		}

		R<AreaVo> areaListR = upmsDaprUtils.getAreaListR();
		if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
			errorList.add(new ErrorMessage(-1, PreDispatchConstants.GET_AREA_INFO));
			return true;
		}
		// 封装区域MAP数据
		initAreaMap(areaHashMap, areaIdMap, areaListR);
		return false;
	}

	/**
	 * 派增验重
	 *
	 * @param errorList
	 * @param existsMap
	 * @param i
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean checkAddRepeat(List<ErrorMessage> errorList, HashMap<String, TPreDispatchInfo> existsMap, int i, TPreDispatchInfo info) {
		TPreDispatchInfo exists;
		exists = existsMap.get(info.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + info.getPayAddress());
		if (null != exists) {
			errorList.add(new ErrorMessage(i, PreDispatchConstants.EXISTS_SAME_EMPIDCARD_ADD));
			return true;
		}
		return false;
	}

	/**
	 * 一大波校验 有问题的标记派单
	 *
	 * @param info
	 * @param type 0 派增校验  1  派减校验
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private String checkBatchSave(TPreDispatchInfo info, String type) {
		String res = null;
		res = updateOrSaveBaseCheck(info);
		// 姓名  身份证  缴费地 必填验证 有问题标记异常
		if (res != null) {
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(res);
			return res;
		}
		if (CommonConstants.ZERO_STRING.equals(type)) {
			// 派增验证
			res = checkAddPreDispatch(info);
			if (res != null) {
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent(res);
				return res;
			}
		}
		if (CommonConstants.ONE_STRING.equals(type)) {
			// 派减验证
			res = checkReducePreDispatch(info);
			if (res != null) {
				info.setPreStatus(CommonConstants.ONE_STRING);
				info.setExceptionContent(res);
				return res;
			}
		}
		return null;
	}

	private void initBatchAreaAdd(HashMap<String, SysArea> areaHashMap, HashMap<String, SysArea> areaIdMap, TPreDispatchInfo info) {
		R<Boolean> x;
		x = handleSocialAreaAdd(areaHashMap, areaIdMap, info, info.getPensionAddress());
		if (null != x) {
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(x.getMsg());
			return;
		}
		x = handleFundAreaAdd(areaHashMap, areaIdMap, info, info.getFundAddress());
		if (null != x) {
			info.setPreStatus(CommonConstants.ONE_STRING);
			info.setExceptionContent(x.getMsg());
		}
	}

	/**
	 * 批量新增 区域数据封装
	 *
	 * @param areaMap
	 * @param areaIdMap
	 * @param entity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> handleSocialAreaAdd(Map<String, SysArea> areaMap,
										   Map<String, SysArea> areaIdMap, TPreDispatchInfo entity, String address) {
		// 为空由更新语句清空缴纳地  不为空且有变化的要重新获取数据
		if (Common.isNotNull(address)) {
			return initSocialArea(areaMap, areaIdMap, entity, address.trim());
		}
		return null;
	}

	/**
	 * 处理公积金的地市数据
	 *
	 * @param areaMap
	 * @param areaIdMap
	 * @param entity
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> handleFundAreaAdd(Map<String, SysArea> areaMap,
										 Map<String, SysArea> areaIdMap, TPreDispatchInfo entity, String address) {
		// 为空由更新语句清空缴纳地  不为空且有变化的要重新获取数据
		if (Common.isNotNull(address)) {
			return initFundArea(areaMap, areaIdMap, entity, address.trim());
		}
		return null;
	}

	/**
	 * 初始化地市派单日
	 *
	 * @param dayConfMap
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initDayLimit(HashMap<String, Integer> dayConfMap, TPreDispatchInfo info) {
		if (Common.isNotNull(info.getSocialProvince())) {
			info.setDayLimit(dayConfMap.get(Common.isBlankToNullString(info.getSocialProvince()) +
					CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getSocialCity()) +
					CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getSocialTown())));
		} else if (Common.isNotNull(info.getFundProvince())) {
			info.setDayLimit(dayConfMap.get(Common.isBlankToNullString(info.getFundProvince()) +
					CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getFundCity()) +
					CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getFundTown())));
		}
	}

	/**
	 * 检查缴纳地对应的补缴时间是否合法
	 *
	 * @param baseSocialSetMap
	 * @param baseFundSetMap
	 * @param temp
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void checkStartTime(Map<String, SysBaseSetInfo> baseSocialSetMap,
								Map<String, SysBaseSetInfo> baseFundSetMap,
								TPreDispatchInfo temp, TPreDispatchInfo info) {
		if (CommonConstants.ZERO_STRING.equals(info.getType())) {
			//  社保地址或缴纳时间变更 要重新校验
			checkSocialStartTime(baseSocialSetMap, temp, info);
			// 公积金缴纳地或缴纳时间变更  要重新校验
			checkFundStartTime(baseFundSetMap, temp, info);
		}
	}

	/**
	 * 校验社保起缴时间
	 *
	 * @param baseSocialSetMap
	 * @param temp
	 * @param info
	 * @Author huyc
	 * @Date 2022-07-18
	 */
	private void checkSocialStartTime(Map<String, SysBaseSetInfo> baseSocialSetMap, TPreDispatchInfo temp, TPreDispatchInfo info) {
		boolean flag;
		LocalDateTime dateTime;
		SysBaseSetInfo socialBaseSetInfo;
		String str;
		flag = Common.isNotNull(info.getPensionAddress()) &&
				Common.isNotNull(info.getPensionStart()) &&
				Common.isNotNull(baseSocialSetMap);
		if (null != temp) {
			flag = flag && (!info.getPensionAddress().equals(temp.getPensionAddress()) ||
					!info.getPensionStart().equals(temp.getPensionStart()));
		}
		if (flag) {
			dateTime = LocalDateTimeUtils.dateOfYearAndMonth(info.getPensionStart(), LocalDateTimeUtils.DATE_SHORT_PATTERN);
			if (null != dateTime) {
				socialBaseSetInfo = baseSocialSetMap.get(LocalDateTimeUtils.formatTime(dateTime, ValidityConstants.DATEFORMAT3_PATTERN)
						+ CommonConstants.DOWN_LINE_STRING + info.getSocialHouseAdd()
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getSocialProvince())
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getSocialCity())
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getSocialTown()));
				str = checkSocialStartDate(info, socialBaseSetInfo);
				if (null != str) {
					info.setPreStatus(CommonConstants.ONE_STRING);
					info.setExceptionContent(str);
				}
			}
		}
	}

	/**
	 * 公积金缴纳地或缴纳时间变更要重新校验
	 *
	 * @param baseFundSetMap
	 * @param temp
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void checkFundStartTime(Map<String, SysBaseSetInfo> baseFundSetMap, TPreDispatchInfo temp, TPreDispatchInfo info) {
		boolean flag;
		LocalDateTime dateTime;
		SysBaseSetInfo fundBaseSetIfno;
		String str;
		flag = Common.isNotNull(info.getFundStart()) &&
				Common.isNotNull(info.getFundAddress()) &&
				Common.isNotNull(baseFundSetMap);
		if (null != temp) {
			flag = flag && (!info.getFundAddress().equals(temp.getFundAddress()) ||
					!info.getFundStart().equals(temp.getFundStart()));
		}
		if (flag) {
			dateTime = LocalDateTimeUtils.dateOfYearAndMonth(info.getFundStart(), LocalDateTimeUtils.DATE_SHORT_PATTERN);
			if (null != dateTime) {
				fundBaseSetIfno = baseFundSetMap.get(LocalDateTimeUtils.formatTime(dateTime, ValidityConstants.DATEFORMAT3_PATTERN)
						+ CommonConstants.DOWN_LINE_STRING + info.getFundHouseAdd()
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getFundProvince())
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getFundCity())
						+ CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(info.getFundTown()));
				str = checkFundStartDate(info, fundBaseSetIfno);
				if (null != str) {
					info.setPreStatus(CommonConstants.ONE_STRING);
					info.setExceptionContent(str);
				}
			}
		}
	}

	/**
	 * 通过身份证+派单类型 确定是否唯一（创建时间为当月的）
	 *
	 * @param listInfo
	 * @param existsMap
	 * @param type      0 派增  1 派减
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initExistsMapByIdCards(List<TPreDispatchInfo> listInfo,
										Map<String, TPreDispatchInfo> existsMap, String type) {
		List<String> idcards = new ArrayList<>();
		if (Common.isNotNull(listInfo)) {
			for (TPreDispatchInfo info : listInfo) {
				idcards.add(info.getEmpIdcard());
			}
		}
		// 初始化要更新的数据MAP
		initExistsMapByIdCards(existsMap, idcards, type);
	}

	private void initDayConfMap(HashMap<String, Integer> dayConfMap) {
		List<TDispatchDayConf> dayConfList = dispatchDayConfMapper.selectList(Wrappers.<TDispatchDayConf>query().lambda());
		if (Common.isNotNull(dayConfList)) {
			for (TDispatchDayConf conf : dayConfList) {
				dayConfMap.put(Common.isBlankToNullString(conf.getProvince()) +
						CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(conf.getCity()) +
						CommonConstants.DOWN_LINE_STRING + Common.isBlankToNullString(conf.getTown()), conf.getDay());

			}
		}
	}

	private void initExistsMapByIdCards(Map<String, TPreDispatchInfo> existsMap, List<String> idcards, String type) {
		if (Common.isNotNull(idcards)) {
			List<TPreDispatchInfo> preDispatchInfoList = baseMapper.selectList(Wrappers.<TPreDispatchInfo>query()
					.lambda().in(TPreDispatchInfo::getEmpIdcard, idcards)
					.eq(TPreDispatchInfo::getStatus, CommonConstants.ZERO_STRING)
					.ne(TPreDispatchInfo::getPreStatus, CommonConstants.TWO_STRING)
					.eq(TPreDispatchInfo::getType, type)
					.ge(TPreDispatchInfo::getCreateTime, LocalDateTimeUtils.firstdayOfMonth(LocalDateTime.now())));
			if (Common.isNotNull(preDispatchInfoList)) {
				for (TPreDispatchInfo info : preDispatchInfoList) {
					existsMap.put(info.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + info.getPayAddress(), info);
				}
			}
		}
	}

	/**
	 * map数据封装
	 *
	 * @param settleDomainList
	 * @param settleDomainNameMap
	 * @param customerNameMap
	 * @param settleIdAndCustomerIdMap
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initSettleDomainMaps(List<TSettleDomainSelectVo> settleDomainList,
									  Map<String, String> settleDomainNameMap,
									  Map<String, String> customerNameMap,
									  Map<String, String> settleIdAndCustomerIdMap) {
			//map数据封装
			if (Common.isNotNull(settleDomainList)) {
				for (TSettleDomainSelectVo settleDomainSelectVo : settleDomainList) {
					settleDomainNameMap.put(settleDomainSelectVo.getId(), settleDomainSelectVo.getDepartName());
					settleIdAndCustomerIdMap.put(settleDomainSelectVo.getId(), settleDomainSelectVo.getCustomerId());
					if (!customerNameMap.containsKey(settleDomainSelectVo.getCustomerName())) {
						customerNameMap.put(settleDomainSelectVo.getCustomerId(), settleDomainSelectVo.getCustomerName());
					}
				}
			}
	}

	/**
	 * 初始化社保公积金基数
	 *
	 * @param listInfo
	 * @param baseSocialSetMap
	 * @param baseFundSetMap
	 * @param baseSocialTimeMap
	 * @param baseFundTimeMap
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initSocialAndFundBaseSet(List<TPreDispatchInfo> listInfo,
										  Map<String, SysBaseSetInfo> baseSocialSetMap,
										  Map<String, SysBaseSetInfo> baseFundSetMap,
										  Map<String, TPreDispatchInfo> baseSocialTimeMap,
										  Map<String, TPreDispatchInfo> baseFundTimeMap) {
		List<String> idList = new ArrayList<>();
		if (Common.isNotNull(listInfo)) {
			for (TPreDispatchInfo info : listInfo) {
				if (Common.isNotNull(info.getPensionStart())) {
					baseSocialTimeMap.put(info.getPensionStart(), info);
				}
				if (Common.isNotNull(info.getFundStart())) {
					baseFundTimeMap.put(info.getFundStart(), info);
				}
				idList.add(info.getId());
			}
		}
		// 初始化社保和公积金配置数据
		initBaseSetMap(baseSocialTimeMap, baseFundTimeMap, baseSocialSetMap, baseFundSetMap);
	}

	/**
	 * 初始化派减的相关状态及数据
	 *
	 * @param selectVo
	 * @param info
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initReduceBaseInfo(TSettleDomainSelectVo selectVo, TPreDispatchInfo info) {
		info.setDataSubStatus(CommonConstants.ONE_STRING);
		info.setStatus(CommonConstants.ZERO_STRING);
		info.setPreStatus(CommonConstants.ZERO_STRING);
		info.setType(CommonConstants.ONE_STRING);
		// 默认社保代理 4
		info.setEmpTypeAdd(CommonConstants.FOUR_STRING);
		info.setPositionAdd(PreDispatchConstants.POSITION);
		// 0 个人辞职 = 合同主动解除  1单位辞退 = 合同被动解除  15  死亡 = 死亡  19 其他
		initLeaveReason(info);
		// 默认社保代理 4
		if (null != selectVo) {
			info.setDepartIdAdd(selectVo.getId());
			info.setDepartNameAdd(selectVo.getDepartName());
			info.setUnitIdAdd(selectVo.getCustomerId());
			info.setUnitNameAdd(selectVo.getCustomerName());
		}
	}

	private void getPreAddMap(HashMap<String, String> preAddMap) {
		List<TPreDispatchInfo> preList = baseMapper.selectList(Wrappers.<TPreDispatchInfo>query().lambda()
				.le(TPreDispatchInfo::getCreateTime, LocalDateTime.now())
				.eq(TPreDispatchInfo::getType, CommonConstants.ZERO_STRING)
				.eq(TPreDispatchInfo::getStatus, CommonConstants.ZERO_STRING)
				.and(obj -> obj
						.eq(TPreDispatchInfo::getPreStatus, CommonConstants.ZERO_STRING)
						.or()
						.eq(TPreDispatchInfo::getPreStatus, CommonConstants.ONE_STRING))
		);
		if (Common.isNotNull(preList)) {
			for (TPreDispatchInfo info : preList) {
				preAddMap.put(info.getEmpIdcard(), info.getEmpIdcard());
			}
		}
	}

	/**
	 * 封装需要派减的社保或公积金信息
	 *
	 * @param preList
	 * @param socialMap
	 * @param fundMap
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initReduceSocialFundInfo(List<TPreDispatchInfo> preList, HashMap<String, TSocialInfo> socialMap, HashMap<String, TProvidentFund> fundMap) {
		List<String> socialReduceCards = new ArrayList<>();
		List<String> fundReduceCards = new ArrayList<>();
		// 初始化社保公积金
		initReduceInfo(preList, socialReduceCards, fundReduceCards);
		List<TSocialInfo> socialInfoList = null;
		List<TProvidentFund> fundList = null;
		if (Common.isNotNull(socialReduceCards)) {
			socialInfoList = socialInfoMapper.selectList(Wrappers.<TSocialInfo>query().lambda()
					.eq(TSocialInfo::getAuditStatus, CommonConstants.ONE_STRING)
					.and(obj -> obj.eq(TSocialInfo::getHandleStatus, CommonConstants.ONE_STRING)
							.or().eq(TSocialInfo::getHandleStatus, CommonConstants.FIVE_STRING))
					.eq(TSocialInfo::getReduceCan, CommonConstants.ZERO_STRING)
					.eq(TSocialInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
					.in(TSocialInfo::getEmpIdcard, socialReduceCards));
		}
		if (Common.isNotNull(fundReduceCards)) {
			fundList = providentFundMapper.selectList(Wrappers.<TProvidentFund>query().lambda()
					.eq(TProvidentFund::getHandleStatus, CommonConstants.ONE_STRING)
					.eq(TProvidentFund::getReduceCan, CommonConstants.ZERO_STRING)
					.eq(TProvidentFund::getDeleteFlag, CommonConstants.ZERO_STRING)
					.in(TProvidentFund::getEmpIdcard, fundReduceCards));
		}
		if (Common.isNotNull(socialInfoList)) {
			for (TSocialInfo social : socialInfoList) {
				socialMap.put(social.getEmpIdcard(), social);
			}
		}
		if (Common.isNotNull(fundList)) {
			for (TProvidentFund fund : fundList) {
				fundMap.put(fund.getEmpIdcard(), fund);
			}
		}
	}

	/**
	 * 初始化社保公积金
	 *
	 * @param preList
	 * @param socialReduceCards
	 * @param fundReduceCards
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void initReduceInfo(List<TPreDispatchInfo> preList, List<String> socialReduceCards, List<String> fundReduceCards) {
		for (TPreDispatchInfo info : preList) {
			if (CommonConstants.ONE_STRING.equals(info.getType())) {
				if (Common.isNotNull(info.getPensionAddressReduce())) {
					socialReduceCards.add(info.getEmpIdcard());
				}
				if (Common.isNotNull(info.getFundAddressReduce())) {
					fundReduceCards.add(info.getEmpIdcard());
				}
			}
		}
	}

	/**
	 * 不需要派单的数据过滤
	 * @param pre
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private boolean checkLimit(TPreDispatchInfo pre) {
		//  当月创建的大于 限制日期的不派单 放在次月派单  本月之前的数据正常派单
		if (null != pre.getDayLimit() && pre.getCreateTime().getDayOfMonth() > pre.getDayLimit().intValue() &&
				LocalDateTime.now().getMonthValue() == pre.getCreateTime().getMonthValue()) {
			return true;
		}
		//  当派减时间为次月之后的月份 不做处理  放到次月及之后派单
		if (Common.isNotNull(pre.getFundEndReduce()) && checkMonthForReduce(pre.getFundEndReduce())) {
			return true;
		}
		return Common.isNotNull(pre.getPensionEndReduce()) && checkMonthForReduce(pre.getPensionEndReduce());
	}

	private boolean checkMonthForReduce(String value1) {
		try {
			return (Integer.parseInt(DateUtil.getYearAndMonth(value1, -1))) >
					Integer.parseInt((DateUtil.getYearAndMonth(LocalDateTime.now(), CommonConstants.ZERO_INT)));
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 重新组装数据
	 * @param pre
	 * @param errorMessageList
	 * @param errorMsgList
	 * @param i
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private void resetMessageList(TPreDispatchInfo pre,
								  List<ErrorMessage> errorMessageList,
								  List<ErrorMessage> errorMsgList, int i) {
		if (Common.isNotNull(errorMessageList)) {
			for (ErrorMessage errorMessage : errorMessageList) {
				errorMsgList.add(new ErrorMessage(i,
						pre.getEmpIdcard() +
								CommonConstants.COLON_STRING +
								errorMessage.getMessage()));
			}
		}
	}

	/**
	 * 处理派单结果
	 * @param preInfo
	 * @param errorMessageList
	 * @return
	 * @Author huyc
	 * @Date 2022-07-18
	 **/
	private R<Boolean> handleDispatchAddRes(TPreDispatchInfo preInfo, List<ErrorMessage> errorMessageList) {
		if (errorMessageList.size() > CommonConstants.ZERO_INT) {
			ErrorMessage errorMessage = errorMessageList.get(CommonConstants.ZERO_INT);
			if (null != errorMessage) {
				if (errorMessage.getMessage().indexOf(PreDispatchConstants.DISPATCH_ADD_SUCCESS) >= CommonConstants.ZERO_INT) {
					preInfo.setPreStatus(CommonConstants.TWO_STRING);
					preInfo.setExceptionContent(CommonConstants.EMPTY_STRING);
					baseMapper.updatePreStatusById(preInfo);
					return R.ok(null, preInfo.getEmpIdcard() +
							CommonConstants.COLON_STRING +
							PreDispatchConstants.DISPATCH_ADD_SUCCESS);
				} else {
					preInfo.setPreStatus(CommonConstants.ONE_STRING);
					preInfo.setExceptionContent(errorMessage.getMessage());
					baseMapper.updatePreStatusById(preInfo);
					return R.failed(preInfo.getEmpIdcard() +
							CommonConstants.COLON_STRING +
							errorMessage.getMessage());
				}
			}
		}
		return null;
	}

	private R<Boolean> handleBatchSocialFundReduce(TPreDispatchInfo preInfo,
												   TDispatchInfo dispatchInfo, TSocialInfo social, TProvidentFund fund) {
		if (Common.isEmpty(preInfo.getSocialProvince()) && Common.isEmpty(preInfo.getFundProvince())) {
			return R.failed("请检查派减缴纳地是否准确！");
		}
		if (Common.isNotNull(preInfo.getSocialProvince())) {
			if (null != social) {
				dispatchInfo.setSettleDomain(social.getSettleDomain());
				dispatchInfo.setBelongUnit(social.getBelongUnit());
			} else {
				preInfo.setPreStatus(CommonConstants.ONE_STRING);
				preInfo.setExceptionContent(PreDispatchConstants.NO_SOCIAL_CAN_REDUCE);
				baseMapper.updatePreStatusById(preInfo);
				return R.failed(PreDispatchConstants.NO_SOCIAL_CAN_REDUCE);
			}
		}
		if (Common.isNotNull(preInfo.getFundProvince())) {
			if (null != fund) {
				dispatchInfo.setSettleDomain(fund.getSettleDomain());
				dispatchInfo.setBelongUnit(fund.getBelongUnit());
			} else {
				preInfo.setPreStatus(CommonConstants.ONE_STRING);
				preInfo.setExceptionContent(PreDispatchConstants.NO_FUND_CAN_REDUCE);
				baseMapper.updatePreStatusById(preInfo);
				return R.failed(PreDispatchConstants.NO_FUND_CAN_REDUCE);
			}
		}
		return null;
	}

	/**
	 * 派减派单时间处理
	 * @param dispatchInfo
	 * @param pre
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private void dispatchReduce(TDispatchReduceVo dispatchInfo, TPreDispatchInfo pre) {
		if (Common.isNotNull(pre.getPensionEndReduce())) {
			dispatchInfo.setSocialReduceDate(DateUtil.getFirstDay(pre.getPensionEndReduce()));
		}
		if (Common.isNotNull(pre.getFundEndReduce())) {
			dispatchInfo.setFundReduceDate(DateUtil.getFirstDay(pre.getFundEndReduce()));
		}
		if (null != pre.getLeaveDate()) {
			dispatchInfo.setLeaveDate(DateUtil.stringToDate(pre.getLeaveDate()));
		}
	}

	/**
	 * 初始化派增的派单数据
	 * @param preInfo
	 * @param importVo
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private void initDispatchAddVo(TPreDispatchInfo preInfo, TDispatchImportVo importVo) {
		importVo.setEmpName(preInfo.getEmpName());
		importVo.setEmpIdcard(preInfo.getEmpIdcard());
		importVo.setEmpType(CommonConstants.TWO_STRING);
		importVo.setEmpMobile(preInfo.getTelTwo());
		importVo.setCustomerId(preInfo.getUnitIdAdd());
		importVo.setCustomerCode(preInfo.getUnitNameAdd());
		importVo.setSettleDomainId(preInfo.getDepartIdAdd());
		importVo.setIdCardAddress(preInfo.getPayAddress());
		importVo.setPost(preInfo.getPositionAdd());
		importVo.setWorkingHours(preInfo.getWorkingHoursAdd());
		importVo.setEmpNational(CommonConstants.ONE_STRING);
		importVo.setEducationName(CommonConstants.FIVE_STRING);
		if (null != preInfo.getPensionBase()){
			importVo.setRecordBase(preInfo.getPensionBase());
		}
		// 封装合同信息
		initDispatchContractVo(preInfo, importVo);
		// 封装社保派单信息
		if (Common.isNotNull(preInfo.getSocialHouseAdd()) &&
				Common.isNotNull(preInfo.getSocialProvince()) &&
				Common.isNotNull(preInfo.getPensionStart())){
			importVo.setPensionStart(DateUtil.getFirstDay(preInfo.getPensionStart()));
			if (Common.isNotNull(preInfo.getPensionAddress())){
				importVo.setSocialHousehold(preInfo.getSocialHouseAdd());
			}
			SysBaseSetInfo socialBaseSet = getSysBaseSetInfo(preInfo.getSocialProvince(),preInfo.getSocialCity(),
					preInfo.getSocialTown(),preInfo.getSocialHouseAdd(),CommonConstants.ZERO_STRING);
			// 初始化派单的社保基数
			initDispatchSocialBase(preInfo, importVo, socialBaseSet);
		}
		// 封装公积金派单信息
		initDispatchAddFund(preInfo, importVo);
	}

	private List<ErrorMessage> handleFileAddress(int i, TPreDispatchInfo pre,
												 HashMap<String, SysArea> areaMap,
												 HashMap<String, SysArea> areaIdMap,
												 TDispatchImportVo importVo,
												 List<ErrorMessage> errorMessageList) {
		SysArea area = areaMap.get(pre.getPayAddress());
		if (null == area || null == area.getParentId() || 0 == area.getParentId().intValue()){
			errorMessageList = new ArrayList<>();
			errorMessageList.add(new ErrorMessage(i+1,"缴费地址不存在或缴费地址不可为省！"));
		}else {
			SysArea areaParent = areaIdMap.get(area.getParentId());
			if (null != areaParent && null != areaParent.getParentId() && 0 != areaParent.getParentId().intValue()) {
				importVo.setFileProvince(areaParent.getParentId().toString());
				importVo.setFileCity(areaParent.getId().toString());
				importVo.setFileTown(area.getId().toString());
			}else {
				importVo.setFileProvince(area.getParentId().toString());
				importVo.setFileCity(area.getId().toString());
				importVo.setFileTown(null);
			}
		}
		return errorMessageList;
	}

	/**
	 * 封装合同信息
	 * @param preInfo
	 * @param importVo
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	private void initDispatchContractVo(TPreDispatchInfo preInfo, TDispatchImportVo importVo) {
		if (Common.isNotNull(preInfo.getContractNameAdd())){
			importVo.setContractName(preInfo.getContractTypeAdd());
			if (Common.isNotNull(preInfo.getContractStartAdd())){
				importVo.setContractStart(DateUtil.stringToDate(ServiceUtil.
						replaceSeparator(preInfo.getContractStartAdd(),CommonConstants.CENTER_SPLIT_LINE_STRING,
								CommonConstants.SLASH_SPLIT_LINE_STRING), DateUtil.ISO_DATE_FORMAT));
			}
			if (Common.isNotNull(preInfo.getContractEndAdd())){
				importVo.setContractEnd(DateUtil.stringToDate(ServiceUtil.
						replaceSeparator(preInfo.getContractEndAdd(), CommonConstants.CENTER_SPLIT_LINE_STRING,
								CommonConstants.SLASH_SPLIT_LINE_STRING), DateUtil.ISO_DATE_FORMAT));
			}
			importVo.setContractTerm(preInfo.getContractTermAdd());
			importVo.setContractType(CommonConstants.ONE_STRING);
			importVo.setContractSubName(PreDispatchConstants.CONTRACT_NAME);
		}
	}

	/**
	 * 初始化派单的社保基数
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param preInfo
	 * @param importVo
	 * @param socialBaseSet
	 * @return
	 **/
	private void initDispatchSocialBase(TPreDispatchInfo preInfo, TDispatchImportVo importVo, SysBaseSetInfo socialBaseSet) {
		if (Common.isNotNull(preInfo.getSocialProvince())){
			importVo.setFileProvince(preInfo.getSocialProvince());
			importVo.setIdCardProvince(preInfo.getSocialProvince());
		}
		if (Common.isNotNull(preInfo.getSocialCity())){
			importVo.setFileCity(preInfo.getSocialCity());
			importVo.setIdCardCity(preInfo.getSocialCity());
		}
		if (Common.isNotNull(preInfo.getSocialTown())){
			importVo.setFileTown(preInfo.getSocialTown());
			importVo.setIdCardTown(preInfo.getSocialTown());
		}
		if (null != socialBaseSet){
			// 最低
			if (socialBaseSet.getLowerLimit().compareTo(Common.isBlankToBigDecimalZero(preInfo.getPensionBase())) ==
					CommonConstants.ZERO_INT){
				importVo.setPaymentType(CommonConstants.ZERO_STRING);
				// 最高
			}else if (socialBaseSet.getUpperLimit().compareTo(Common.isBlankToBigDecimalZero(preInfo.getPensionBase())) ==
					CommonConstants.ZERO_INT){
				importVo.setPaymentType(CommonConstants.TWO_STRING);
			}else {
				importVo.setPaymentType(CommonConstants.ONE_STRING);
			}
		}else {
			importVo.setPaymentType(CommonConstants.ONE_STRING);
		}
		// 自定义
		importVo.setPaymentType(CommonConstants.ONE_STRING);
		importVo.setPensionCardinal(preInfo.getPensionBase());
		importVo.setMedicalCardinal(preInfo.getPensionBase());
		importVo.setUnemploymentCardinal(preInfo.getPensionBase());
		importVo.setWorkInjuryCardinal(preInfo.getPensionBase());
		importVo.setBirthCardinal(preInfo.getPensionBase());
		importVo.setBigailmentCardinal(preInfo.getPensionBase());
	}

	/**
	 * 封装公积金派单信息
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param preInfo
	 * @param importVo
	 * @return
	 **/
	private void initDispatchAddFund(TPreDispatchInfo preInfo, TDispatchImportVo importVo) {
		if (Common.isNotNull(preInfo.getFundStart())){
			importVo.setProvidentStart(DateUtil.getFirstDay(preInfo.getFundStart()));
		}
		if (Common.isNotNull(preInfo.getFundBase())){
			importVo.setProvidentCardinal(preInfo.getFundBase());
			importVo.setProvidentPer(preInfo.getFundPersonalPer());
		}
		if (Common.isNotNull(preInfo.getFundAddress())){
			importVo.setProvidentHousehold(preInfo.getFundHouseAdd());
		}
	}

	/**
	 * 批量派单派增处理
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param settleDomainNameMap
	 * @param customerNameMap
	 * @param settleIdAndCustomerIdMap
	 * @param user
	 * @param errorMsgList
	 * @param i
	 * @param pre
	 * @param areaMap
	 * @param areaIdMap
	 * @return
	 **/
	private void batchDispatchAdd(Map<String, String> settleDomainNameMap, Map<String, String> customerNameMap,
								  Map<String, String> settleIdAndCustomerIdMap, YifuUser user,
								  List<ErrorMessage> errorMsgList, int i, TPreDispatchInfo pre,
								  HashMap<String, SysArea> areaMap,
								  HashMap<String, SysArea> areaIdMap) {
		TDispatchImportVo importVo;
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		if (null != pre && CommonConstants.ZERO_STRING.equals(pre.getType())){
			importVo = new TDispatchImportVo();
			//  初始化派增的派单数据
			initDispatchAddVo(pre, importVo);
			importVo.setRowIndex(i);
			List<TDispatchImportVo> importVoList = new ArrayList<>();
			importVoList.add(importVo);
			// 如果档案地市空  只能用缴纳地封装，如果缴纳地有问题直接返回
			if (null == importVo.getFileCity()){
				R<AreaVo> areaListR = upmsDaprUtils.getAreaListR();
				if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
					errorMessageList.add(new ErrorMessage(i+1,PreDispatchConstants.GET_AREA_INFO));
				}
				initAreaMap(areaMap, areaIdMap,areaListR);
				// 处理 档案地市
				errorMessageList = handleFileAddress(i, pre, areaMap, areaIdMap, importVo, errorMessageList);
			}
			//  档案地市没问题 开始派单处理
			if (!Common.isNotNull(errorMessageList)){
				dispatchInfoService.importTDispatchInfo(importVoList, errorMessageList, user);
			}
			//  处理派增结果
			handleDispatchAddRes(pre, errorMessageList);
			// 重新组装数据
			resetMessageList(pre, errorMessageList, errorMsgList, i+1);
		}
	}
}
