package cn.superdesk.uniorder.service.accounting.unified.supplier.Impl;

import cn.hutool.core.io.FileUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplier;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplierIssues;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.AccountingOrderUnifiedSupplierListItemVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo;
import cn.superdesk.uniorder.notify.NotifyUtils;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierExportExcelService;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierService;
import cn.superdesk.uniorder.service.accounting.unified.supplier.AccountingUnifiedSupplierXGoodsService;
import cn.superdesk.uniorder.service.order.base.UnifiedOrderService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 作为 供应商结算 对账单 共用的 Excel 导出 服务
 * @Author: linjinyu
 * @CreateDate: 2021/2/25 上午11:40
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/2/25 上午11:40
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class AccountingUnifiedSupplierExportExcelServiceImpl implements AccountingUnifiedSupplierExportExcelService {

    @Autowired
    private AccountingUnifiedSupplierService       accountingUnifiedSupplierService;
    @Autowired
    private AccountingUnifiedSupplierXGoodsService accountingUnifiedSupplierXGoodsService;
    @Autowired
    private UnifiedOrderService                    unifiedOrderService;

    @Autowired
    private ResourceConstant resourceConstant;


    private static final String TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_ISSUE_DIM_ORDER = "AccountingUnifiedSupplierIssueDimOrder.xlsx";
    private static final String TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_ISSUE_DIM_GOODS = "AccountingUnifiedSupplierIssueDimGoods.xlsx";

    private static final String TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_LIST = "exportAccountingUnifiedSupplierList.xlsx";

    /**
     * 已添加 数据脱敏逻辑 20211203
     *
     * @param accountingUnifiedSupplierIssues
     * @param loginSysUser
     */
    public void exportAccountingUnifiedSupplierIssues(AccountingUnifiedSupplierIssues accountingUnifiedSupplierIssues, LoginSysUser loginSysUser) {

        // 对账单详情信息
        Long   accountingOrderId = accountingUnifiedSupplierIssues.getAccountingOrderId();
        String accountingOrderSn = accountingUnifiedSupplierIssues.getAccountingOrderSn();

        log.info("\n\n正在生成 {} \n\n", accountingOrderSn);

        /****************************************** 初始化数据 start ******************************************/

        // 对账单主体信息
        AccountingUnifiedSupplier accountingUnifiedSupplier = accountingUnifiedSupplierService.findById(accountingUnifiedSupplierIssues.getAccountingOrderId());

        // 是有可以这样的,就是主体删除了,关联关系还在的情况
        if (null == accountingUnifiedSupplier) {
            accountingUnifiedSupplier = new AccountingUnifiedSupplier();
            accountingUnifiedSupplier.setId(accountingOrderId);
            accountingUnifiedSupplier.setAccountingOrderSn(accountingOrderSn);
            accountingUnifiedSupplier.setDimCreateBy(0);
        }


        // 对账单 问题订单号
        List<String> issuesOrderSns = AnStringUtils.stringArrayConvertToStringList(accountingUnifiedSupplierIssues.getOrderSnList(), ",");

        List<Map<String, String>> issuesOrderSnsListMap = new ArrayList<>();
        issuesOrderSns.forEach(AnLamdaUtils.consumerWithIndex((orderSn, index) -> {

            Map<String, String> temp = new HashMap<>();
            temp.put("index", AnStringUtils.getString(index));
            temp.put("orderSn", orderSn);

            issuesOrderSnsListMap.add(temp);
        }));


        // 已添加 数据脱敏逻辑 20211203
        List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> dataList = unifiedOrderService.getSupplierStatementOfAccountDetailDimGoods2Goods(accountingOrderSn, loginSysUser);

        /****************************************** 初始化数据   end ******************************************/


        String templateFileName = null;


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

        String relativePath = File.separator + "excel" + File.separator + "accounting" + File.separator + "unified" + 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;
        FileUtil.touch(targetWriteFileFullPath);


        switch (AccountingOrderDimCreateByEnum.get(accountingUnifiedSupplier.getDimCreateBy())) {
            case 订单:
                templateFileName = templateRelativePath + TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_ISSUE_DIM_ORDER;
                break;
            case 商品:
                templateFileName = templateRelativePath + TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_ISSUE_DIM_GOODS;
                break;
            case 流水:
                break;
            default:
                break;
        }

        log.info("\n\n地址:\n{}\n{}\n\n", templateFileName, targetWriteFileFullPath);

        ExcelWriter excelWriter = EasyExcel.write(targetWriteFileFullPath)
                .inMemory(Boolean.TRUE).withTemplate(templateFileName).build();
        WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "IssuesOrderSns").build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "对账单-详情").build();

        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        excelWriter.fill(new FillWrapper("issues", issuesOrderSnsListMap), fillConfig, writeSheet0);
        excelWriter.fill(new FillWrapper("detail", dataList), fillConfig, writeSheet1);


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

    @Override
    public SysNotify exportExcelAccountingSupplierList(List<AccountingOrderUnifiedSupplierListItemVo> list) {

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

        String relativePath = File.separator + "excel" +
                File.separator + "accounting" +
                File.separator + "unified" +
                File.separator + "supplier" +
                File.separator;
        String templateRelativePath = excelExportPathRoot + excelExportRelativePathTemplate + relativePath;
        String templateFullPath     = templateRelativePath + TEMPLATE_EXCEL_EXPORT_ACCOUNTING_UNIFIED_SUPPLIER_LIST;

        String targetFullPath          = excelExportPathRoot + excelExportRelativePathStorage;
        String targetFileName          = "供应商结算_" + "对账单-概要_" + "导出" + ExcelResponse.addTail() + ".xlsx";
        String targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;
        FileUtil.touch(targetWriteFileFullPath);

        ExcelWriter excelWriter = EasyExcel.write(targetWriteFileFullPath).withTemplate(templateFullPath).build();
        WriteSheet  writeSheet0 = EasyExcel.writerSheet(0, "对账单-概要").build();
        FillConfig  fillConfig  = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
        excelWriter.fill(new FillWrapper("detail", list), fillConfig, writeSheet0);
        excelWriter.finish();
        return NotifyUtils.createSysNotify(targetFileName, relativePath + targetFileName, SysQuartzScheduleTaskStatementOfAccountRunStateEnum.成功);

    }

}
