/*
 *    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.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.social.entity.*;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysBaseSetInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TDispatchInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialFundInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchImportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchInfoSearchVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

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

	private final ArchivesDaprUtil archivesDaprUtil;

	private final TSocialFundInfoMapper socialFundMapper;

	private final SysBaseSetInfoMapper baseSetMapper;

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

	/**
	 * 派单信息记录表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TDispatchInfoSearchVo searchVo) {
		String fileName = "不良记录批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TDispatchInfo> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			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, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
			ExcelWriter excelWriter = EasyExcel.write(out, TDispatchInfo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TDispatchInfo> util = new ExcelUtil<>(TDispatchInfo.class);
						for (TDispatchInfo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("派单信息记录表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("派单信息记录表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

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

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

	private LambdaQueryWrapper buildQueryWrapper(TDispatchInfoSearchVo entity) {
		LambdaQueryWrapper<TDispatchInfo> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TDispatchInfo::getCreateTime, entity.getCreateTimes()[0])
					.le(TDispatchInfo::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TDispatchInfo::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TDispatchImportVo> util1 = new ExcelUtil<>(TDispatchImportVo.class);
		;
		// 写法2：
		// 匿名内部类 不用额外写一个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);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	@GlobalTransactional
	private void importTDispatchInfo(List<TDispatchImportVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		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, String> settleDomainVo = new HashMap<>();
		// 获取所有社保户和公积金户数据
		Map<String, SysBaseSetInfo> socialHoldMap = new HashMap<>();
		Map<String, SysBaseSetInfo> fundHoldMap = new HashMap<>();
		initHoldInfo(socialholds, fundholds, socialHoldMap, fundHoldMap);
		// 员工档案
		List<EmpAddDispatchVo> empAdds = new ArrayList<>();
		//员工合同
		List<EmpContractDispatchVo> contracts = new ArrayList<>();
		//员工项目档案
		List<EmpProjectDispatchVo> projects = new ArrayList<>();
		//新增社保
		List<TSocialInfo> socials = new ArrayList<>();
		//新增公积金
		List<TProvidentFund> funds = new ArrayList<>();
		//新增派单信息
		Map<String,TDispatchInfo> dispatchMap = new HashMap<>();
		EmpAddDispatchVo emp;
		EmpContractDispatchVo contract;
		EmpProjectDispatchVo project;
		TSocialFundInfo sf;
		DispatchEmpVo empVo = null;
		TSocialInfo social;
		TProvidentFund fund;
		SysBaseSetInfo socialSet;
		SysBaseSetInfo fundSet;
		TDispatchInfo dispatch;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			socialSet = null;
			fundSet = null;
			TDispatchImportVo excel = excelVOList.get(i);
			// 数据合法情况
			if (validImport(errorMessageList, excel, dispatchMap)) {
				continue;
			}
			if (Common.isNotNull(excel.getSocialHousehold())){
				socialSet = socialHoldMap.get(excel.getSocialHousehold());
				if (Common.isEmpty(socialSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_HOLD_NOT_EXIST)));
					continue;
				}
			}
			if (Common.isNotNull(excel.getProvidentHousehold())){
				fundSet = fundHoldMap.get(excel.getProvidentHousehold());
				if (Common.isEmpty(fundSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_HOLD_NOT_EXIST)));
					continue;
				}
			}
			// 是否可以派单： 派单状态、兼职工伤处理
			if (validDdispatchStatus(errorMessageList, socialFundMap, excel)) {
				continue;
			}
			if (Common.isNotNull(empVoMap)) {
				empVo = empVoMap.get(excel.getEmpIdcard());
			}
			// 初始化新增信息：档案、项目档案、员工合同
			initAddInfo(empAdds, contracts, projects, empVo, excel);
			// 新增社保
			initSocialAddInfo(socials, empVo, socialSet, excel);
			// 新增公积金
			if (initFundAddInfo(errorMessageList, funds, empVo, fundSet, excel)){
				continue;
			}
			// 新增派单信息
			dispatch = new TDispatchInfo();
			dispatch.setEmpIdcard(excel.getEmpIdcard());
			dispatch.setEmpName(excel.getEmpName());
			dispatch.setEmpNational(excel.getEmpNational());
			dispatch.setEmpType(excel.getEmpType());
			dispatch.setEmpMobile(excel.getEmpMobile());
			dispatch.setStatus(CommonConstants.ONE_STRING);
			if (Common.isNotNull(empVo)){
				dispatch.setEmpId(empVo.getId());
				dispatch.setEmpNo(empVo.getEmpCode());
				//TODO
				dispatch.setSettleDomain(empVo.getDeptId());
				dispatch.setSettleDomainName(empVo.getDeptName());
			}
			dispatchMap.put(excel.getEmpIdcard(),dispatch);
			// 变更社保公积金查询

			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	private boolean initFundAddInfo(List<ErrorMessage> errorMessageList, List<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("");
			fund.setSettleDomain("");
			fund.setEmpId(empVo.getId());
			fund.setEmpIdcard(excel.getEmpIdcard());
			fund.setTrustRemark(excel.getTrustRemark());
			fund.setUnitProvidengCardinal(excel.getProvidentPer());
			fund.setPersonalProvidentPer(excel.getProvidentPer());
			fund.setUnitProvidengCardinal(excel.getProvidentCardinal());
			fund.setPersonalProvidentCardinal(excel.getProvidentCardinal());
			fund.setProvidentStart(excel.getProvidentStart());
			if (Common.isNotNull(fundSet)){
				if (!checkFundPer(fundSet.getFundProList(), excel)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_PERCENT_NOT_EXIST)));
					return true;
				}
				fund.setCanOverpay(fundSet.getCanOverpay());
				fund.setOverpayNumber(fundSet.getOverpayNumber());
				fund.setFundBaseSetId(fundSet.getId());
				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(fundSet.getPayPolicy());
				fund.setHaveThisMonth(fundSet.getHaveThisMonth());
			}
			funds.add(fund);
		}
		return false;
	}

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

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

	private void initSocialAddInfo(List<TSocialInfo> socials, DispatchEmpVo empVo, SysBaseSetInfo socialSet, TDispatchImportVo excel) {
		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);
			// TODO 封装单位信息 结算信息
			social.setBelongUnit("");
			social.setSettleDomain("");
			social.setEmpId(empVo.getId());
			social.setEmpIdcard(excel.getEmpIdcard());
			social.setBigailmentHandle(CommonConstants.ZERO_STRING);
			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());
			social.setPensionStart(excel.getPensionStart());
			social.setMedicalStart(ifNull(excel.getMedicalStart(), excel.getPensionStart()));
			social.setUnemployStart(ifNull(excel.getUnemployStart(), excel.getPensionStart()));
			social.setBigailmentStart(ifNull(excel.getBigailmentStart(), excel.getPensionStart()));
			social.setWorkInjuryStart(ifNull(excel.getWorkInjuryStart(), excel.getPensionStart()));
			social.setBirthStart(ifNull(excel.getBirthStart(), excel.getPensionStart()));
			if (CommonConstants.ONE_STRING.equals(excel.getPaymentType())){
				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.setPersonalPensionCardinal(excel.getPensionCardinal());
				social.setPersonalMedicalCardinal(ifNull(excel.getMedicalCardinal(), excel.getPensionCardinal()));
				social.setPersonalUnemploymentCardinal(ifNull(excel.getUnemploymentCardinal(), excel.getPensionCardinal()));
				social.setPersonalBigailmentCardinal(ifNull(excel.getBigailmentCardinal(), excel.getPensionCardinal()));

				social.setUnitPensionCardinal(excel.getPensionCardinal());
				social.setUnitMedicalCardinal(ifNull(excel.getMedicalCardinal(), excel.getPensionCardinal()));
				social.setUnitUnemploymentCardinal(ifNull(excel.getUnemploymentCardinal(), excel.getPensionCardinal()));
				social.setUnitWorkInjuryCardinal(ifNull(excel.getWorkInjuryCardinal(), excel.getPensionCardinal()));
				social.setUnitBigailmentCardinal(ifNull(excel.getBigailmentCardinal(), excel.getPensionCardinal()));
				social.setUnitBirthCardinal(ifNull(excel.getBirthCardinal(), excel.getPensionCardinal()));
			}
			// 获取到政策后封装相关数据
			if (Common.isNotNull(socialSet)){
				social.setCanOverpay(socialSet.getCanOverpay());
				social.setCardinalId(socialSet.getId());
				social.setSocialHousehold(socialSet.getId());
				social.setCollectMoth(socialSet.getCollectMoth());
				social.setCollectType(socialSet.getCollectType());
				social.setHaveThisMonth(socialSet.getHaveThisMonth());
				social.setInsuranceBigailment(socialSet.getInsuranceBigailment());
				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.setIsIllness(socialSet.getIsIllness());
				social.setOverpayNumber(socialSet.getOverpayNumber());
				social.setValueType(socialSet.getValueType());
				// 比例初始化
				social.setPersonalPensionPer(socialSet.getPersonalPersionPro());
				social.setPersonalMedicalPer(socialSet.getPersonalMedicalPro());
				social.setPersonalUnemploymentPer(socialSet.getPersonalUnemploymentPro());
				social.setPersonalBigailmentPer(socialSet.getPayPersonalPro());

				social.setUnitPensionPer(socialSet.getUnitPersionPro());
				social.setUnitMedicalPer(socialSet.getUnitMedicalPro());
				social.setUnitUnemploymentPer(socialSet.getUnitUnemploymentPro());
				social.setUnitWorkUnjuryPer(socialSet.getUnitInjuryPro());
				social.setUnitBigailmentPer(socialSet.getPayCompanyPro());
				social.setUnitBirthPer(socialSet.getUnitBirthPro());

				social.setUnitBigailmentMoney(socialSet.getPayCompany());
				social.setPersonalBigailmentMoney(socialSet.getPayPersonal());
				//按最低
				if (CommonConstants.ZERO_STRING.equals(excel.getPaymentType())){
					social.setPersonalPensionCardinal(socialSet.getLowerLimit());
					social.setPersonalMedicalCardinal(socialSet.getLowerLimit());
					social.setPersonalUnemploymentCardinal(socialSet.getLowerLimit());
					social.setPersonalBigailmentCardinal(socialSet.getLowerLimit());

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

					social.setUnitPensionCardinal(socialSet.getUpperLimit());
					social.setUnitMedicalCardinal(socialSet.getUpperLimit());
					social.setUnitUnemploymentCardinal(socialSet.getUpperLimit());
					social.setUnitWorkInjuryCardinal(socialSet.getUpperLimit());
					social.setUnitBigailmentCardinal(socialSet.getUpperLimit());
					social.setUnitBirthCardinal(socialSet.getUpperLimit());
				}
			}
			socials.add(social);
		}
	}

	private BigDecimal ifNull(BigDecimal old,BigDecimal last){
			if (Common.isEmpty(old)){
				return last;
			}
			return old;
	}
	private Date ifNull(Date old,Date last){
		if (Common.isEmpty(old)){
			return last;
		}
		return old;
	}

	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)
					.ge(SysBaseSetInfo::getApplyStartDate, now)
					.le(SysBaseSetInfo::getApplyEndDate, now)
					.eq(SysBaseSetInfo::getDeleteFlag, CommonConstants.ZERO_STRING));
			if (Common.isNotNull(socialBases)) {
				socialHoldMap = socialBases.stream().collect(Collectors.toMap(k -> k.getDepartName(), k -> k));
			}
			socialBases.clear();
		}
		if (Common.isNotNull(fundHolds)) {
			List<SysBaseSetInfo> fundBases = baseSetMapper.getFundBaseSet(fundHolds);
			if (Common.isNotNull(fundBases)) {
				fundHoldMap = fundBases.stream().collect(Collectors.toMap(k -> k.getDepartName(), k -> k));
			}
			fundBases.clear();
		}
	}

	private void initContractInfo(List<EmpContractDispatchVo> contracts,
								  TDispatchImportVo excel,
								  DispatchEmpVo empVo) {
		EmpContractDispatchVo contract;
		contract = new EmpContractDispatchVo();
		contract.setContractEnd(excel.getContractEnd());
		contract.setContractName(excel.getContractName());
		contract.setContractStart(excel.getContractStart());
		contract.setContractType(excel.getContractType());
		contract.setContractSubName(excel.getContractSubName());
		contract.setDeptNo(excel.getSettleDomainCode());
		contract.setPost(excel.getPost());
		contract.setSituation(excel.getContractType());
		contract.setEmpIdcard(excel.getEmpIdcard());
		contract.setEmpName(excel.getEmpName());
		if (Common.isNotNull(empVo)) {
			contract.setEmpId(empVo.getId());
			contract.setEmpNo(empVo.getEmpCode());
			contract.setEmpType(empVo.getEmpNatrue());
		}
		contracts.add(contract);
	}

	private void initProjectInfo(List<EmpProjectDispatchVo> projects,
								 TDispatchImportVo excel,
								 DispatchEmpVo empVo) {
		EmpProjectDispatchVo project;
		project = new EmpProjectDispatchVo();
		project.setDeptNo(excel.getSettleDomainCode());
		project.setContractType(excel.getContractType());
		project.setEmpIdcard(excel.getEmpIdcard());
		project.setEmpName(excel.getEmpName());
		project.setEmpNatrue(excel.getEmpType());
		project.setPost(excel.getPost());
		project.setWorkingHours(excel.getWorkingHours());
		if (Common.isNotNull(empVo)) {
			project.setEmpId(empVo.getId());
			project.setEmpNo(empVo.getEmpCode());
		}
		projects.add(project);
	}

	private void initEmpAddInfo(List<EmpAddDispatchVo> empAdds, TDispatchImportVo excel) {
		EmpAddDispatchVo emp;
		emp = new EmpAddDispatchVo();
		emp.setEmpIdcard(excel.getEmpIdcard());
		emp.setEmpName(excel.getEmpName());
		emp.setEmpNational(excel.getEmpNational());
		emp.setEmpNatrue(excel.getEmpType());
		emp.setEmpPhone(excel.getEmpMobile());
		emp.setEmpRegisType(excel.getEmpRegisType());
		emp.setContractStatus(CommonConstants.ZERO_INT);
		emp.setDeleteFlag(CommonConstants.ZERO_STRING);
		emp.setFileSource(CommonConstants.ONE_STRING);
		emp.setFileProvince(excel.getFileProvince());
		emp.setFileCity(excel.getFileCity());
		emp.setFileTown(excel.getFileTown());
		emp.setFileStatus(CommonConstants.ZERO_INT);
		emp.setStatus(CommonConstants.ZERO_INT);
		emp.setIdProvince(excel.getIdCardProvince());
		emp.setIdCity(excel.getIdCardCity());
		emp.setIdTown(excel.getIdCardTown());
		emp.setProjectNum(CommonConstants.ONE_INT);
		emp.setDeptNo(excel.getSettleDomainCode());
		emp.setPost(excel.getPost());
		empAdds.add(emp);
	}

	private boolean validDdispatchStatus(List<ErrorMessage> errorMessageList, Map<String, TSocialFundInfo> socialFundMap, TDispatchImportVo excel) {
		TSocialFundInfo sf;
		if (Common.isNotNull(socialFundMap)) {
			sf = socialFundMap.get(excel.getEmpIdcard());
			if (Common.isNotNull(sf)) {
				// 拒绝新增1：派单待审核、派单待办理、办理成功且未派减成功------ 先排除兼职工伤
				if (CommonConstants.ZERO_STRING.equals(sf.getSocialAddStatus())
						|| CommonConstants.ONE_STRING.equals(sf.getSocialAddStatus())
						|| (CommonConstants.TWO_STRING.equals(sf.getSocialAddStatus())
						&& !CommonConstants.TWO_STRING.equals(sf.getSocialReduceStatus())
						&& BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(excel.getPensionCardinal())) != 0
						&& BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(sf.getUnitPensionCardinal())) != 0)
				) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_EXISTING)));
					return true;
				}
				// 拒绝新增2：新增兼职工伤---有兼职工伤不可重复增、
				if (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(excel.getPensionCardinal())) == 0) {
					// 有兼职工伤不可重复增 (未派减成功不可新增兼职工伤，但是可以新增五险)
					if (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(sf.getUnitPensionCardinal())) == 0
							&& !CommonConstants.TWO_STRING.equals(sf.getSocialReduceStatus())) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_INJURY_EXISTING)));
						return true;
					}
					// 有五险未派减不给新增兼职工伤
					if (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(sf.getUnitPensionCardinal())) != 0
							&& Common.isEmpty(sf.getSocialReduceStatus())) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_NOT_REDUCE)));
						return true;
					}
				}
				// 拒绝新增3：新增五险对应兼职工伤逻辑---有兼职工伤未派减不给增五险、
				if (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(excel.getPensionCardinal())) != 0) {
					// 有兼职工伤未派减不给增五险
					if (BigDecimal.ZERO.compareTo(BigDecimalUtils.isNullToZero(sf.getUnitPensionCardinal())) == 0
							&& Common.isEmpty(sf.getSocialReduceStatus())) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_INJURY_NOT_REDUCE)));
						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));
		if (Common.isNotNull(list)) {
			return list.stream().collect(Collectors.toMap(k -> k.getEmpIdcard(), k -> k));
		}
		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> res = archivesDaprUtil.getDispatchEmpVo(checkVo);
			if (Common.isNotNull(res) && Common.isNotNull(res.getData())) {
				empVoMap = res.getData();
			}
		}
		return empVoMap;
	}

	private boolean validImport(List<ErrorMessage> errorMessageList,
								TDispatchImportVo excel,
								Map<String, TDispatchInfo> dispatchMap) {
		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.isNotNull(excel.getContractName()) && (
				Common.isEmpty(excel.getContractSubName())
						|| Common.isEmpty(excel.getContractType())
						|| Common.isEmpty(excel.getContractStart())
						|| Common.isEmpty(excel.getContractEnd())
		)) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_CONTRACT_NOT_EMPTY)));
			return true;
		}
		if (Common.isNotNull(excel.getSocialHousehold()) && (
				Common.isEmpty(excel.getRecordBase())
						|| Common.isEmpty(excel.getPensionStart())
						|| Common.isEmpty(excel.getPaymentType())
						|| Common.isEmpty(excel.getPensionCardinal())
		)) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_SOCIAL_EXIST)));
			return true;
		}
		if (Common.isNotNull(excel.getProvidentHousehold()) && (
				Common.isEmpty(excel.getProvidentCardinal())
						|| Common.isEmpty(excel.getProvidentStart())
						|| Common.isEmpty(excel.getProvidentPer())
		)) {
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_NOT_EMPTY)));
			return true;
		}
		if (Common.isNotNull(dispatchMap)){
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), MsgUtils.getMessage(ErrorCodes.EMP_DISPATCH_FUND_NOT_EMPTY)));
			return true;
		}
		return false;
	}


	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TDispatchImportVo excel) {
		TDispatchInfo insert = new TDispatchInfo();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}
}
