/*
 *    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.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
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.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.entity.TPaymentInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSendEkpError;
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.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 TPaymentInfoMapper tPaymentInfoMapper;

	/**
	 * 收入明细表简单分页查询
	 *
	 * @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) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo, Common.getList(searchVo.getIds()));
					if (Common.isNotNull(list)) {
						ExcelUtil<IncomeExportVo> util = new ExcelUtil<>(IncomeExportVo.class);
						for (IncomeExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet("收入明细表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						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
	 **/
	@Override
	public boolean saveDetail(TIncomeDetail tIncomeDetail) {
		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);
		} else {
			// 核心判断
			return this.copyCore(tIncomeDetail, incomeList, detailList);
		}
	}

	/**
	 * @Description: 新增收入明细-详情表，同时统计；
	 * @Author: hgw
	 * @Date: 2022/8/31 16:34
	 * @return: boolean
	 **/
	@Override
	public void saveBathDetail(List<TIncomeDetail> tIncomeDetailList) {
		Map<String,Integer> map = new HashMap<>();
		Map<String,String> idMap = new HashMap<>();
		for (TIncomeDetail tIncomeDetail : tIncomeDetailList) {
			// 获取对应信息的统计表，根据项目配置，判断是否可以加一条统计：
			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);
			tPaymentInfoMapper.updateByIncome(tIncomeDetail.getSourceId());
			// 不存在，直接新增
			if (incomeList == null || incomeList.isEmpty()) {
				BeanUtil.copyProperties(tIncomeDetail, income);
				income.setSendStatus(CommonConstants.ZERO_STRING);
				this.save(income);
				String sendBack = this.getSendBack(income);
				income.setSendTime(new Date());
				if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
					income.setSendStatus(CommonConstants.ONE_STRING);
					income.setSendMonth(DateUtil.addMonth(0));
					income.setEkpId(sendBack);
				} else {
					if (map.get(sendBack) > 0) {
						int i = map.get(sendBack) + 1;
						map.put(sendBack,i);
						idMap.put(sendBack,income.getId());
						//单个异常超过十次，保存异常内容
						if (i >= 10) {
							for (String key: map.keySet()) {
								TSendEkpError error = new TSendEkpError();
								error.setCreateTime(new Date());
								error.setCreateDay(DateUtil.getThisDay());
								error.setType(CommonConstants.FIVE_STRING);
								error.setLinkId(income.getId());
								error.setTitle(key);
								error.setNums(map.get(key));
								tSendEkpErrorService.save(error);
							}
							break;
						}
					} else {
						map.put(sendBack,1);
						idMap.put(sendBack,income.getId());
					}
				}
				this.updateById(income);
			} else {
				// 判断，比例，直接加
				if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getFeeMode())) {
					BeanUtil.copyProperties(tIncomeDetail, income);
					income.setSendStatus(CommonConstants.ZERO_STRING);
					this.save(income);
					String sendBack = this.getSendBack(income);
					income.setSendTime(new Date());
					if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
						income.setSendStatus(CommonConstants.ONE_STRING);
						income.setSendMonth(DateUtil.addMonth(0));
						income.setEkpId(sendBack);
					} else {
						if (map.get(sendBack) > 0) {
							int i = map.get(sendBack) + 1;
							map.put(sendBack,i);
							idMap.put(sendBack,income.getId());
							//单个异常超过十次，保存异常内容
							if (i >= 10) {
								for (String key: map.keySet()) {
									TSendEkpError error = new TSendEkpError();
									error.setCreateTime(new Date());
									error.setCreateDay(DateUtil.getThisDay());
									error.setType(CommonConstants.FIVE_STRING);
									error.setLinkId(income.getId());
									error.setTitle(key);
									error.setNums(map.get(key));
									tSendEkpErrorService.save(error);
								}
								break;
							}
						} else {
							map.put(sendBack,1);
							idMap.put(sendBack,income.getId());
						}
					}
					this.updateById(income);
				} 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 detail1 : detailList) {
						nums = numMap.get(detail1.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail1.getSourceType()
								+ CommonConstants.DOWN_LINE_STRING + detail1.getFeeType());
						if (Common.isEmpty(nums)) {
							nums = CommonConstants.ZERO_INT;
						}
						if (CommonConstants.ONE_STRING.equals(detail1.getRedData())) {
							nums--;
						} else {
							nums++;
						}
						numMap.put(detail1.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail1.getSourceType()
								+ CommonConstants.DOWN_LINE_STRING + detail1.getFeeType(), nums);
					}
					for (TIncome income1 : incomeList) {
						nums = incomeMap.get(income1.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income1.getFeeType());
						if (Common.isEmpty(nums)) {
							nums = CommonConstants.ZERO_INT;
						}
						if (CommonConstants.ONE_STRING.equals(income1.getRedData())) {
							nums--;
						} else {
							nums++;
						}
						incomeMap.put(income1.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income1.getFeeType(), nums);

						insureNums = insureMap.get(income1.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income1.getFeeType());
						if (Common.isEmpty(insureNums)) {
							insureNums = CommonConstants.ZERO_INT;
						}
						if (CommonConstants.ONE_STRING.equals(income1.getRedData())) {
							insureNums--;
						} else {
							insureNums++;
						}
						insureMap.put(income1.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income1.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) {
								BeanUtil.copyProperties(tIncomeDetail, income);
								income.setSendStatus(CommonConstants.ZERO_STRING);
								this.save(income);
								String sendBack = this.getSendBack(income);
								income.setSendTime(new Date());
								if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
									income.setSendStatus(CommonConstants.ONE_STRING);
									income.setSendMonth(DateUtil.addMonth(0));
									income.setEkpId(sendBack);
								} else {
									if (map.get(sendBack) > 0) {
										int i = map.get(sendBack) + 1;
										map.put(sendBack,i);
										idMap.put(sendBack,income.getId());
										//单个异常超过十次，保存异常内容
										if (i >= 10) {
											for (String key: map.keySet()) {
												TSendEkpError error = new TSendEkpError();
												error.setCreateTime(new Date());
												error.setCreateDay(DateUtil.getThisDay());
												error.setType(CommonConstants.FIVE_STRING);
												error.setLinkId(income.getId());
												error.setTitle(key);
												error.setNums(map.get(key));
												tSendEkpErrorService.save(error);
											}
											break;
										}
									} else {
										map.put(sendBack,1);
										idMap.put(sendBack,income.getId());
									}
								}
								this.updateById(income);
							}
						} else {
							// 红冲判断：当本类型是最大值，才可以红冲
							if (this.redDateJudge(tIncomeDetail, numMap)) {
								BeanUtil.copyProperties(tIncomeDetail, income);
								income.setSendStatus(CommonConstants.ZERO_STRING);
								this.save(income);
								String sendBack = this.getSendBack(income);
								income.setSendTime(new Date());
								if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
									income.setSendStatus(CommonConstants.ONE_STRING);
									income.setSendMonth(DateUtil.addMonth(0));
									income.setEkpId(sendBack);
								} else {
									if (map.get(sendBack) > 0) {
										int i = map.get(sendBack) + 1;
										map.put(sendBack,i);
										idMap.put(sendBack,income.getId());
										//单个异常超过十次，保存异常内容
										if (i >= 10) {
											for (String key: map.keySet()) {
												TSendEkpError error = new TSendEkpError();
												error.setCreateTime(new Date());
												error.setCreateDay(DateUtil.getThisDay());
												error.setType(CommonConstants.FIVE_STRING);
												error.setLinkId(income.getId());
												error.setTitle(key);
												error.setNums(map.get(key));
												tSendEkpErrorService.save(error);
											}
											break;
										}
									} else {
										map.put(sendBack,1);
										idMap.put(sendBack,income.getId());
									}
								}
								this.updateById(income);
							}
						}
					} 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) {
									BeanUtil.copyProperties(tIncomeDetail, income);
									income.setSendStatus(CommonConstants.ZERO_STRING);
									this.save(income);
									String sendBack = this.getSendBack(income);
									income.setSendTime(new Date());
									if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
										income.setSendStatus(CommonConstants.ONE_STRING);
										income.setSendMonth(DateUtil.addMonth(0));
										income.setEkpId(sendBack);
									} else {
										if (map.get(sendBack) > 0) {
											int i = map.get(sendBack) + 1;
											map.put(sendBack,i);
											idMap.put(sendBack,income.getId());
											//单个异常超过十次，保存异常内容
											if (i >= 10) {
												for (String key: map.keySet()) {
													TSendEkpError error = new TSendEkpError();
													error.setCreateTime(new Date());
													error.setCreateDay(DateUtil.getThisDay());
													error.setType(CommonConstants.FIVE_STRING);
													error.setLinkId(income.getId());
													error.setTitle(key);
													error.setNums(map.get(key));
													tSendEkpErrorService.save(error);
												}
												break;
											}
										} else {
											map.put(sendBack,1);
											idMap.put(sendBack,income.getId());
										}
									}
									this.updateById(income);
								}
							} else {
								if (this.redDateJudge(tIncomeDetail, numMap)) {
									BeanUtil.copyProperties(tIncomeDetail, income);
									income.setSendStatus(CommonConstants.ZERO_STRING);
									this.save(income);
									String sendBack = this.getSendBack(income);
									income.setSendTime(new Date());
									if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
										income.setSendStatus(CommonConstants.ONE_STRING);
										income.setSendMonth(DateUtil.addMonth(0));
										income.setEkpId(sendBack);
									} else {
										if (map.get(sendBack) > 0) {
											int i = map.get(sendBack) + 1;
											map.put(sendBack,i);
											idMap.put(sendBack,income.getId());
											//单个异常超过十次，保存异常内容
											if (i >= 10) {
												for (String key: map.keySet()) {
													TSendEkpError error = new TSendEkpError();
													error.setCreateTime(new Date());
													error.setCreateDay(DateUtil.getThisDay());
													error.setType(CommonConstants.FIVE_STRING);
													error.setLinkId(income.getId());
													error.setTitle(key);
													error.setNums(map.get(key));
													tSendEkpErrorService.save(error);
												}
												break;
											}
										} else {
											map.put(sendBack,1);
											idMap.put(sendBack,income.getId());
										}
									}
									this.updateById(income);
								}
							}
						} else {
							// 各个模式累加逻辑：
							this.judgeMixModel(tIncomeDetail, numMap, incomeMap);
						}
					} 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) {
								BeanUtil.copyProperties(tIncomeDetail, income);
								income.setSendStatus(CommonConstants.ZERO_STRING);
								this.save(income);
								String sendBack = this.getSendBack(income);
								income.setSendTime(new Date());
								if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
									income.setSendStatus(CommonConstants.ONE_STRING);
									income.setSendMonth(DateUtil.addMonth(0));
									income.setEkpId(sendBack);
								} else {
									if (map.get(sendBack) > 0) {
										int i = map.get(sendBack) + 1;
										map.put(sendBack,i);
										idMap.put(sendBack,income.getId());
										//单个异常超过十次，保存异常内容
										if (i >= 10) {
											for (String key: map.keySet()) {
												TSendEkpError error = new TSendEkpError();
												error.setCreateTime(new Date());
												error.setCreateDay(DateUtil.getThisDay());
												error.setType(CommonConstants.FIVE_STRING);
												error.setLinkId(income.getId());
												error.setTitle(key);
												error.setNums(map.get(key));
												tSendEkpErrorService.save(error);
											}
											break;
										}
									} else {
										map.put(sendBack,1);
										idMap.put(sendBack,income.getId());
									}
								}
								this.updateById(income);
							}
						} else {
							// 3金额-人次
							// 各个模式累加逻辑：
							this.judgeMixModel(tIncomeDetail, numMap, incomeMap);
						}
					}
				}
			}
		}
		for (String key: map.keySet()) {
			TSendEkpError error = new TSendEkpError();
			error.setCreateTime(new Date());
			error.setCreateDay(DateUtil.getThisDay());
			error.setType(CommonConstants.FIVE_STRING);
			error.setLinkId(idMap.get(key));
			error.setTitle(key);
			error.setNums(map.get(key));
			tSendEkpErrorService.save(error);
		}
	}

	@Override
	public void pushDetail() {
		List<TIncome> list = baseMapper.selectList(Wrappers.<TIncome>query().lambda()
				.eq(TIncome::getSendStatus, CommonConstants.ZERO_STRING));
		String sendBack;
		Map<String,Integer> map = new HashMap<>();
		Map<String,String> idMap = new HashMap<>();
		//收入更新
		List<TIncome> updateList = new ArrayList<>();
		for (TIncome income : list) {
			sendBack = this.getSendBack(income);
			income.setSendTime(new Date());
			if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
				income.setSendStatus(CommonConstants.ONE_STRING);
				income.setSendMonth(DateUtil.addMonth(0));
				income.setEkpId(sendBack);
				updateList.add(income);
				if (updateList.size() >= CommonConstants.FIVES_INT) {
					baseMapper.updateIncomeById(updateList);
					updateList.clear();
				}
			} else {
				if (map.get(sendBack) > 0) {
					int i = map.get(sendBack) + 1;
					map.put(sendBack,i);
					idMap.put(sendBack,income.getId());
					//单个异常超过十次，保存异常内容
					if (i >= 10) {
						baseMapper.updateIncomeById(updateList);
						for (String key: map.keySet()) {
							TSendEkpError error = new TSendEkpError();
							error.setCreateTime(new Date());
							error.setCreateDay(DateUtil.getThisDay());
							error.setType(CommonConstants.FIVE_STRING);
							error.setLinkId(income.getId());
							error.setTitle(key);
							error.setNums(map.get(key));
							tSendEkpErrorService.save(error);
						}
						break;
					}
				} else {
					map.put(sendBack,1);
					idMap.put(sendBack,income.getId());
				}
			}
		}
		for (String key: map.keySet()) {
			TSendEkpError error = new TSendEkpError();
			error.setCreateTime(new Date());
			error.setCreateDay(DateUtil.getThisDay());
			error.setType(CommonConstants.FIVE_STRING);
			error.setLinkId(idMap.get(key));
			error.setTitle(key);
			error.setNums(map.get(key));
			tSendEkpErrorService.save(error);
		}
		baseMapper.updateIncomeById(updateList);
	}

	/**
	 * @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);
			sendBack = ekpIncomeUtil.sendToEkpManage(sendParam);
		} else {
			EkpIncomeParamRisk sendParam = new EkpIncomeParamRisk();
			this.copyToEkpRisk(income, sendParam);
			sendBack = ekpIncomeUtil.sendToEkpRisk(sendParam);
		}
		return sendBack;
	}

	// 复制并保存
	private boolean saveIncome(TIncomeDetail tIncomeDetail) {
		TIncome income = new TIncome();
		BeanUtil.copyProperties(tIncomeDetail, income);
		income.setSendStatus(CommonConstants.ZERO_STRING);
		this.save(income);
		String sendBack = this.getSendBack(income);
		if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
			sendBack = this.getSendBack(income);
		}
		income.setSendTime(new Date());
		if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
			income.setSendStatus(CommonConstants.ONE_STRING);
			income.setSendMonth(DateUtil.addMonth(0));
			income.setEkpId(sendBack);
		} else {
			TSendEkpError error = new TSendEkpError();
			error.setCreateTime(new Date());
			error.setCreateDay(DateUtil.getThisDay());
			error.setType(CommonConstants.FOUR_STRING);
			error.setCreateUserName("收入表推送");
			error.setLinkId(income.getId());
			error.setTitle(sendBack);
			error.setNums(CommonConstants.ONE_INT);
			tSendEkpErrorService.saveError(error);
		}
		return this.updateById(income);
	}

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

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

	/**
	 * @Description: 明细转统计核心逻辑
	 * @Author: hgw
	 * @Date: 2022/9/2 10:22
	 * @return: boolean
	 **/
	private boolean copyCore(TIncomeDetail tIncomeDetail, List<TIncome> incomeList, List<TIncomeDetail> detailList) {
		// 判断，比例，直接加
		if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getFeeMode())) {
			return this.saveIncome(tIncomeDetail);
		} 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) {
						return this.saveIncome(tIncomeDetail);
					}
				} else {
					// 红冲判断：当本类型是最大值，才可以红冲
					if (this.redDateJudge(tIncomeDetail, numMap)) return this.saveIncome(tIncomeDetail);
				}
			} 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);
						}
					} else {
						if (this.redDateJudge(tIncomeDetail, numMap)) return this.saveIncome(tIncomeDetail);
					}
				} else {
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap);
				}
			} 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);
					}
				} else {
					// 3金额-人次
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap);
				}
			}
		}
		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) {
		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);
			}
		} else {
			// 红冲判断：当本类型是最大值，才可以红冲
			if (this.redDateJudge(tIncomeDetail, numMap)) return this.saveIncome(tIncomeDetail);
		}
		return true;
	}

}
