package cn.superdesk.uniorder.service.operationCenter.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.superdesk.data.extract.enums.opCenter.OpCenterGoodsTypeEnum;
import cn.superdesk.data.extract.enums.opCenter.OpCenterOrderBizTypeEnum;
import cn.superdesk.data.extract.enums.opCenter.OpCenterTransactionStatusEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSettlementStateEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.common.sequence.GenRandomHelper;
import cn.superdesk.uniorder.dao.entity.operationCenter.accounting.UnifiedAccountingOrderGoods;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dao.mapper.operationCenter.accounting.UnifiedAccountingOrderCreditMapper;
import cn.superdesk.uniorder.dao.mapper.operationCenter.accounting.UnifiedAccountingOrderCreditMapperEx;
import cn.superdesk.uniorder.dao.mapper.operationCenter.accounting.UnifiedAccountingOrderGoodsMapper;
import cn.superdesk.uniorder.dao.mapper.operationCenter.accounting.UnifiedAccountingOrderGoodsMapperEx;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.operationCenter.order.OperationCenterOrderParam;
import cn.superdesk.uniorder.dto.vo.operationCenter.accounting.UnifiedAccountingOrderInfoVo;
import cn.superdesk.uniorder.notify.NotifyUtils;
import cn.superdesk.uniorder.service.operationCenter.UnifiedAccountingOrderGoodsService;
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 com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author : zx
 * @Create : 2023/4/27 16:09
 * Description :
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UnifiedAccountingOrderGoodsServiceImpl implements UnifiedAccountingOrderGoodsService {

    private final UnifiedAccountingOrderGoodsMapperEx unifiedAccountingOrderGoodsMapperEx;


    private final UnifiedAccountingOrderCreditMapperEx unifiedAccountingOrderCreditMapperEx;


    private final ResourceConstant excelExportConstant;

    private static final String EXPORT_ACCOUNTING_ORDER_GOODS_LIST = "AccountingOrderGoodsListExportTemplate.xls";
    private static final String EXPORT_ACCOUNTING_GOODS_NEGOTIATING_COST = "AccountingGoodsNegotiatingCostExportTemplate.xls";
    private static final String EXPORT_ACCOUNTING_GOODS_SUPPLIER_COSTS = "AccountingGoodsSupplierCostsExportTemplate.xls";
    private static final String EXPORT_ACCOUNTING_CREDIT_LIST = "AccountingCreditExportTemplate.xls";
   private static final String EXPORT_ACCOUNTING_NO_ACCOUNTING_CREDIT = "AccountingNoAccountingCreditExportTemplate.xls";

    @Override
    public int insertSelective(UnifiedAccountingOrderGoods unifiedAccountingOrderGoods) {
        return 0;
    }

    @Override
    public int updateByPrimaryKeySelective(UnifiedAccountingOrderGoods unifiedAccountingOrderGoods) {
        return 0;
    }

    @Override
    public void deleteObj(Long id) {

    }

    @Override
    public UnifiedAccountingOrderGoods findById(Long id) {
        return null;
    }

    @Override
    public List<UnifiedAccountingOrderGoods> findAll(Map<String, Object> queryMap) {
        return null;
    }

    @Override
    public PageInfo<UnifiedAccountingOrderGoods> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        return null;
    }

    @Override
    public List<UnifiedAccountingOrderInfoVo> getOrderGoodsList(OperationCenterOrderParam param) {
        return unifiedAccountingOrderGoodsMapperEx.getOrderGoodsList(param);
    }

    @Override
    public SysNotify exportExcelOrder(OperationCenterOrderParam param) {
        //首先定义模版位置 ---初始化位置
        String excelExportPathRoot = excelExportConstant.getPathRoot();
        String excelExportOrderPathTemplate = excelExportConstant.getPathTemplate();
        String excelExportOrderPathStorage = excelExportConstant.getPathStorage();
        String relativePath = File.separator + "excel" + File.separator + "accounting" + File.separator + "unified" + File.separator+ "order" + File.separator;
        //模版位置 绝对路径 前缀
        String templateRelativePath = excelExportPathRoot + excelExportOrderPathTemplate + relativePath;
        //下载位置
        String targetFullPath = excelExportPathRoot + excelExportOrderPathStorage;

        String strTime = DateUtil.format(new Date(), "yyyyMMddHHmmss");

        //模版位置
        String templateFullPath = "";
        String targetFileName = "";
        String targetWriteFileFullPath = "";


        List<UnifiedAccountingOrderInfoVo> result = new ArrayList<>();
        switch (param.getImportAccountingOrderExcelEnum()) {
            case 商品维度导出列表:
            case 商品维度导出列表含协议成本:
            case 商品维度导出列表含供应商成本:

                param.setFlag(2);//查询excel字段
                //查询列表
                result = unifiedAccountingOrderGoodsMapperEx.getOrderGoodsList(param);

                result = result.stream()
                        .map(vo -> {
                            //业务类型
                            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                            //商品类型
                            vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                            //交易状态
                            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                            //对账状态
                            vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                            return vo;
                        }).collect(Collectors.toList());




                //模版 全路径
                switch (param.getImportAccountingOrderExcelEnum()) {
                    case 商品维度导出列表:
                        templateFullPath = templateRelativePath + EXPORT_ACCOUNTING_ORDER_GOODS_LIST;
                        //下载文件名称
                        targetFileName = "订单管理（商品维度）_导出列表_" + strTime + GenRandomHelper.genRandomNum(4) +".xlsx";
                        break;
                    case 商品维度导出列表含协议成本:
                        templateFullPath = templateRelativePath + EXPORT_ACCOUNTING_GOODS_NEGOTIATING_COST;
                        //下载文件名称
                        targetFileName = "订单管理（商品维度）_导出（含协议成本）_" + strTime + GenRandomHelper.genRandomNum(4) +".xlsx";
                        break;
                    case 商品维度导出列表含供应商成本:
                        templateFullPath = templateRelativePath + EXPORT_ACCOUNTING_GOODS_SUPPLIER_COSTS;
                        //下载文件名称
                        targetFileName = "订单管理（商品维度）_导出（含供应商成本）_" + strTime + GenRandomHelper.genRandomNum(4) +".xlsx";
                        break;
                }


                //下载 全路径
                targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;

                FileUtil.touch(targetWriteFileFullPath);

                ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath);
                ExcelWriter excelWriter = null;
                WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "商品数据_订单管理").build();
                excelWriter = excelWriterBuilder.withTemplate(templateFullPath).build();



                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(new FillWrapper("detail", result), fillConfig, writeSheet0);
                excelWriter.finish();


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



            case 流水维度导出列表:
                param.setFlag(2);
                result = unifiedAccountingOrderCreditMapperEx.getOrderCreditList(param);


                result = result.stream()
                        .map(vo -> {
                            //业务类型
                            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                            //商品类型
                            vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                            //交易状态
                            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                            //对账状态
                            vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                            //是否参与结算
                            vo.setIsSettlementDesc(null !=vo.getIsSettlement()? CommonSettlementStateEnum.getDesc(vo.getIsSettlement()):"");

                            return vo;
                        }).collect(Collectors.toList());







                templateFullPath = templateRelativePath + EXPORT_ACCOUNTING_CREDIT_LIST;
                //下载文件名称
                targetFileName = "订单管理（流水维度）_导出列表_" + strTime + GenRandomHelper.genRandomNum(4) +".xlsx";
                //下载 全路径
                targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;

                FileUtil.touch(targetWriteFileFullPath);

                 excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath);
                 excelWriter = null;
                 writeSheet0 = EasyExcel.writerSheet(0, "流水数据_订单管理").build();
                excelWriter = excelWriterBuilder.withTemplate(templateFullPath).build();



                 fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(new FillWrapper("detail", result), fillConfig, writeSheet0);
                excelWriter.finish();


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

            case 未对账订单导出列表:

                //流水
                param.setAccountingStatus(CommonAccountingStateEnum.未对账.getKey().toString());
                param.setFlag(2);
                result = unifiedAccountingOrderCreditMapperEx.getOrderCreditList(param);



                //商品
                //  param.setFlag(2);//查询excel字段
                //查询列表商品

                List<UnifiedAccountingOrderInfoVo> orderGoodsList = unifiedAccountingOrderGoodsMapperEx.getOrderGoodsList(param);



                //商品数据转化
                orderGoodsList = orderGoodsList.stream()
                        .map(vo -> {
                            //业务类型
                            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                            //商品类型
                            vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                            //交易状态
                            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                            //对账状态
                            vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                            return vo;
                        }).collect(Collectors.toList());




                //流水数据转化
                result = result.stream()
                        .map(vo -> {
                            //业务类型
                            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId()):"");
                            //商品类型
                            vo.setGoodsTypeDesc(null != vo.getGoodsTypeId()? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()):"");
                            //交易状态
                            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId()):"");
                            //对账状态
                            vo.setAccountingStatusDesc(null !=vo.getAccountingStatus()? CommonAccountingStateEnum.getDesc(vo.getAccountingStatus()):"");
                            //是否参与结算
                            vo.setIsSettlementDesc(null !=vo.getIsSettlement()? CommonSettlementStateEnum.getDesc(vo.getIsSettlement()):"");

                            return vo;
                        }).collect(Collectors.toList());



                templateFullPath = templateRelativePath + EXPORT_ACCOUNTING_NO_ACCOUNTING_CREDIT;
                //下载文件名称
                targetFileName = "未对账订单_导出列表_" + strTime + GenRandomHelper.genRandomNum(4) +".xlsx";
                //下载 全路径
                targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;

                FileUtil.touch(targetWriteFileFullPath);

                excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath);
                excelWriter = null;
                writeSheet0 = EasyExcel.writerSheet(0, "商品明细").build();
                WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "流水明细").build();
                excelWriter = excelWriterBuilder.withTemplate(templateFullPath).build();



                fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
                excelWriter.fill(new FillWrapper("detail", orderGoodsList), fillConfig, writeSheet0);
                excelWriter.fill(new FillWrapper("detail", result), fillConfig, writeSheet1);
                excelWriter.finish();


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

        }

        return null;
    }
}
