/*
 *    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.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.metadata.IPage;
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.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.service.TIncomeDetailService;
import com.yifu.cloud.plus.v1.yifu.social.service.TIncomeService;
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;

	/**
	 * 收入明细表简单分页查询
	 *
	 * @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, null, 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 = EasyExcel.write(out, IncomeExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo, null, Common.getList(searchVo.getIds()), CommonConstants.EMPTY_STRING);
					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 = EasyExcel.writerSheet("收入明细表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("收入明细表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error(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> settleDomainIds,
										   List<String> ids,
										   String sql) {
		return baseMapper.noPageDiy(searchVo, settleDomainIds, ids, sql);
	}

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

	@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 {
			EasyExcel.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);
			// 数据合法情况 TODO

			// 插入
			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;
		}
		tIncomeDetail.setCreateTime(new Date());
		tIncomeDetail.setDataCreateMonth(DateUtil.addMonth(0));
		tIncomeDetailService.save(tIncomeDetail);

		// 获取对应信息的统计表，根据项目配置，判断是否可以加一条统计：
		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);
		// 不存在，直接新增
		if (incomeList == null || incomeList.isEmpty()) {
			return this.saveIncome(tIncomeDetail);
		} else {
			// 核心判断
			return this.copyCore(tIncomeDetail, incomeList, detailList);
		}
	}

	// 复制并保存
	private boolean saveIncome(TIncomeDetail tIncomeDetail) {
		TIncome income = new TIncome();
		BeanUtil.copyProperties(tIncomeDetail, income);
		income.setPushStatus(CommonConstants.ZERO_STRING);
		return this.save(income);
	}

	/**
	 * @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;
			for (TIncomeDetail detail : detailList) {
				nums = numMap.get(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getRedData());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ONE_INT;
				} else {
					nums++;
				}
				numMap.put(detail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + detail.getSourceType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + detail.getRedData(), nums);
			}
			for (TIncome income : incomeList) {
				nums = incomeMap.get(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + income.getRedData());
				if (Common.isEmpty(nums)) {
					nums = CommonConstants.ONE_INT;
				} else {
					nums++;
				}
				incomeMap.put(income.getPayMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + income.getRedData(), nums);
				insureMap.put(income.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + income.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + income.getRedData(), CommonConstants.ZERO_INT);
			}
			// 金额人数、人次，需要判重
			// 社保、公积金(收入来源：1社保2公积金3商险4薪资)
			if (CommonConstants.ONE_STRING.equals(tIncomeDetail.getSourceType())
					|| CommonConstants.TWO_STRING.equals(tIncomeDetail.getSourceType())) {
				if (incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()
						+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getRedData()) == null) {
					return this.saveIncome(tIncomeDetail);
				}
			} else if (CommonConstants.THREE_STRING.equals(tIncomeDetail.getSourceType())) {
				// 商险。收费方式：2金额-人数
				if (CommonConstants.TWO_STRING.equals(tIncomeDetail.getFeeMode())) {
					if (insureMap.get(tIncomeDetail.getDataCreateMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()
							+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getRedData()) == null) {
						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()
							+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getRedData()) == null) {
						return this.saveIncome(tIncomeDetail);
					}
				} else {
					// 3金额-人次
					// 各个模式累加逻辑：
					return this.judgeMixModel(tIncomeDetail, numMap, incomeMap);
				}
			}
		}
		return true;
	}

	/**
	 * @Description: 人次：各个模式累加逻辑
	 * @Author: hgw
	 * @Date: 2022/9/1 18:17
	 * @return: boolean
	 **/
	private boolean judgeMixModel(TIncomeDetail tIncomeDetail, Map<String, Integer> numMap, Map<String, Integer> incomeMap) {
		Integer nums = numMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getSourceType()
				+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()
				+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getRedData());
		Integer maxNum = incomeMap.get(tIncomeDetail.getPayMonth() + CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getFeeType()
				+ CommonConstants.DOWN_LINE_STRING + tIncomeDetail.getRedData());
		// 当明细的次数大于总次数，才可以新增统计
		if (Common.isEmpty(maxNum) || nums > maxNum) {
			return this.saveIncome(tIncomeDetail);
		}
		return false;
	}


}
