/*
 *    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.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.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
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.salary.vo.UpdateSocialFoundVo;
import com.yifu.cloud.plus.v1.yifu.social.constants.SocialConstants;
import com.yifu.cloud.plus.v1.yifu.social.entity.*;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialFundInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.*;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialFundHistoryVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialFundInfoDetailVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialFundInfoExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialFundInfoSearchVo;
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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社保公积金查询表
 *
 * @author fxj
 * @date 2022-07-15 11:38:05
 */
@Log4j2
@RequiredArgsConstructor
@Service
public class TSocialFundInfoServiceImpl extends ServiceImpl<TSocialFundInfoMapper, TSocialFundInfo> implements TSocialFundInfoService {

	private final ArchivesDaprUtil archivesDaprUtil;
	private final TDispatchInfoService tDispatchInfoService;
	private final TSocialLogService tSocialLogService;
	private final TAuditInfoService tAuditInfoService;
	private final TForecastLibraryService tForecastLibraryService;
	private final SysBaseSetInfoService sysBaseSetInfoService;
	private final TSocialFundHistoryService tSocialFundHistoryService;

	/**
	 * 社保公积金查询表简单分页查询
	 *
	 * @param tSocialFundInfo 社保公积金查询表
	 * @return
	 */
	@Override
	public IPage<TSocialFundInfo> getTSocialFundInfoPage(Page<TSocialFundInfo> page, TSocialFundInfoSearchVo tSocialFundInfo) {
		return baseMapper.getTSocialFundInfoPage(page, tSocialFundInfo);
	}

	/**
	 * 社保公积金查询表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TSocialFundInfoSearchVo searchVo) {
		String fileName = "社保公积金批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TSocialFundInfoExportVo> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TSocialFundInfoExportVo.class).includeColumnFiledNames(searchVo.getExportFields()).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = export(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TSocialFundInfoExportVo> util = new ExcelUtil<>(TSocialFundInfoExportVo.class);
						for (TSocialFundInfoExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (list != null) {
						WriteSheet writeSheet = EasyExcel.writerSheet("社保公积金查询表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("社保公积金查询表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			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<TSocialFundInfo> noPageDiy(TSocialFundInfoSearchVo searchVo) {
		LambdaQueryWrapper<TSocialFundInfo> wrapper = buildQueryWrapper(searchVo);
		if (Common.isNotNull(searchVo.getIdList())) {
			wrapper.in(TSocialFundInfo::getId, searchVo.getIdList());
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	private List<TSocialFundInfoExportVo> export(TSocialFundInfoSearchVo searchVo) {
		if (Common.isNotNull(searchVo.getIdList())) {
			searchVo.setIdList(searchVo.getIdList());
		}
		return baseMapper.exportList(searchVo);
	}

	private Long noPageCountDiy(TSocialFundInfoSearchVo searchVo) {
		LambdaQueryWrapper<TSocialFundInfo> wrapper = buildQueryWrapper(searchVo);
		if (Common.isNotNull(searchVo.getIdList())) {
			wrapper.in(TSocialFundInfo::getId, searchVo.getIdList());
		}
		return baseMapper.selectCount(wrapper);
	}

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

	/**
	 * @param doMonth 执行月份
	 * @Description: 批量调基
	 * @Author: hgw
	 * @Date: 2022/7/22 11:32
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage>>
	 **/
	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream, String doMonth) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSocialFundHistoryVo> util1 = new ExcelUtil<>(TSocialFundHistoryVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TSocialFundHistoryVo.class, new ReadListener<TSocialFundHistoryVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TSocialFundHistoryVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TSocialFundHistoryVo 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());
					importTSocialFundInfo(cachedDataList, errorMessageList, doMonth);
					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);
	}

	private void importTSocialFundInfo(List<TSocialFundHistoryVo> excelVOList
			, List<ErrorMessage> errorMessageList, String doMonth) {
		// 执行数据插入操作 组装
		TSocialFundHistoryVo excel;
		List<String> idCardList = new ArrayList<>();
		for (int i = 0; i < excelVOList.size(); i++) {
			idCardList.add(excelVOList.get(i).getEmpIdcard());
		}
		List<TSocialFundInfo> socialFundInfoList = this.list(Wrappers.<TSocialFundInfo>query().lambda()
				.in(TSocialFundInfo::getEmpIdcard, idCardList));
		Map<String, TSocialFundInfo> socialFundInfoMap = new HashMap<>();
		if (socialFundInfoList != null && !socialFundInfoList.isEmpty()) {
			for (TSocialFundInfo socialFundInfo : socialFundInfoList) {
				socialFundInfoMap.put(socialFundInfo.getEmpIdcard(), socialFundInfo);
			}
			socialFundInfoList.clear();
		}
		TSocialFundInfo oldSocialFundInfo;
		TSocialFundInfo socialFundInfo;
		// 判断是否修改了社保
		boolean isSocial;
		// 判断是否修改了公积金
		boolean isFund;
		TSocialFundHistory history;
		// 基数配置Map
		Map<String, SysBaseSetInfo> socialSetInfoMap = sysBaseSetInfoService.getSysBaseSetInfoMap(CommonConstants.ZERO_STRING);
		Map<String, SysBaseSetInfo> fundSetInfoMap = sysBaseSetInfoService.getSysBaseSetInfoMap(CommonConstants.ONE_STRING);
		// 社保基数配置
		SysBaseSetInfo socialSetInfo;
		SysBaseSetInfo fundSetInfo;
		for (int i = 0; i < excelVOList.size(); i++) {
			isSocial = false;
			isFund = false;
			excel = excelVOList.get(i);
			socialFundInfo = socialFundInfoMap.get(excel.getEmpIdcard());
			if (null != socialFundInfo) {
				if (socialFundInfo.getEmpName().equals(excel.getEmpName())) {
					history = new TSocialFundHistory();
					BeanUtil.copyProperties(excel, history);
					// 存储变更日志使用的
					oldSocialFundInfo = new TSocialFundInfo();
					BeanUtil.copyProperties(socialFundInfo, oldSocialFundInfo);
					// 0：校验数据有效性
					// 缴纳类型不为空
					if (Common.isNotNull(excel.getPaymentType())) {
						isSocial = true;
						if (checkSocialUpdateTwo(errorMessageList, excel.getRowIndex(), history)) continue;
					} else {
						isFund = true;
						// 验证公积金数据调基是否完整
						if (checkFundUpdate(errorMessageList, excel.getRowIndex(), history)) continue;
					}
					isFund = initIsFund(isFund, history);
					// 如果调整公积金，公积金信息全都要填写!
					if (checkFundInfo(errorMessageList, excel.getRowIndex(), isFund, history)) continue;
					history.setEmpId(socialFundInfo.getEmpId());
					history.setEmpIdcard(socialFundInfo.getEmpIdcard());
					history.setEmpName(socialFundInfo.getEmpName());
					history.setCreateTime(LocalDateTime.now());

					// 初始化微0，后面变更
					history.setIsFund(CommonConstants.ZERO_INT);
					history.setIsFund(CommonConstants.ZERO_INT);
					// 社保，且缴纳类型为自定义
					if (isSocial) {
						if (socialFundInfo.getSocialTown() != null) {
							socialSetInfo = socialSetInfoMap.get(socialFundInfo.getSocialHousehold() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getSocialProvince() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getSocialCity() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getSocialTown());
						} else {
							socialSetInfo = socialSetInfoMap.get(socialFundInfo.getSocialHousehold() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getSocialProvince() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getSocialCity());
						}
						if (socialSetInfo == null) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "未找到社保基数配置!"));
							continue;
						}
						// 初始化社保调基信息
						initSocialHistory(history, socialFundInfo);
						// 更新社保公积金表的社保信息
						this.setSocialFundInfoBySocial(socialFundInfo, socialSetInfo, history);
					}
					if (isFund) {
						history.setIsFund(CommonConstants.ONE_INT);
						history.setSocialFundId(socialFundInfo.getId());
						history.setUnitFundBase(excel.getUnitFundBase());
						history.setUnitFundProp(excel.getUnitFundProp());
						history.setPersonalFundBase(excel.getPersonalFundBase());
						history.setPersonalFundProp(excel.getPersonalFundProp());

						if (socialFundInfo.getFundTown() != null) {
							fundSetInfo = fundSetInfoMap.get(socialFundInfo.getProvidentHousehold() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getFundProvince() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getFundCity() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getFundTown());
						} else {
							fundSetInfo = fundSetInfoMap.get(socialFundInfo.getProvidentHousehold() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getFundProvince() + CommonConstants.DOWN_LINE_STRING
									+ socialFundInfo.getFundCity());
						}
						if (fundSetInfo == null) {
							errorMessageList.add(new ErrorMessage(i, "未找到公积金基数配置!"));
							continue;
						}
						/* if (!ServiceUtil.checkFundPercentByList(fundSetInfo.getFundProList(), history)) {
							errorMessageList.add(new ErrorMessage(i, "无对应公积金比例，请查验公积金户+缴纳地+缴纳月份的公积金比例配置！"))
							continue
						}*/
						history.setUnitFundMoney(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(history.getUnitFundBase()
								, history.getUnitFundProp(), CommonConstants.ONE_OF_PERCENT), Integer.parseInt(socialFundInfo.getFundPayPoint())));
						history.setPersonalFundMoney(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(history.getPersonalFundBase()
								, history.getPersonalFundProp(), CommonConstants.ONE_OF_PERCENT), Integer.parseInt(socialFundInfo.getFundPayPoint())));
						// 更新社保公积金表的公积金信息
						this.setSocialFundInfoByFund(socialFundInfo, history);
					}
					// 1：新增调基记录
					tSocialFundHistoryService.save(history);
					// 2：更新社保公积金查询
					this.updateById(socialFundInfo);

					// 3：新增变更日志
					tSocialLogService.saveModificationRecord(CommonConstants.THREE_INT, oldSocialFundInfo.getId(), oldSocialFundInfo, socialFundInfo);
					// 4：同步预估库
					tForecastLibraryService.updateToneForecastLibary(socialFundInfo, doMonth);
					// 返回信息处理
					initResSuccessMessage(errorMessageList, excel.getRowIndex(), isSocial, isFund);
				} else {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SocialConstants.EMP_NAME_ERROR));
				}
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "调基失败：未找到对应项目下的员工" + excel.getEmpName() + "数据!"));
			}

		}
	}

	private void initResSuccessMessage(List<ErrorMessage> errorList, int i, boolean isSocial, boolean isFund) {
		if (isSocial && isFund) {
			errorList.add(new ErrorMessage(i, "社保公积金调基成功!", CommonConstants.GREEN));
		} else if (isSocial) {
			errorList.add(new ErrorMessage(i, "社保调基成功!", CommonConstants.GREEN));
		} else {
			errorList.add(new ErrorMessage(i, "公积金调基成功!", CommonConstants.GREEN));
		}
	}

	/**
	 * @param socialFundInfo
	 * @param baseSetVo
	 * @Description: 塞值：社保公积金表的社保信息
	 * @Author: hgw
	 * @Date: 2022/7/25 16:04
	 * @return: void
	 **/
	private void setSocialFundInfoBySocial(TSocialFundInfo socialFundInfo, SysBaseSetInfo socialSetInfo
			, TSocialFundHistory baseSetVo) {
		socialFundInfo.setPaymentType(String.valueOf(baseSetVo.getPaymentType()));
		// 自定义，存基数等
		if (CommonConstants.ONE_INT == baseSetVo.getPaymentType()) {
			socialFundInfo.setUnitPensionCardinal(baseSetVo.getUnitPensionCardinal());
			socialFundInfo.setUnitMedicalCardinal(baseSetVo.getUnitMedicalCardinal());
			socialFundInfo.setUnitBirthCardinal(baseSetVo.getUnitBirthCardinal());
			socialFundInfo.setUnitUnemploymentCardinal(baseSetVo.getUnitUnemploymentCardinal());
			socialFundInfo.setUnitWorkInjuryCardinal(baseSetVo.getUnitWorkInjuryCardinal());

			socialFundInfo.setPersonalPensionCardinal(baseSetVo.getUnitPensionCardinal());
			socialFundInfo.setPersonalMedicalCardinal(baseSetVo.getUnitMedicalCardinal());
			socialFundInfo.setPersonalUnemploymentCardinal(baseSetVo.getUnitUnemploymentCardinal());

			if (baseSetVo.getUnitBigailmentMoney() != null) {
				socialFundInfo.setUnitBigailmentMoney(baseSetVo.getUnitBigailmentMoney());
			}
			if (baseSetVo.getPersonalBigailmentMoney() != null) {
				socialFundInfo.setPersonalBigailmentMoney(baseSetVo.getPersonalBigailmentMoney());
			}
		} else if (CommonConstants.ZERO_INT == baseSetVo.getPaymentType()) {
			BigDecimal limitBase = socialSetInfo.getLowerLimit();
			this.setLimtBase(socialFundInfo, limitBase, socialSetInfo);
		} else if (CommonConstants.TWO_INT == baseSetVo.getPaymentType()) {
			BigDecimal limitBase = socialSetInfo.getUpperLimit();
			this.setLimtBase(socialFundInfo, limitBase, socialSetInfo);
		}

		// 金额计算
		socialFundInfo.setUnitPersionMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getUnitPensionCardinal(), socialFundInfo.getUnitPensionPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setUnitMedicalMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getUnitMedicalCardinal(), socialFundInfo.getUnitMedicalPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setUnitBirthMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getUnitBirthCardinal(), socialFundInfo.getUnitBirthPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setUnitInjuryMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getUnitWorkInjuryCardinal(), socialFundInfo.getUnitWorkUnjuryPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setUnitUnemploymentMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getUnitUnemploymentCardinal(), socialFundInfo.getUnitUnemploymentPer(), CommonConstants.ONE_OF_PERCENT));

		socialFundInfo.setPersonalPersionMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getPersonalPensionCardinal(), socialFundInfo.getPersonalPensionPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setPersonalMedicalMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getPersonalMedicalCardinal(), socialFundInfo.getPersonalMedicalPer(), CommonConstants.ONE_OF_PERCENT));
		socialFundInfo.setPersonalUnemploymentMoney(BigDecimalUtils.safeMultiply(socialFundInfo.getPersonalUnemploymentCardinal(), socialFundInfo.getPersonalUnemploymentPer(), CommonConstants.ONE_OF_PERCENT));

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

	/**
	 * @param socialFundInfo
	 * @param limitBase
	 * @Description: 塞最低或最高值
	 * @Author: hgw
	 * @Date: 2022/7/25 16:15
	 * @return: void
	 **/
	private void setLimtBase(TSocialFundInfo socialFundInfo, BigDecimal limitBase, SysBaseSetInfo sysBaseSetInfo) {
		socialFundInfo.setUnitPensionCardinal(limitBase);
		socialFundInfo.setUnitMedicalCardinal(limitBase);
		socialFundInfo.setUnitBirthCardinal(limitBase);
		socialFundInfo.setUnitUnemploymentCardinal(limitBase);
		socialFundInfo.setUnitWorkInjuryCardinal(limitBase);

		socialFundInfo.setPersonalPensionCardinal(limitBase);
		socialFundInfo.setPersonalMedicalCardinal(limitBase);
		socialFundInfo.setPersonalUnemploymentCardinal(limitBase);

		// 大病处理: 0 收取  按派单的社保里的基数和比例来
		if (CommonConstants.ZERO_STRING.equals(sysBaseSetInfo.getIsIllness())) {
			// 大病收取方式  0.按年  判断当前月份是否收取大病     按年收大病起缴月份收取一次，非当年的 大病 按实际收取月份收取大病金额
			this.setBigMoney(socialFundInfo, sysBaseSetInfo, limitBase);
			// 大病处理: 1 不收取
		} else {
			socialFundInfo.setUnitBigailmentMoney(BigDecimal.ZERO);
			socialFundInfo.setPersonalBigailmentMoney(BigDecimal.ZERO);
		}
	}

	private void setBigMoney(TSocialFundInfo socialInfo, SysBaseSetInfo sysBaseSetInfo
			, BigDecimal limitBase) {
		if (CommonConstants.ZERO_STRING.equals(sysBaseSetInfo.getCollectType())) {
			socialInfo.setUnitBigailmentMoney(BigDecimalUtils.isNullToZero(sysBaseSetInfo.getPayCompany()));
			socialInfo.setPersonalBigailmentMoney(BigDecimalUtils.isNullToZero(sysBaseSetInfo.getPayPersonal()));
			//大病收取方式 : 1.按月
		} else if (CommonConstants.ONE_STRING.equals(sysBaseSetInfo.getCollectType())) {
			//  大病取值方式：1 按比例   按派单的基数和比例来
			if (CommonConstants.ONE_STRING.equals(sysBaseSetInfo.getValueType())) {
				socialInfo.setUnitBigailmentCardinal(limitBase);
				socialInfo.setUnitBigailmentPer(sysBaseSetInfo.getPayCompanyPro());
				socialInfo.setPersonalBigailmentCardinal(limitBase);
				socialInfo.setPersonalBigailmentPer(sysBaseSetInfo.getPayPersonalPro());
				socialInfo.setPersonalBigailmentMoney(BigDecimalUtils.safeMultiply(
						limitBase,
						sysBaseSetInfo.getPayPersonalPro(),
						CommonConstants.ONE_OF_PERCENT));
				socialInfo.setUnitBigailmentMoney(BigDecimalUtils.safeMultiply(
						limitBase,
						sysBaseSetInfo.getPayCompanyPro(),
						CommonConstants.ONE_OF_PERCENT));
			} else {
				// 大病取值方式：0按定值
				socialInfo.setUnitBigailmentMoney(BigDecimalUtils.isNullToZero(sysBaseSetInfo.getPayCompany()));
				socialInfo.setPersonalBigailmentMoney(BigDecimalUtils.isNullToZero(sysBaseSetInfo.getPayPersonal()));
			}
		}
	}

	/**
	 * @param socialFundInfo
	 * @param baseSetVo
	 * @Description: 塞值：社保公积金表的公积金信息
	 * @Author: hgw
	 * @Date: 2022/7/25 16:05
	 * @return: void
	 **/
	private void setSocialFundInfoByFund(TSocialFundInfo socialFundInfo, TSocialFundHistory baseSetVo) {
		socialFundInfo.setUnitProvidengCardinal(baseSetVo.getUnitFundBase());
		socialFundInfo.setUnitProvidentPer(baseSetVo.getUnitFundProp());
		socialFundInfo.setPersonalProvidentCardinal(baseSetVo.getPersonalFundBase());
		socialFundInfo.setPersonalProvidentPer(baseSetVo.getPersonalFundProp());

		socialFundInfo.setUnitFundSum(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(
						socialFundInfo.getUnitProvidengCardinal(), socialFundInfo.getUnitProvidentPer(), CommonConstants.ONE_OF_PERCENT)
				, Integer.parseInt(socialFundInfo.getFundPayPoint())));
		socialFundInfo.setPersonalFundSum(Common.formatMoneyForFund(BigDecimalUtils.safeMultiply(
						socialFundInfo.getPersonalProvidentCardinal(), socialFundInfo.getPersonalProvidentPer(), CommonConstants.ONE_OF_PERCENT)
				, Integer.parseInt(socialFundInfo.getFundPayPoint())));
	}

	/**
	 * @param history
	 * @param baseSetVo
	 * @Description: 填充调基表信息
	 * @Author: hgw
	 * @Date: 2022/7/25 16:06
	 * @return: void
	 **/
	private void initSocialHistory(TSocialFundHistory history, TSocialFundInfo baseSetVo) {
		history.setIsSocial(CommonConstants.ONE_INT);
		history.setSocialFundId(baseSetVo.getId());
		if (CommonConstants.ONE_INT == history.getPaymentType()) {
			history.setUnitPersionPro(baseSetVo.getUnitPensionCardinal());
			history.setUnitMedicalPro(baseSetVo.getUnitMedicalCardinal());
			history.setUnitUnemploymentPro(baseSetVo.getUnitUnemploymentCardinal());
			history.setUnitInjuryPro(baseSetVo.getUnitWorkInjuryCardinal());
			history.setUnitBirthPro(baseSetVo.getUnitBirthCardinal());
			history.setPersonalPersionPro(baseSetVo.getPersonalPensionCardinal());
			history.setPersonalMedicalPro(baseSetVo.getPersonalMedicalCardinal());
			history.setPersonalUnemploymentPro(baseSetVo.getPersonalUnemploymentCardinal());
			history.setUnitPersionMoney(BigDecimalUtils.safeMultiply(
					history.getUnitPensionCardinal(),
					history.getUnitPersionPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setUnitMedicalMoney(BigDecimalUtils.safeMultiply(
					history.getUnitMedicalCardinal(),
					history.getUnitMedicalPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setUnitUnemploymentMoney(BigDecimalUtils.safeMultiply(
					history.getUnitUnemploymentCardinal(),
					history.getUnitUnemploymentPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setUnitInjuryMoney(BigDecimalUtils.safeMultiply(
					history.getUnitWorkInjuryCardinal(),
					history.getUnitInjuryPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setUnitBirthMoney(BigDecimalUtils.safeMultiply(
					history.getUnitBirthCardinal(),
					history.getUnitBirthPro(),
					CommonConstants.ONE_OF_PERCENT));
			// 个人、单位，采用一个基数
			history.setPersonalPersionMoney(BigDecimalUtils.safeMultiply(
					history.getUnitPensionCardinal(),
					history.getPersonalPersionPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setPersonalMedicalMoney(BigDecimalUtils.safeMultiply(
					history.getUnitMedicalCardinal(),
					history.getPersonalMedicalPro(),
					CommonConstants.ONE_OF_PERCENT));
			history.setPersonalUnemploymentMoney(BigDecimalUtils.safeMultiply(
					history.getUnitUnemploymentCardinal(),
					history.getPersonalUnemploymentPro(),
					CommonConstants.ONE_OF_PERCENT));
		}
	}

	/**
	 * 验证自定义 和非自定义社保的数据完整性
	 *
	 * @return
	 * @Author hgw
	 * @Date 2022-7-25 10:46:43
	 **/
	private boolean checkSocialUpdateTwo(List<ErrorMessage> errorList, int i, TSocialFundHistory baseSetVo) {
		if ((CommonConstants.ZERO_INT == baseSetVo.getPaymentType()
				|| CommonConstants.TWO_INT == baseSetVo.getPaymentType())
				&& (
				null != baseSetVo.getUnitPensionCardinal()
						|| null != baseSetVo.getUnitMedicalCardinal()
						|| null != baseSetVo.getUnitBirthCardinal()
						|| null != baseSetVo.getUnitUnemploymentCardinal()
						|| null != baseSetVo.getUnitWorkInjuryCardinal()
						|| null != baseSetVo.getUnitBigailmentMoney()
						|| null != baseSetVo.getPersonalBigailmentMoney()
		)) {
			errorList.add(new ErrorMessage(i, "缴纳类型非自定义，不可填写社保信息!"));
			return true;
		} else if (CommonConstants.ONE_INT == baseSetVo.getPaymentType()
				&& (
				null == baseSetVo.getUnitPensionCardinal()
						|| null == baseSetVo.getUnitMedicalCardinal()
						|| null == baseSetVo.getUnitBirthCardinal()
						|| null == baseSetVo.getUnitUnemploymentCardinal()
						|| null == baseSetVo.getUnitWorkInjuryCardinal()
		)) {
			errorList.add(new ErrorMessage(i, "缴纳类型为自定义，社保信息除大病外都要填写!"));
			return true;
		}
		return false;
	}

	/**
	 * @Description: 验证公积金数据调基是否完整
	 * @Author: hgw
	 * @Date: 2022/7/25 11:28
	 * @return: boolean
	 **/
	private boolean checkFundUpdate(List<ErrorMessage> errorList, int i, TSocialFundHistory baseSetVo) {
		if (null != baseSetVo.getUnitMedicalCardinal()
				|| null != baseSetVo.getUnitBirthCardinal()
				|| null != baseSetVo.getUnitUnemploymentCardinal()
				|| null != baseSetVo.getUnitWorkInjuryCardinal()
				|| null != baseSetVo.getUnitBigailmentMoney()
				|| null != baseSetVo.getPersonalBigailmentMoney()) {
			errorList.add(new ErrorMessage(i, "检测到调整了社保字段，缴纳类型不可为空。自定义，所有社保项目必填；非自定义，社保项目不可填写!"));
			return true;
		}
		if (null == baseSetVo.getUnitFundBase()
				|| null == baseSetVo.getUnitFundProp()
				|| null == baseSetVo.getPersonalFundBase()
				|| null == baseSetVo.getPersonalFundProp()) {
			errorList.add(new ErrorMessage(i, "缴纳类型为空，如果调整公积金，公积金信息全都要填写!"));
			return true;
		}
		return false;
	}

	/**
	 * @Description: 是否公积金
	 * @Author: hgw
	 * @Date: 2022/7/25 11:31
	 * @return: boolean
	 **/
	private boolean initIsFund(boolean isFund, TSocialFundHistory baseSetVo) {
		if (null != baseSetVo.getUnitFundBase()
				&& null != baseSetVo.getUnitFundProp()
				&& null != baseSetVo.getPersonalFundBase()
				&& null != baseSetVo.getPersonalFundProp()) {
			isFund = true;
		}
		return isFund;
	}

	/**
	 * @Description: 验证公积金数据的完整性
	 * @Author: hgw
	 * @Date: 2022/7/25 11:33
	 * @return: boolean
	 **/
	private boolean checkFundInfo(List<ErrorMessage> errorList, int i, boolean isFund, TSocialFundHistory baseSetVo) {
		if (!isFund && ((null != baseSetVo.getUnitFundBase() && (
				null == baseSetVo.getPersonalFundBase()
						|| null == baseSetVo.getUnitFundProp()
						|| null == baseSetVo.getPersonalFundProp()))
				||
				(null != baseSetVo.getPersonalFundBase() && (
						null == baseSetVo.getUnitFundBase()
								|| null == baseSetVo.getUnitFundProp()
								|| null == baseSetVo.getPersonalFundProp()))
				||
				(null != baseSetVo.getUnitFundProp() && (
						null == baseSetVo.getUnitFundBase()
								|| null == baseSetVo.getPersonalFundBase()
								|| null == baseSetVo.getPersonalFundProp()))
				||
				(null != baseSetVo.getPersonalFundProp() && (
						null == baseSetVo.getUnitFundBase()
								|| null == baseSetVo.getUnitFundProp()
								|| null == baseSetVo.getPersonalFundBase())))) {
			errorList.add(new ErrorMessage(i, "如果调整公积金，公积金信息全都要填写!"));
			return true;
		}
		return false;
	}

	@Override
	public TSocialFundInfoDetailVo getDetailById(String id) {
		TSocialFundInfoDetailVo detailVo = new TSocialFundInfoDetailVo();
		TSocialFundInfo socialFundInfo = this.getById(id);
		if (socialFundInfo != null) {
			// 主表信息
			detailVo.setSocialFundInfo(socialFundInfo);
			// 人员信息
			if (Common.isNotNull(socialFundInfo.getEmpId())) {
				R<TEmployeeInfo> employeeInfoR = archivesDaprUtil.getTEmployeeInfoById(socialFundInfo.getEmpId());
				if (employeeInfoR != null && employeeInfoR.getCode() == CommonConstants.SUCCESS) {
					detailVo.setEmployeeInfo(employeeInfoR.getData());
				}
				// 社保所属项目
				if (Common.isNotNull(socialFundInfo.getSettleDomain())) {
					TEmployeeProject employeeProject = new TEmployeeProject();
					employeeProject.setEmpId(socialFundInfo.getEmpId());
					employeeProject.setDeptId(socialFundInfo.getSettleDomain());
					R<TEmployeeProject> employeeProjectR = archivesDaprUtil.getTEmployeeProjectById(employeeProject);
					if (employeeProjectR != null && employeeProjectR.getCode() == CommonConstants.SUCCESS) {
						detailVo.setSocialProject(employeeProjectR.getData());
					}
				}
				// 公积金所属项目
				if (Common.isNotNull(socialFundInfo.getSettleDomainFund())) {
					TEmployeeProject employeeProject = new TEmployeeProject();
					employeeProject.setEmpId(socialFundInfo.getEmpId());
					employeeProject.setDeptId(socialFundInfo.getSettleDomainFund());
					R<TEmployeeProject> employeeProjectR = archivesDaprUtil.getTEmployeeProjectById(employeeProject);
					if (employeeProjectR != null && employeeProjectR.getCode() == CommonConstants.SUCCESS) {
						detailVo.setFundProject(employeeProjectR.getData());
					}
				}
			}
			// 2022-7-21 12:00
			// 倩倩已确认，社保公积金详情里的合同，采用社保/公积金对应的派单的合同信息（去除状态）
			// 另外，基数sheet，采用变更日志，不是调基表。
			// 社保所属合同
			if (Common.isNotNull(socialFundInfo.getSocialId())) {
				TDispatchInfo dispatchInfo = tDispatchInfoService.getOne(Wrappers.<TDispatchInfo>query().lambda()
						.eq(TDispatchInfo::getSocialId, socialFundInfo.getSocialId())
						.eq(TDispatchInfo::getType, CommonConstants.ZERO_STRING)
						.orderByDesc(TDispatchInfo::getCreateTime).last(CommonConstants.LAST_ONE_SQL));
				detailVo.setSocialContract(dispatchInfo);
			}
			// 公积金所属合同
			if (Common.isNotNull(socialFundInfo.getFundId())) {
				TDispatchInfo dispatchInfo = tDispatchInfoService.getOne(Wrappers.<TDispatchInfo>query().lambda()
						.eq(TDispatchInfo::getFundId, socialFundInfo.getFundId())
						.eq(TDispatchInfo::getType, CommonConstants.ZERO_STRING)
						.orderByDesc(TDispatchInfo::getCreateTime).last(CommonConstants.LAST_ONE_SQL));
				detailVo.setFundContract(dispatchInfo);
			}
			// 调基记录
			List<TSocialLog> socialLogList = tSocialLogService.list(Wrappers.<TSocialLog>query().lambda()
					.eq(TSocialLog::getType, CommonConstants.THREE_INT)
					.eq(TSocialLog::getMainId, socialFundInfo.getId())
					.orderByDesc(TSocialLog::getCreateTime));
			detailVo.setLogList(socialLogList);
			// 流程进展明细
			List<TAuditInfo> auditInfoList = tAuditInfoService.list(Wrappers.<TAuditInfo>query().lambda()
					.eq(TAuditInfo::getEmpIdcard, socialFundInfo.getEmpIdcard())
					.orderByDesc(TAuditInfo::getAuditTime));
			detailVo.setAuditList(auditInfoList);
		}
		return detailVo;
	}

	@Override
	public void updateSocialAndFoundInfo(UpdateSocialFoundVo infoVo) {
		if (Common.isNotNull(infoVo) && Common.isNotNull(infoVo.getFlag())) {
			if (CommonConstants.ZERO_STRING.equals(infoVo.getFlag())) {
				baseMapper.updateSocialAndFoundInfo(infoVo);
			}else {
				baseMapper.updateSocialAndFoundInfoF(infoVo);
			}
		}
	}

}