package cn.superdesk.uniorder.service.invoice.supplier.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.superdesk.uniorder.common.enums.common.CommonOrderGoodsUnitEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.common.excel.utils.ExcelExportModeEasyExcelUtils;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.excel.biz.SugarUpBigDecimalCellWriteHandler;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.dao.entity.invoice.common.InvoiceType;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.invoice.common.InvoiceTypeCacheCriteria;
import cn.superdesk.uniorder.dto.vo.invoice.supplier.InvoiceApplySupplierDetailDimGoodsItemVo;
import cn.superdesk.uniorder.dto.vo.organisation.SysPlatformExtInvoiceVo;
import cn.superdesk.uniorder.notify.NotifyUtils;
import cn.superdesk.uniorder.service.invoice.common.InvoiceTypeService;
import cn.superdesk.uniorder.service.invoice.supplier.InvoiceApplySupplierExportExcelService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2021/12/10 下午5:47
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/12/10 下午5:47
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class InvoiceApplySupplierExportExcelServiceImpl implements InvoiceApplySupplierExportExcelService {

	@Autowired
	private InvoiceTypeService invoiceTypeService;

	@Autowired
	private ResourceConstant resourceConstant;

	private static Map<Integer, String[]> mapperHead  = new HashMap<>();
	private static Map<Integer, String[]> mapperValue = new HashMap<>();

	private static Map<Integer, String[]> mapperHeadMerge  = new HashMap<>();
	private static Map<Integer, String[]> mapperValueMerge = new HashMap<>();

	static {

		// 初始化
//		modeOfExportExcelInvoiceApplyFocusScoreDimCredit.put(1, (mode) -> getHead(fieldHeadMode1Static));
//		modeOfExportExcelInvoiceApplyFocusScoreDimCredit.put(2, (mode) -> getHead(fieldHeadMode2Static));
//		modeOfExportExcelInvoiceApplyFocusScoreDimCredit.put(3, (mode) -> getHead(fieldHeadMode3Static));

		mapperHead.put(1, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldHeadMode1Static);
		mapperHead.put(2, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldHeadMode2Static);
		mapperHead.put(3, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldHeadMode3Static);

		mapperValue.put(1, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldValueMode1Static);
		mapperValue.put(2, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldValueMode2Static);
		mapperValue.put(3, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldValueMode3Static);

//		mapperHeadMerge.put(1, InvoiceApplyExportExcelFocusScoreDimCreditStatic.fieldHeadMode1StaticMerge);
		mapperHeadMerge.put(2, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldHeadMode2StaticMerge);
		mapperHeadMerge.put(3, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldHeadMode3StaticMerge);

//		mapperValueMerge.put(1, InvoiceApplyExportExcelFocusScoreDimCreditStatic.fieldValueMode1StaticMerge);
		mapperValueMerge.put(2, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldValueMode2StaticMerge);
		mapperValueMerge.put(3, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fieldValueMode3StaticMerge);
	}

	private static final String TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_1 = "exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode1.xlsx";
	private static final String TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_2 = "exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode2.xlsx";
	private static final String TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_3 = "exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode3.xlsx";// 导出开票数据

	// 侨城汇
	//	|---- 1. 搜索框 条件 结算集
	//	|---- 2. 搜索框 条件 结算集 后 界面上 勾选 要以 开票申请编号 分 sheet 分合并前 合并后
	//	|---- 3. 搜索框 条件 结算集 后 界面上 勾选 要以 开票申请编号 分 sheet 财务专用
	public SysNotify exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode1(List<InvoiceApplySupplierDetailDimGoodsItemVo> resultList) {

		String excelExportPathRoot             = resourceConstant.getPathRoot();
		String excelExportRelativePathTemplate = resourceConstant.getPathTemplate();
		String excelExportRelativePathStorage  = resourceConstant.getPathStorage();

		String relativePath = File.separator + "excel" + File.separator + "invoice" + File.separator + "supplier" + File.separator;

		String templateRelativePath = excelExportPathRoot + excelExportRelativePathTemplate + relativePath;
		String templateFullPath;

		String targetFullPath          = excelExportPathRoot + excelExportRelativePathStorage;
		String targetFileName          = "供应商结算" + "_" + "发票(开票申请)_" + "导出报表" + ExcelResponse.addTail() + ".xlsx";
		String targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;

//		if (!FileUtil.exist(targetWriteFileFullPath)) {
//			FileUtil.mkdir(targetWriteFileFullPath);
//		}
		FileUtil.touch(targetWriteFileFullPath);

		/******************************************  start ******************************************/

		ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath);
		ExcelWriter        excelWriter        = null;

		WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "发票申请-结果模式").build();
		FillConfig fillConfig  = FillConfig.builder().forceNewRow(Boolean.FALSE).build();


		// 文件
		templateFullPath = templateRelativePath + TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_1;

		excelWriter = excelWriterBuilder.withTemplate(templateFullPath).build();
		excelWriter.fill(new FillWrapper("detail", resultList), fillConfig, writeSheet0);

		// 别忘记关闭流
		excelWriter.finish();


		/******************************************  start ******************************************/

		return NotifyUtils.createSysNotify(
				targetFileName,
				relativePath + targetFileName,
				SysQuartzScheduleTaskStatementOfAccountRunStateEnum.成功
		);
	}

	public SysNotify exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode2(List<InvoiceApplySupplierDetailDimGoodsItemVo> resultList) {

		String excelExportPathRoot             = resourceConstant.getPathRoot();
		String excelExportRelativePathTemplate = resourceConstant.getPathTemplate();
		String excelExportRelativePathStorage  = resourceConstant.getPathStorage();

		String relativePath = File.separator + "excel" + File.separator + "invoice" + File.separator + "supplier" + File.separator;

		String templateRelativePath = excelExportPathRoot + excelExportRelativePathTemplate + relativePath;
		String templateFullPath;


		String targetFullPath = excelExportPathRoot + excelExportRelativePathStorage;
		// ZIP 积分结算_开票明细_操作导出按钮_202105081028
		String targetZipFileName          = "供应商结算" + "_" + "发票(开票申请)" + "_" + "勾选导出报表" + ExcelResponse.addTail() + ".zip";
		String targetZipWriteFileFullPath = targetFullPath + relativePath + targetZipFileName;

//		if (!FileUtil.exist(targetWriteFileFullPath)) {
//			FileUtil.mkdir(targetWriteFileFullPath);
//		}
		FileUtil.touch(targetZipWriteFileFullPath);

		/******************************************  start ******************************************/

//		ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath)
////				.inMemory(Boolean.TRUE)
//				;
//		ExcelWriter excelWriter = null;

		templateFullPath = templateRelativePath + TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_2;
//		excelWriter = excelWriterBuilder
////				.withTemplate(templateFullPath)
//				.build();

		// 得到处理后的数据
		Map<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> resultMap = mergeResultByExcelDebugAndCreateWorkbook(2, resultList);

		// 初始化Excel文件列表
		List<File> excelFileList = new ArrayList<>();

		try {
			int sheetNo = 0;
			for (Map.Entry<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> _entry : resultMap.entrySet()) {

				String outSaleName = AnStringUtils.stringListConvertToString(_entry.getValue()
						.getTransferListBySheet()
						.stream()
						.map(InvoiceApplySupplierDetailDimGoodsItemVo::getSaleName)
						.distinct()
						.collect(Collectors.toList())
				);
				String invoiceApplySn = _entry.getKey();
				String accountingOrderSn = AnStringUtils.stringListConvertToString(_entry.getValue()
						.getTransferListBySheet()
						.stream()
						.map(InvoiceApplySupplierDetailDimGoodsItemVo::getAccountingOrderSn)
						.distinct()
						.collect(Collectors.toList())
				);


				// Excel 企业名称+开票申请单号+结算单编号
//				String targetXlsxFileName          = outVirtName + "_" + invoiceApplySn + "_" + accountingOrderSn + ExcelResponse.addTail() + ".xlsx";
				String targetXlsxFileName          = outSaleName + "_" + accountingOrderSn + "_" + invoiceApplySn + ".xlsx";
				String targetXlsxWriteFileFullPath = targetFullPath + relativePath + targetXlsxFileName;


				ExcelWriter excelWriter = EasyExcel
						.write(targetXlsxWriteFileFullPath)
						.inMemory(Boolean.TRUE)
						.registerWriteHandler(SugarUpBigDecimalCellWriteHandler
								.builder()
								.startRow(1)
								.matchCell(Arrays.asList(13, 15)) /* 13-销售单价 14-金额 15-税率 */
								.build()
						)
//				        .withTemplate(templateFullPath)
						.build();


				/****************************************** 侨城汇需求 20210922 start ******************************************/
//				qchNeed20210922(_entry.getValue().getTransferListBySheet());
				/****************************************** 侨城汇需求 20210922   end ******************************************/

				sheetNo = sheetNo + 1;
				ExcelExportModeEasyExcelUtils.createSheetByWorkbook(
						_entry.getValue().getTransferListBySheet(),
						mapperHead.get(2),
						mapperValue.get(2),
						excelWriter,
						sheetNo,
						_entry.getKey()
				);
				sheetNo = sheetNo + 1;

				/****************************************** 侨城汇需求 20210922 start ******************************************/
				// 在传入时已经处理过了 mark by linjinyu at 20220217 这个早就屏蔽了 这个是对的
//				qchNeed20210922(_entry.getValue().getTransferListBySheetMerge());
				/****************************************** 侨城汇需求 20210922   end ******************************************/

				ExcelExportModeEasyExcelUtils.createSheetByWorkbook(
						_entry.getValue().getTransferListBySheetMerge(),
						mapperHeadMerge.get(2),
						mapperValueMerge.get(2),
						excelWriter,
						sheetNo,
						_entry.getKey() + "_合并"
				);

				// 别忘记关闭流
				excelWriter.finish();

				excelFileList.add(FileUtil.file(targetXlsxWriteFileFullPath));
			}

			// 生成zip
			ZipUtil.zip(FileUtil.file(targetZipWriteFileFullPath), false, excelFileList.toArray(new File[excelFileList.size()]));

		} catch (Exception e) {

			log.error("exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode2 \n{}", ExceptionUtils.getMessage(e));
			return NotifyUtils.createSysNotify(targetZipFileName, relativePath + targetZipFileName, SysQuartzScheduleTaskStatementOfAccountRunStateEnum.失败);
		}


		/******************************************  start ******************************************/

		return NotifyUtils.createSysNotify(targetZipFileName, relativePath + targetZipFileName, SysQuartzScheduleTaskStatementOfAccountRunStateEnum.成功);

	}

	public SysNotify exportExcelInvoiceApplySupplierFocusScoreDimGoodsMode3(List<InvoiceApplySupplierDetailDimGoodsItemVo> resultList) {

		String excelExportPathRoot             = resourceConstant.getPathRoot();
		String excelExportRelativePathTemplate = resourceConstant.getPathTemplate();
		String excelExportRelativePathStorage  = resourceConstant.getPathStorage();

		String relativePath = File.separator + "excel" + File.separator + "invoice" + File.separator + "supplier" + File.separator;

		String templateRelativePath = excelExportPathRoot + excelExportRelativePathTemplate + relativePath;
		String templateFullPath;


		String targetFullPath = excelExportPathRoot + excelExportRelativePathStorage;

		String targetZipFileName          = "供应商结算" + "_" + "发票(开票申请)" + "_" + "勾选导出开票数据" + ExcelResponse.addTail() + ".zip";
		String targetZipWriteFileFullPath = targetFullPath + relativePath + targetZipFileName;

//		if (!FileUtil.exist(targetWriteFileFullPath)) {
//			FileUtil.mkdir(targetWriteFileFullPath);
//		}
		FileUtil.touch(targetZipWriteFileFullPath);

		/******************************************  start ******************************************/

//		ExcelWriterBuilder excelWriterBuilder = ;

		// 模板文件没在用
		templateFullPath = templateRelativePath + TEMPLATE_EXCEL_EXPORT_INVOICE_APPLY_SUPPLIER_FOCUS_SCORE_DIM_GOODS_MODE_3;


		// 得到处理后的数据
		Map<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> resultMap = mergeResultByExcelDebugAndCreateWorkbook(3, resultList);

		// 初始化Excel文件列表
		List<File> excelFileList = new ArrayList<>();

		try {

			// 生成 excel
			int sheetNo = 0;
			for (Map.Entry<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> _entry : resultMap.entrySet()) {

				String outSaleName = AnStringUtils.stringListConvertToString(_entry.getValue()
						.getTransferListBySheet()
						.stream()
						.map(InvoiceApplySupplierDetailDimGoodsItemVo::getSaleName)
						.distinct()
						.collect(Collectors.toList())
				);
				String invoiceApplySn = _entry.getKey();
				String accountingOrderSn = AnStringUtils.stringListConvertToString(_entry.getValue()
						.getTransferListBySheet()
						.stream()
						.map(InvoiceApplySupplierDetailDimGoodsItemVo::getAccountingOrderSn)
						.distinct()
						.collect(Collectors.toList())
				);


				// Excel 供应商名称+结算单编号+开票申请单号
				String targetXlsxFileName          = outSaleName + "_" + accountingOrderSn + "_" + invoiceApplySn + ".xlsx";
				String targetXlsxWriteFileFullPath = targetFullPath + relativePath + targetXlsxFileName;


				ExcelWriter excelWriter = EasyExcel
						.write(targetXlsxWriteFileFullPath)
						.inMemory(Boolean.TRUE)
						.registerWriteHandler(SugarUpBigDecimalCellWriteHandler
								.builder()
								.startRow(1)
								.matchCell(Arrays.asList(11, 12))
								.build()
						)
//				        .withTemplate(templateFullPath)
						.build();

				/****************************************** 侨城汇需求 20210922 start ******************************************/
				// 在传入时已经处理过了 mark by linjinyu at 20220217 屏蔽
				// 【【结算中心-正式环境】供应商结算-发票登记管理-FLSC_QCHSAA2022020723726592-导出开票数据未显示税率信息】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004455
//				qchNeed20210922(_entry.getValue().getTransferListBySheetMerge());
				/****************************************** 侨城汇需求 20210922   end ******************************************/


				ExcelExportModeEasyExcelUtils.createSheetByWorkbook(
						_entry.getValue().getTransferListBySheetMerge(),
						mapperHeadMerge.get(3),
						mapperValueMerge.get(3),
						excelWriter,
						sheetNo,
						_entry.getKey() + "_合并"
				);

				// 别忘记关闭流
				excelWriter.finish();

				excelFileList.add(FileUtil.file(targetXlsxWriteFileFullPath));

			}

			// 生成zip
			ZipUtil.zip(FileUtil.file(targetZipWriteFileFullPath), false, excelFileList.toArray(new File[excelFileList.size()]));

		} catch (Exception e) {

			log.error("exportExcelInvoiceApplyFocusScoreDimCreditMode2 \n{}", ExceptionUtils.getMessage(e));

			return NotifyUtils.createSysNotify(targetZipFileName, relativePath + targetZipFileName, SysQuartzScheduleTaskStatementOfAccountRunStateEnum.失败);
		}


		/******************************************  start ******************************************/

		return NotifyUtils.createSysNotify(targetZipFileName, relativePath + targetZipFileName, SysQuartzScheduleTaskStatementOfAccountRunStateEnum.成功);
	}

	public void qchNeed20210922(List<InvoiceApplySupplierDetailDimGoodsItemVo> resultTmp) {

		resultTmp.forEach(vo -> {

			/****************************************** part start ******************************************/

			if (null != vo.getMerchTaxRate()) {
				vo.setMerchTaxRate(vo.getMerchTaxRate().divide(new BigDecimal(100L), 2, BigDecimal.ROUND_HALF_UP));
			}


			/****************************************** part start ******************************************/

			vo.setEncryptedVersionNumber("33.0"); // 编码版本号 加密版本号 税务分类版本
			vo.setFlagTaxIncentives("0"); // 享受优惠政策 0 好像是没有
			vo.setPersonNameCashier(""); // 收款人
			vo.setPersonNameReview(""); // 复核人
			vo.setPurchaserCompanyType("01"); // 购方企业类型
			vo.setFlagTaxIncluded("含税"); // 含税标志

			/****************************************** part start ******************************************/

			InvoiceType invoiceType = invoiceTypeService.cacheGetEntity(InvoiceTypeCacheCriteria
					.builder()
					.hashTable(InvoiceTypeCacheCriteria.HASHTABLE)
					.hashTableKeyField(InvoiceTypeCacheCriteria.HASHTABLE_KEY_FIELD_ID)
					.keyField(AnStringUtils.getString(vo.getInvoiceType()))
					.build()
			);

			if (null != invoiceType) {
				vo.setInvoiceTypeName(invoiceType.getTypeName());
			}

			/****************************************** part start ******************************************/

			// 处理 sysPlatformExtInvoiceId 不为0的情况
			if (ObjectUtil.isNotNull(vo)
					&& ObjectUtil.isNotNull(vo.getSysPlatformExtInvoiceId())
					&& vo.getSysPlatformExtInvoiceId().compareTo(0L) != 0) {

				SysPlatformExtInvoiceVo sysPlatformExtInvoiceVo = AnJsonUtils.toObject(vo.getSysPlatformExtInvoiceSnapshot(), SysPlatformExtInvoiceVo.class);

				vo.setPurchaserCompanyName(sysPlatformExtInvoiceVo.getCompanyName());
				vo.setPurchaserTaxpayersIDCode(sysPlatformExtInvoiceVo.getTaxpayersIDCode());
				vo.setPurchaserAddressPhone(StrUtil.format("{}{}", sysPlatformExtInvoiceVo.getAddress(), sysPlatformExtInvoiceVo.getTel()));
				vo.setPurchaserPhone(sysPlatformExtInvoiceVo.getTel());
				vo.setPurchaserAddress(sysPlatformExtInvoiceVo.getAddress());
				vo.setPurchaserBankAccountNumber(StrUtil.format("{}{}", sysPlatformExtInvoiceVo.getBankName(), sysPlatformExtInvoiceVo.getBankAccount()));
				vo.setPurchaserBankAccount(sysPlatformExtInvoiceVo.getBankAccount());
				vo.setPurchaserBankName(sysPlatformExtInvoiceVo.getBankName());
			} else {
				vo.setPurchaserCompanyName(vo.getInvoiceTitle());
			}
		});
	}


	/**
	 * 可行 再合并 TODO 现在已经改成只处理数据 markby linjinyu at 202106031203
	 *
	 * @param resultList
	 * @return
	 */
	public Map<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> mergeResultByExcelDebugAndCreateWorkbook(Integer mode, List<InvoiceApplySupplierDetailDimGoodsItemVo> resultList) {


		// 变换
		List<InvoiceApplySupplierDetailDimGoodsItemVo> transformList = resultList.parallelStream()
				.filter(o -> CommonOrderGoodsUnitEnum.项.getDesc().equals(o.getUnit()) && null != o.getGoodsId() && o.getGoodsId().equals(-1L))
				.collect(Collectors.toList());

		if (CollUtil.isNotEmpty(transformList)) {

			transformList.forEach(o -> {
				o.setGoodsId(0L);
			});
		}


		log.info("\n\n\nexportExcelInvoiceApplyFocusScoreDimCredit 数据准备 : {}\n\n\n", AnJsonUtils.toJson(resultList));

//		HSSFWorkbook workbook = new HSSFWorkbook();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();

		Map<String, InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct> resultMap = new HashMap<>();

		if (CollUtil.isEmpty(resultList)) {
			return resultMap;
		}

		// 得出当前数据 发票申请的 id -> sn
		Map<Long, String> invoiceApplyMap = resultList.stream().collect(Collectors.toMap(
				/* key      */InvoiceApplySupplierDetailDimGoodsItemVo::getInvoiceApplyId,
				/* value    */InvoiceApplySupplierDetailDimGoodsItemVo::getInvoiceApplySn,
				/* key重复时 */(key1, key2) -> key2,
				LinkedHashMap::new
		));

		// 因为是可以多选的 所以先按 发票申请Id 分组
		Map<String, List<InvoiceApplySupplierDetailDimGoodsItemVo>> transferMapGrouopByInvoiceApplyId = resultList.parallelStream()
				.collect(Collectors.groupingBy(InvoiceApplySupplierDetailDimGoodsItemVo::getInvoiceApplySn, Collectors.toList()));
//				.collect(Collectors.groupingBy(e -> fetchGroupKey(e), Collectors.toList()));

//		List<ExportExcelInvoiceApplyForceScoreDimCreditVo> transferListBySheet      = null;
//		List<ExportExcelInvoiceApplyForceScoreDimCreditVo> transferListBySheetMerge = null;


		int sheetNo = 0;
		// 因为是可以多选的 所以先按 发票申请Id 分组 每个 entry 是 一份
		for (Map.Entry<String, List<InvoiceApplySupplierDetailDimGoodsItemVo>> entry : transferMapGrouopByInvoiceApplyId.entrySet()) {

//			transferListBySheet = new ArrayList<>();
//			transferListBySheetMerge = new ArrayList<>();

			InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct struct = new InvoiceApplySupplierExportExcelFocusScoreDimGoodsStruct();
			struct.setTransferListBySheet(new ArrayList<>());
			struct.setTransferListBySheetMerge(new ArrayList<>());

			Map<String, List<InvoiceApplySupplierDetailDimGoodsItemVo>> transferMapGrouopByInvoiceApplyIdGroupBy = entry.getValue().parallelStream()
					.collect(Collectors.groupingBy(e -> InvoiceApplySupplierExportExcelFocusScoreDimGoodsStatic.fetchGroupKeyByName(e), Collectors.toList()));

			for (Map.Entry<String, List<InvoiceApplySupplierDetailDimGoodsItemVo>> _entry : transferMapGrouopByInvoiceApplyIdGroupBy.entrySet()) {


				log.info("_groupKey : {} _size : {}", _entry.getKey(), _entry.getValue().size());

				// 为什么是大于1
				if (_entry.getValue().size() > 1) {
//					log.info("\n{}", JsonUtils.toJson(_entry.getValue()));

					// TODO 处理 合并
					InvoiceApplySupplierDetailDimGoodsItemVo _merge = new InvoiceApplySupplierDetailDimGoodsItemVo();
					BeanUtil.copyProperties(_entry.getValue().get(0), _merge);

					// 商品数量
					_merge.setQuantity(_entry.getValue().stream()
							.map(item -> item.getQuantity() == null ? 0 : item.getQuantity())
							.reduce(0, Integer::sum));
//					// 销售单价
//					_merge.setPrice(_entry.getValue().stream()
//							.map(item -> item.getPrice() == null ? BigDecimal.ZERO : item.getPrice())
//							.reduce(BigDecimal.ZERO, BigDecimal::add));
					// 结算金额
					_merge.setGoodsCostAmount(_entry.getValue().stream()
							.map(item -> item.getGoodsCostAmount() == null ? BigDecimal.ZERO : item.getGoodsCostAmount())
							.reduce(BigDecimal.ZERO, BigDecimal::add));

//					累加
//					BigDecimal::add

					/****************************************** 侨城汇 合并后数据为0不要了 start ******************************************/
					if (_merge.getQuantity().compareTo(0) != 0 || _merge.getGoodsCostAmount().compareTo(BigDecimal.ZERO) != 0) {
//						transferListBySheetMerge.add(_merge);
						struct.getTransferListBySheetMerge().add(_merge);
					}


				} else {
//					transferListBySheetMerge.addAll(_entry.getValue());
					struct.getTransferListBySheetMerge().addAll(_entry.getValue());
				}

//				transferListBySheet.addAll(_entry.getValue());
				struct.getTransferListBySheet().addAll(_entry.getValue());
			}

			resultMap.put(/* InvoiceNo */entry.getKey(), struct);


			/****************************************** 不在这处理了 start ******************************************/
//			try {
////				ExcelExportModePoiHssfUtils.createSheetByWorkbook(transferListBySheet, fieldHeadMode2Static, fieldValueMode2Static, workbook, invoiceApplyMap.get(entry.getKey()).toString() + "");
////				ExcelExportModePoiHssfUtils.createSheetByWorkbook(transferListBySheetMerge, fieldHeadMode2StaticMerge, fieldValueMode2StaticMerge, workbook, invoiceApplyMap.get(entry.getKey()).toString() + "_合并");
//
//				if (mode.compareTo(2) == 0) {
//
//					log.info("\n\n\n创建 sheet : {} \ntransferListBySheet 数据准备 : {}\n\n\n", invoiceApplyMap.get(entry.getKey()), JsonUtils.toJson(transferListBySheet));
////					WriteSheet writeSheet0 = EasyExcel
////							.writerSheet(sheetNo)
////							.sheetName(invoiceApplyMap.get(entry.getKey()))
////							.head(getHead(mapperHead.get(mode)))
////							.build();
//////					excelWriter.fill(new FillWrapper("detail", transferListBySheet), fillConfig, writeSheet0);
////					excelWriter.write(transferListBySheet, writeSheet0);
//					sheetNo = sheetNo + 1;
//					ExcelExportModeEasyExcelUtils.createSheetByWorkbook(transferListBySheet, mapperHead.get(mode), mapperValue.get(mode), excelWriter, sheetNo, invoiceApplyMap.get(entry.getKey()));
//				}
//
//				log.info("\n\n\n创建 sheet : {} \ntransferListBySheetMerge 数据准备 : {}\n\n\n", invoiceApplyMap.get(entry.getKey()) + "_合并", JsonUtils.toJson(transferListBySheetMerge));
////				WriteSheet writeSheet1 = EasyExcel
////						.writerSheet(sheetNo + 1)
////						.sheetName(invoiceApplyMap.get(entry.getKey()) + "_合并")
////						.head(getHead(mapperHead.get(mode)))
////						.build();
//////				excelWriter.fill(new FillWrapper("detail", transferListBySheetMerge), fillConfig, writeSheet1);
////				excelWriter.write(transferListBySheetMerge, writeSheet1);
//				sheetNo = sheetNo + 1;
//				ExcelExportModeEasyExcelUtils.createSheetByWorkbook(transferListBySheetMerge, mapperHeadMerge.get(mode), mapperValueMerge.get(mode), excelWriter, sheetNo, invoiceApplyMap.get(entry.getKey()) + "_合并");
//
//			} catch (Exception e) {
//
//				e.printStackTrace();
//			}
			/****************************************** 不在这处理了 start ******************************************/

//			sheetNo = sheetNo + 2;
		}

		return resultMap;


	}
}
