/*
 *    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 com.alibaba.excel.EasyExcelFactory;
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.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.ekp.vo.EkpIncomePushInfoVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
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.EkpDaprUtils;
import com.yifu.cloud.plus.v1.yifu.ekp.util.EkpIncomeUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpIncomeParamManage;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpIncomeParamRisk;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.EkpInsuranceViewVo;
import com.yifu.cloud.plus.v1.yifu.social.constants.SocialConstants;
import com.yifu.cloud.plus.v1.yifu.social.entity.TIncome;
import com.yifu.cloud.plus.v1.yifu.social.entity.TIncomeDetail;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TIncomeMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TPaymentInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TIncomeDetailService;
import com.yifu.cloud.plus.v1.yifu.social.service.TIncomeService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSendEkpErrorService;
import com.yifu.cloud.plus.v1.yifu.social.util.DoJointSocialTask;
import com.yifu.cloud.plus.v1.yifu.social.vo.IncomeExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TIncomeSearchVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TIncomeVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 收入明细表
 *
 * @author hgw
 * @date 2022-08-30 17:34:58
 */
@Log4j2
@Service
public class TIncomeServiceImpl extends ServiceImpl<TIncomeMapper, TIncome> implements TIncomeService {

	@Autowired
	private TIncomeDetailService tIncomeDetailService;

	@Autowired
	private TSendEkpErrorService tSendEkpErrorService;

	@Autowired
	private EkpIncomeUtil ekpIncomeUtil;

	@Autowired
	private DoJointSocialTask doJointSocialTask;

	@Autowired
	private TPaymentInfoMapper tPaymentInfoMapper;

	@Autowired
	private EkpDaprUtils ekpDaprUtil;

	/**
	 * 收入明细表简单分页查询
	 *
	 * @param tIncome 收入明细表
	 * @return
	 */
	@Override
	public IPage<TIncome> getTIncomePage(Page<TIncome> page, TIncomeSearchVo tIncome) {
		return baseMapper.getTIncomePage(page, tIncome);
	}

	/**
	 * 收入明细表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TIncomeSearchVo searchVo) {
		String fileName = "收入明细批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<IncomeExportVo> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo, Common.getList(searchVo.getIds()));
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding(CommonConstants.UTF8);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcelFactory.write(out, IncomeExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT_3) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT_3);
					list = noPageDiy(searchVo, Common.getList(searchVo.getIds()));
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet("收入明细表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet("收入明细表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error(CommonConstants.ERROR_IMPORT, e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error(CommonConstants.ERROR_IMPORT, e);
			}
		}
	}

	private List<IncomeExportVo> noPageDiy(TIncomeSearchVo searchVo,
										   List<String> ids) {
		return baseMapper.noPageDiy(searchVo, ids);
	}

	private int noPageCountDiy(TIncomeSearchVo searchVo,
							   List<String> ids) {
		return baseMapper.noPageCountDiy(searchVo, ids);
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TIncomeVo> util1 = new ExcelUtil<>(TIncomeVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcelFactory.read(inputStream, TIncomeVo.class, new ReadListener<TIncomeVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TIncomeVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TIncomeVo 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());
					importTIncome(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);
	}

	private void importTIncome(List<TIncomeVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TIncomeVo excel = excelVOList.get(i);
			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

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

	/**
	 * @Description: 新增收入明细-详情表，同时统计；
	 * @Author: hgw
	 * @Date: 2022/8/31 16:34
	 * @return: boolean
	 **/
	public boolean saveDetail(TIncomeDetail tIncomeDetail,boolean synFlag) {
		if (Common.isEmpty(tIncomeDetail.getEmpIdcard())
				|| Common.isEmpty(tIncomeDetail.getDeptId())
				|| Common.isEmpty(tIncomeDetail.getPayMonth())) {
			return false;
		}
		// 获取对应信息的统计表，根据项目配置，判断是否可以加一条统计：
		TIncome income = new TIncome();
		income.setEmpIdcard(tIncomeDetail.getEmpIdcard());
		income.setDeptId(tIncomeDetail.getDeptId());
		List<TIncome> incomeList = baseMapper.getTIncomeList(income);

		TIncomeDetail detail = new TIncomeDetail();
		detail.setEmpIdcard(tIncomeDetail.getEmpIdcard());
		detail.setDeptId(tIncomeDetail.getDeptId());
		List<TIncomeDetail> detailList = tIncomeDetailService.getTIncomeDetailList(detail);

		tIncomeDetail.setCreateTime(new Date());
		tIncomeDetail.setDataCreateMonth(DateUtil.addMonth(0));
		tIncomeDetailService.save(tIncomeDetail);
		// 不存在，直接新增
		if (incomeList == null || incomeList.isEmpty()) {
			return this.saveIncome(tIncomeDetail,synFlag);
		} else {
			// 核心判断
			return this.copyCore(tIncomeDetail, incomeList, detailList,null,synFlag);
		}
	}

	@Override
	public boolean savePushIncome(TIncome income) {
		doJointSocialTask.asynchronousEkpIncomeAssoT(income);
		return true;
	}

	/**
	 * @Description: 新增收入明细-详情表，同时统计；
	 * @Author: hgw
	 * @Date: 2022/8/31 16:34
	 * @return: boolean
	 **/
	@Override
	public boolean saveBathDetail(TIncomeDetail tIncomeDetail, String paymentId) {
		if (Common.isEmpty(tIncomeDetail.getEmpIdcard())
				|| Common.isEmpty(tIncomeDetail.getDeptId())
				|| Common.isEmpty(tIncomeDetail.getPayMonth())) {
			return false;
		}
		// 获取对应信息的统计表，根据项目配置，判断是否可以加一条统计：
		TIncome income = new TIncome();
		income.setEmpIdcard(tIncomeDetail.getEmpIdcard());
		income.setDeptId(tIncomeDetail.getDeptId());
		List<TIncome> incomeList = baseMapper.getTIncomeList(income);
		TIncomeDetail detail = new TIncomeDetail();
		detail.setEmpIdcard(tIncomeDetail.getEmpIdcard());
		detail.setDeptId(tIncomeDetail.getDeptId());
		List<TIncomeDetail> detailList = tIncomeDetailService.getTIncomeDetailList(detail);
		tIncomeDetail.setCreateTime(new Date());
		tIncomeDetail.setDataCreateMonth(DateUtil.addMonth(0));
		tIncomeDetailService.save(tIncomeDetail);
		// 不存在，直接新增
		if (incomeList == null || incomeList.isEmpty()) {
			return this.savePaymentIncomeNew(tIncomeDetail, paymentId);
		} else {
			// 核心判断
			return this.copyCoreNew(tIncomeDetail, incomeList, detailList, paymentId, true);
		}
	}

	@Override
	public void pushDetail() {
		//管理费处理
		long count = baseMapper.selectCount(Wrappers.<TIncome>query().lambda()
				.eq(TIncome::getSendStatus, CommonConstants.ZERO_STRING)
				.eq(TIncome::getFeeType, CommonConstants.ONE_STRING));
		if (count > 0) {
			List<TIncome> list = baseMapper.selectList(Wrappers.<TIncome>query().lambda()
					.eq(TIncome::getSendStatus, CommonConstants.ZERO_STRING)
					.eq(TIncome::getFeeType, CommonConstants.ONE_STRING));
			int i = (int) Math.ceil((double) count / CommonConstants.ONE_THOUSAND_INT);
			if (!list.isEmpty()) {
				List<TIncome> pushList;
				int k = 0;
				for (int j = 0; j < i; j++) {
					synchronized (this) {
						if (j == i - 1) {
							pushList = list.subList(k, list.size());
						} else {
							pushList = list.subList(k, k + 1000);
						}
						k = k + 1000;
						if (Common.isNotNull(pushList)) {
							//推送数据封装并推送
							doJointSocialTask.asynchronousEkpIncomePush(pushList);
						}
					}
				}
			}
		}
		//风险金处理
		long countRisk = baseMapper.selectCount(Wrappers.<TIncome>query().lambda()
				.eq(TIncome::getSendStatus, CommonConstants.ZERO_STRING)
				.eq(TIncome::getFeeType, CommonConstants.TWO_STRING));
		if (countRisk > 0) {
			List<TIncome> list = baseMapper.selectList(Wrappers.<TIncome>query().lambda()
					.eq(TIncome::getSendStatus, CommonConstants.ZERO_STRING)
					.eq(TIncome::getFeeType, CommonConstants.TWO_STRING));
			int i = (int) Math.ceil((double) countRisk / CommonConstants.ONE_THOUSAND_INT);
			if (!list.isEmpty()) {
				List<TIncome> pushList;
				int k = 0;
				for (int j = 0; j < i; j++) {
					synchronized (this) {
						if (j == i - 1) {
							pushList = list.subList(k, list.size());
						} else {
							pushList = list.subList(k, k + 1000);
						}
						k = k + 1000;
						if (Common.isNotNull(pushList)) {
							//推送数据封装并推送
							doJointSocialTask.asynchronousEkpIncomeRiskPush(pushList);
						}
					}
				}
			}
		}
	}

	/**
	 * @param income
	 * @Description: 判断类型发送
	 * @Author: hgw
	 * @Date: 2022/9/6 15:15
	 * @return: java.lang.String
	 **/
	private String getSendBack(TIncome income) {
		String sendBack="";
		if (CommonConstants.ONE_STRING.equals(income.getFeeType())) {
			EkpIncomeParamManage sendParam = new EkpIncomeParamManage();
			this.copyToEkpManage(income, sendParam);
			R<EkpIncomePushInfoVo> info = ekpDaprUtil.pushManagerInfoToEkp(sendParam);
			if (!Common.isEmpty(info) && Common.isNotNull(info.getData())) {
				sendBack = info.getData().getId();
			}
		} else {
			EkpIncomeParamRisk sendParam = new EkpIncomeParamRisk();
			this.copyToEkpRisk(income, sendParam);
			R<EkpIncomePushInfoVo> info = ekpDaprUtil.pushRiskInfoToEkp(sendParam);
			if (!Common.isEmpty(info) && Common.isNotNull(info.getData())) {
				sendBack = info.getData().getId();
			}
		}
		return sendBack;
	}

	// 复制并保存
	private boolean saveIncome(TIncomeDetail tIncomeDetail,boolean synFlag) {
		TIncome income = new TIncome();
		BeanUtil.copyProperties(tIncomeDetail, income);
		income.setSendStatus(CommonConstants.ZERO_STRING);
		income.setApplyNo(tIncomeDetail.getApplyNo());
		this.save(income);
		if (Common.isNotNull(tIncomeDetail.getRedisKey())) {
			income.setRedisKey(tIncomeDetail.getRedisKey());
		}
		long start = System.currentTimeMillis();
		if (synFlag){
			doJointSocialTask.asynchronousEkpIncome(income);
		}else {
			doJointSocialTask.asynchronousEkpIncomeAsso(income);
		}
		log.info("线程执行耗时："+  (System.currentTimeMillis()-start));
		return true;
	}

	// 复制并保存
	private boolean savePaymentIncome(TIncomeDetail tIncomeDetail, String paymentId) {
		TIncome income = new TIncome();
		BeanUtil.copyProperties(tIncomeDetail, income);
		income.setSendStatus(CommonConstants.ZERO_STRING);
		income.setApplyNo(tIncomeDetail.getApplyNo());
		this.save(income);
		long start = System.currentTimeMillis();
		income.setSourceId(paymentId);
		doJointSocialTask.asynchronousEkpIncomePayment(income,paymentId);
		log.info("线程执行耗时："+  (System.currentTimeMillis()-start));
		return true;
	}

	// 复制并保存
	private boolean savePaymentIncomeNew(TIncomeDetail tIncomeDetail, String paymentId) {
		TIncome income = new TIncome();
		BeanUtil.copyProperties(tIncomeDetail, income);
		income.setSendStatus(CommonConstants.ZERO_STRING);
		income.setApplyNo(tIncomeDetail.getApplyNo());
		this.save(income);
		income.setSourceId(paymentId);
		doJointSocialTask.asynchronousEkpIncomePaymentNew(income,paymentId);
		return true;
	}

	/**
	 * @param income    收入
	 * @param sendParam 目标格式
	 * @Description: 转化格式，传到EKP
	 * @Author: hgw
	 * @Date: 2022/9/5 16:57
	 * @return: void
	 **/
	private void copyToEkpManage(TIncome income, EkpIncomeParamManage sendParam) {
		// 项目编码
		sendParam.setFd_3adfef5e5b9d34(income.getDeptNo());
		// 项目名称
		sendParam.setFd_3adfef5eb6691c(income.getDeptName());
		// 单号
		sendParam.setFd_3adfef7f5d2b52("");
		// 客户编码
		sendParam.setFd_3adfef80202ab2(income.getUnitNo());
		// 客户名称
		sendParam.setFd_3adfef7fc1c886(income.getUnitName());
		// 类型：单选（人，人次，比例，固定值，总额）
		// feeMode收费方式：1按比例2金额-人数3金额-人次
		if (CommonConstants.ONE_STRING.equals(income.getFeeMode())) {
			sendParam.setFd_3adda3037e3bda("比例");
		} else if (CommonConstants.TWO_STRING.equals(income.getFeeMode())) {
			sendParam.setFd_3adda3037e3bda("人数");
		} else {
			sendParam.setFd_3adda3037e3bda("人次");
		}
		// 产生来源：单选（社保，工资，商险）
		// sourceType1社保2公积金3商险4薪资
		if (CommonConstants.THREE_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("商险");
		} else if (CommonConstants.FOUR_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("工资");
		} else if (CommonConstants.TWO_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("公积金");
		} else {
			sendParam.setFd_3adda320daef5a("社保");
		}
		// 姓名
		sendParam.setFd_3adfef948da848(income.getEmpName());
		// 身份证号
		sendParam.setFd_3adfef94dcdbb4(income.getEmpIdcard());
		// 生成月份
		if (Common.isEmpty(income.getCreateMonth()) || income.getCreateMonth().length() != 6) {
			sendParam.setFd_3ae0c23b2e9a92(SocialConstants.YEAR_1970);
		} else {
			sendParam.setFd_3ae0c23b2e9a92(income.getCreateMonth().substring(0, 4)
					+ CommonConstants.CENTER_SPLIT_LINE_STRING + income.getCreateMonth().substring(4, 6));
		}
		// 结算月份
		if (Common.isEmpty(income.getPayMonth()) || income.getPayMonth().length() != 6) {
			sendParam.setFd_3ae0c23cb3fccc(SocialConstants.YEAR_1970);
		} else {
			sendParam.setFd_3ae0c23cb3fccc(income.getPayMonth().substring(0, 4)
					+ CommonConstants.CENTER_SPLIT_LINE_STRING + income.getPayMonth().substring(4, 6));
		}
		// 管理费、风险金金额
		sendParam.setFd_3adfef963bae28(String.valueOf(income.getMoney()));
		// 应收
		sendParam.setFd_3adfefa3daae72(String.valueOf(income.getMoney()));
		// 结算状态
		sendParam.setFd_3adfefaaa3bbd0("未结算");
		// 收款状态
		sendParam.setFd_3adfefaaef583e("未收");
		// 结算单号
		sendParam.setFd_3aead3c68b1078("");
		// 收款单号
		sendParam.setFd_3aeae58b14691c("");
		// 管理费id
		sendParam.setFd_3b13dae9bd70f8(income.getId());
		// 薪酬申请编号
		sendParam.setFd_3b3bf13759b850(income.getApplyNo()==null?"":income.getApplyNo());
	}

	private void copyToEkpRisk(TIncome income, EkpIncomeParamRisk sendParam) {
		// 项目编码
		sendParam.setFd_3adfef5e5b9d34(income.getDeptNo());
		// 项目名称
		sendParam.setFd_3adfef5eb6691c(income.getDeptName());
		// 单号
		sendParam.setFd_3adfef7f5d2b52("");
		// 客户编码
		sendParam.setFd_3adfef80202ab2(income.getUnitNo());
		// 客户名称
		sendParam.setFd_3adfef7fc1c886(income.getUnitName());
		// 类型：单选（人，人次，比例，固定值，总额）
		// feeMode收费方式：1按比例2金额-人数3金额-人次
		if (CommonConstants.ONE_STRING.equals(income.getFeeMode())) {
			sendParam.setFd_3adda3037e3bda("比例");
		} else if (CommonConstants.TWO_STRING.equals(income.getFeeMode())) {
			sendParam.setFd_3adda3037e3bda("人数");
		} else {
			sendParam.setFd_3adda3037e3bda("人次");
		}
		// 产生来源：单选（社保，工资，商险）
		// sourceType1社保2公积金3商险4薪资
		if (CommonConstants.THREE_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("商险");
		} else if (CommonConstants.FOUR_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("工资");
		} else if (CommonConstants.TWO_STRING.equals(income.getSourceType())) {
			sendParam.setFd_3adda320daef5a("公积金");
		} else {
			sendParam.setFd_3adda320daef5a("社保");
		}
		// 姓名
		sendParam.setFd_3adfef948da848(income.getEmpName());
		// 身份证号
		sendParam.setFd_3adfef94dcdbb4(income.getEmpIdcard());
		// 生成月份
		if (Common.isEmpty(income.getCreateMonth()) || income.getCreateMonth().length() != 6) {
			sendParam.setFd_3ae0c3032cffc8(SocialConstants.YEAR_1970);
		} else {
			sendParam.setFd_3ae0c3032cffc8(income.getCreateMonth().substring(0, 4)
					+ CommonConstants.CENTER_SPLIT_LINE_STRING + income.getCreateMonth().substring(4, 6));
		}
		// 结算月份
		if (Common.isEmpty(income.getPayMonth()) || income.getPayMonth().length() != 6) {
			sendParam.setFd_3ae0c3044e5958(SocialConstants.YEAR_1970);
		} else {
			sendParam.setFd_3ae0c3044e5958(income.getPayMonth().substring(0, 4)
					+ CommonConstants.CENTER_SPLIT_LINE_STRING + income.getPayMonth().substring(4, 6));
		}
		// 管理费、风险金金额
		sendParam.setFd_3adfef963bae28(String.valueOf(income.getMoney()));
		// 应收
		sendParam.setFd_3adfefa3daae72(String.valueOf(income.getMoney()));
		// 结算状态
		sendParam.setFd_3adfefaaa3bbd0("未结算");
		// 收款状态
		sendParam.setFd_3adfefaaef583e("未收");
		// 结算单号
		sendParam.setFd_3aead7204bb594("");
		// 收款单号
		sendParam.setFd_3aeae59b70fe5a("");
		// 风险金id
		sendParam.setFd_3b13dac4c03022(income.getId());
		// 薪酬申请编号
		sendParam.setFd_3b3bf0e75ef6c4(income.getApplyNo()==null?"":income.getApplyNo());
	}

	/**
	 * @Description: 明细转统计核心逻辑
	 * @Author: hgw
	 * @Date: 2022/9/2 10:22
	 * @return: boolean
	 **/
	private boolean copyCore(TIncomeDetail tIncomeDetail, List<TIncome> incomeList, List<TIncomeDetail> detailList,
							 String paymentId,boolean synFlag) {
		if (Common.isNotNull(tIncomeDetail.getSourceId())) {
			// 如果该id、该类型的金额已存在，则不允许重复生成推送
			TIncomeDetail a = new TIncomeDetail();
			a.setId(tIncomeDetail.getId());
			a.setSourceId(tIncomeDetail.getSourceId());
			a.setMoney(tIncomeDetail.getMoney());
			a.setRedData(tIncomeDetail.getRedData());
			a.setFeeType(tIncomeDetail.getFeeType());
			int repeatNums = tIncomeDetailService.getTIncomeDetailRepeat(a);
			if (repeatNums > CommonConstants.ZERO_INT) {
				return true;
			}
		}
		// 判断，比例，直接加
		if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getFeeMode())) {
			if (Common.isNotNull(paymentId)) {
				return this.savePaymentIncome(tIncomeDetail,paymentId);
			} else {
				return this.saveIncome(tIncomeDetail,synFlag);
			}
		} else {
			Map<String, Integer> numMap = new HashMap<>();
			Map<String, Integer> incomeMap = new HashMap<>();
			// 商险Map
			Map<String, Integer> insureMap = new HashMap<>();
			Integer nums;
			Integer insureNums;
			for (TIncomeDetail detail : detailList) {
				nums = numMap.get(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(detail.getRedData())) {
					nums--;
				} else {
					nums++;
				}
				numMap.put(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType(), nums);
			}
			for (TIncome income : incomeList) {
				nums = incomeMap.get(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(income.getRedData())) {
					nums--;
				} else {
					nums++;
				}
				incomeMap.put(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType(), nums);

				insureNums = insureMap.get(income.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType());
				if (Common.isEmpty(insureNums)) {
					insureNums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(income.getRedData())) {
					insureNums--;
				} else {
					insureNums++;
				}
				insureMap.put(income.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType(), insureNums);
			}
			// 金额人数、人次，需要判重
			// 社保、公积金(收入来源：1社保2公积金3商险4薪资)
			if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getSourceType())
					|| CommonConstants.TWO_STRING.equals(tIncomeDetail.getSourceType())) {
				if (CommonConstants.ZERO_STRING.equals(tIncomeDetail.getRedData())) {
					if (incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
							|| incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
						if (Common.isNotNull(paymentId)) {
							return this.savePaymentIncome(tIncomeDetail,paymentId);
						} else {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				} else {
					// 红冲判断：当本类型是最大值，才可以红冲
					if (this.redDateJudge(tIncomeDetail, numMap)) {
						if (Common.isNotNull(paymentId)) {
							return this.savePaymentIncome(tIncomeDetail,paymentId);
						} else {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				}
			} else if (CommonConstants.THREE_STRING.equals(tIncomeDetail.getSourceType())) {
				// 商险。收费方式：2金额-人数
				if (CommonConstants.TWO_STRING.equals(tIncomeDetail.getFeeMode())) {
					if (CommonConstants.ZERO_STRING.equals(tIncomeDetail.getRedData())) {
						if (insureMap.get(tIncomeDetail.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
								|| insureMap.get(tIncomeDetail.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					} else {
						if (this.redDateJudge(tIncomeDetail, numMap)) {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				} else {
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap,synFlag);
				}
			} else {
				// 薪资。收费方式：2金额-人数
				if (CommonConstants.TWO_STRING.equals(tIncomeDetail.getFeeMode())) {
					if (incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
							|| incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
						return this.saveIncome(tIncomeDetail,synFlag);
					}
				} else {
					// 3金额-人次
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap,synFlag);
				}
			}
		}
		if (Common.isNotNull(paymentId)) {
			tPaymentInfoMapper.updateBySocialIncomeFlag(paymentId);
		}
		return true;
	}

	/**
	 * @Description: 明细转统计核心逻辑
	 * @Author: hgw
	 * @Date: 2022/9/2 10:22
	 * @return: boolean
	 **/
	private boolean copyCoreNew(TIncomeDetail tIncomeDetail, List<TIncome> incomeList, List<TIncomeDetail> detailList,
							 String paymentId,boolean synFlag) {
		if (Common.isNotNull(tIncomeDetail.getSourceId())) {
			// 如果该id、该类型的金额已存在，则不允许重复生成推送
			TIncomeDetail a = new TIncomeDetail();
			a.setId(tIncomeDetail.getId());
			a.setSourceId(tIncomeDetail.getSourceId());
			a.setMoney(tIncomeDetail.getMoney());
			a.setRedData(tIncomeDetail.getRedData());
			a.setFeeType(tIncomeDetail.getFeeType());
			int repeatNums = tIncomeDetailService.getTIncomeDetailRepeat(a);
			if (repeatNums > CommonConstants.ZERO_INT) {
				return true;
			}
		}
		// 判断，比例，直接加
		if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getFeeMode())) {
			if (Common.isNotNull(paymentId)) {
				return this.savePaymentIncomeNew(tIncomeDetail,paymentId);
			} else {
				return this.saveIncome(tIncomeDetail,synFlag);
			}
		} else {
			Map<String, Integer> numMap = new HashMap<>();
			Map<String, Integer> incomeMap = new HashMap<>();
			// 商险Map
			Map<String, Integer> insureMap = new HashMap<>();
			Integer nums;
			Integer insureNums;
			for (TIncomeDetail detail : detailList) {
				nums = numMap.get(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(detail.getRedData())) {
					nums--;
				} else {
					nums++;
				}
				numMap.put(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType(), nums);
			}
			for (TIncome income : incomeList) {
				nums = incomeMap.get(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(income.getRedData())) {
					nums--;
				} else {
					nums++;
				}
				incomeMap.put(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType(), nums);

				insureNums = insureMap.get(income.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType());
				if (Common.isEmpty(insureNums)) {
					insureNums = CommonConstants.ZERO_INT;
				}
				if (CommonConstants.ONE_STRING.equals(income.getRedData())) {
					insureNums--;
				} else {
					insureNums++;
				}
				insureMap.put(income.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType(), insureNums);
			}
			// 金额人数、人次，需要判重
			// 社保、公积金(收入来源：1社保2公积金3商险4薪资)
			if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getSourceType())
					|| CommonConstants.TWO_STRING.equals(tIncomeDetail.getSourceType())) {
				if (CommonConstants.ZERO_STRING.equals(tIncomeDetail.getRedData())) {
					if (incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
							|| incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
						if (Common.isNotNull(paymentId)) {
							return this.savePaymentIncomeNew(tIncomeDetail,paymentId);
						} else {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				} else {
					// 红冲判断：当本类型是最大值，才可以红冲
					if (this.redDateJudge(tIncomeDetail, numMap)) {
						if (Common.isNotNull(paymentId)) {
							return this.savePaymentIncomeNew(tIncomeDetail,paymentId);
						} else {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				}
			} else if (CommonConstants.THREE_STRING.equals(tIncomeDetail.getSourceType())) {
				// 商险。收费方式：2金额-人数
				if (CommonConstants.TWO_STRING.equals(tIncomeDetail.getFeeMode())) {
					if (CommonConstants.ZERO_STRING.equals(tIncomeDetail.getRedData())) {
						if (insureMap.get(tIncomeDetail.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
								|| insureMap.get(tIncomeDetail.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					} else {
						if (this.redDateJudge(tIncomeDetail, numMap)) {
							return this.saveIncome(tIncomeDetail,synFlag);
						}
					}
				} else {
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap,synFlag);
				}
			} else {
				// 薪资。收费方式：2金额-人数
				if (CommonConstants.TWO_STRING.equals(tIncomeDetail.getFeeMode())) {
					if (incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) == null
							|| incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()) <= CommonConstants.ZERO_INT) {
						return this.saveIncome(tIncomeDetail,synFlag);
					}
				} else {
					// 3金额-人次
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap,synFlag);
				}
			}
		}
		if (Common.isNotNull(paymentId)) {
			tPaymentInfoMapper.updateBySocialIncomeFlag(paymentId);
		}
		return true;
	}

	/**
	 * @Description: 红冲判断
	 * @Author: hgw
	 * @Date: 2022/9/7 17:27
	 * @return: boolean
	 **/
	private boolean redDateJudge(TIncomeDetail tIncomeDetail, Map<String, Integer> numMap) {
		Integer socialNum = CommonConstants.ZERO_INT;
		Integer fundNum = CommonConstants.ZERO_INT;
		Integer insureNum = CommonConstants.ZERO_INT;
		Integer salaryNum = CommonConstants.ZERO_INT;
		Integer myNum = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getSourceType()
				+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
		if (!CommonConstants.ONE_STRING.equals(tIncomeDetail.getSourceType())) {
			socialNum = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + CommonConstants.ONE_STRING
					+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
		}
		if (!CommonConstants.TWO_STRING.equals(tIncomeDetail.getSourceType())) {
			fundNum = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + CommonConstants.TWO_STRING
					+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
		}
		if (!CommonConstants.THREE_STRING.equals(tIncomeDetail.getSourceType())) {
			insureNum = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + CommonConstants.THREE_STRING
					+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
		}
		if (!CommonConstants.FOUR_STRING.equals(tIncomeDetail.getSourceType())) {
			salaryNum = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + CommonConstants.FOUR_STRING
					+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
		}
		// 红冲判断：当本类型是最大值，才可以红冲
		if (myNum != null && myNum > ifNullToZero(socialNum) && myNum > ifNullToZero(fundNum)
				&& myNum > ifNullToZero(insureNum) && myNum > ifNullToZero(salaryNum)) {
			return true;
		}
		return false;
	}

	private int ifNullToZero(Integer num) {
		if (num == null) {
			return CommonConstants.ZERO_INT;
		}
		return num;
	}

	/**
	 * @Description: 人次：各个模式累加逻辑
	 * @Author: hgw
	 * @Date: 2022/9/1 18:17
	 * @return: boolean
	 **/
	private boolean judgeMixModel(TIncomeDetail tIncomeDetail, Map<String, Integer> numMap, Map<String, Integer> incomeMap,boolean synFlag) {
		String month = tIncomeDetail.getPayMonth();
		if (CommonConstants.THREE_STRING.equals(tIncomeDetail.getSourceType())) {
			month = tIncomeDetail.getDataCreateMonth();
		}
		if (CommonConstants.ZERO_STRING.equals(tIncomeDetail.getRedData())) {
			Integer nums = numMap.get(month + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getSourceType()
					+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
			Integer maxNum = incomeMap.get(month + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType());
			// 当明细的次数大于总次数，才可以新增统计
			if (Common.isEmpty(maxNum) || ifNullToZero(nums) >= maxNum) {
				return this.saveIncome(tIncomeDetail,synFlag);
			}
		} else {
			// 红冲判断：当本类型是最大值，才可以红冲
			if (this.redDateJudge(tIncomeDetail, numMap)) return this.saveIncome(tIncomeDetail,synFlag);
		}
		return true;
	}

	/**
	 * @param applyNo
	 * @Description: 删除薪资关联的收入明细
	 * @Author: hgw
	 * @Date: 2022/11/4 17:03
	 * @return: boolean
	 **/
	public void deleteIncomeAndDetailByApplyNo(String applyNo) {
		baseMapper.deleteIncomeByApplyNo(applyNo);
		baseMapper.deleteIncomeDetailByApplyNo(applyNo);
	}

	/**
	 * @param idSet
	 * @param dept
	 * @Description: ekp费用划转-收入
	 * @Author: hgw
	 * @Date: 2022/11/17 9:42
	 * @return: void
	 **/
	public void changeIncomeAndDetailDept(Set<String> idSet, TSettleDomainSelectVo dept) {
		baseMapper.changeIncomeDept(idSet, dept);
		baseMapper.changeIncomeDetailDept(idSet, dept);
	}

	@Override
	public Boolean updateIncomeSettleStatus(List<EkpInsuranceViewVo> viewVoList) {
		try {
			if (!viewVoList.isEmpty()) {
				TIncome income;
				for (EkpInsuranceViewVo viewVo : viewVoList) {
					//根据明细id更新结算状态
					income = baseMapper.selectById(viewVo.getId());
					if (Common.isNotNull(income)) {
						income.setIncomeSettleFlag(viewVo.getIncomeSettleFlag());
						income.setIncomeCollectFlag(viewVo.getIncomeCollectFlag());
						baseMapper.updateById(income);
					}
				}
			}
		} catch (Exception e) {
			log.error("更新收入结算状态失败", e);
			return false;
		}
		return true;
	}

}
