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.*;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountRunStateEnum;
import cn.superdesk.uniorder.dao.entity.operationCenter.OperationCenterOrder;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dao.mapper.operationCenter.OperationCenterOrderMapper;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.operationCenter.order.OperationCenterOrderParam;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.OperationCenterOrderDetailsVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.OperationCenterOrderGoodsVO;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.OperationCenterOrderTransactionLogVo;
import cn.superdesk.uniorder.dto.vo.operationCenter.order.OperationCenterOrderVo;
import cn.superdesk.uniorder.notify.NotifyUtils;
import cn.superdesk.uniorder.service.operationCenter.OperationCenterOrderService;
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.apache.commons.collections.CollectionUtils;
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/3/24 17:04
 * Description :
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationCenterOrderServiceImpl implements OperationCenterOrderService {
    private final OperationCenterOrderMapper operationCenterOrderMapper;

    private final ResourceConstant excelExportConstant;

    //订单模板
    private static final String EXPORT_OPERATION_CENTER_ORDER_TEMPLATE = "exportExcelOperationCenterOrderTemplate.xls";


    @Override
    public int insertSelective(OperationCenterOrder operationCenterOrder) {
        return operationCenterOrderMapper.insertSelective(operationCenterOrder);
    }

    @Override
    public int updateByPrimaryKeySelective(OperationCenterOrder operationCenterOrder) {
        return operationCenterOrderMapper.updateByPrimaryKeySelective(operationCenterOrder);
    }

    @Override
    public void deleteObj(Long id) {
        operationCenterOrderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public OperationCenterOrder findById(Long id) {
        return operationCenterOrderMapper.selectByPrimaryKey(id);
    }

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

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

    /**
     * 条件查询运营中心订单列表
     *
     * @param param
     * @return
     */
    @Override
    public List<OperationCenterOrderVo> getOperatorCenterOrderList(OperationCenterOrderParam param) {
        return operationCenterOrderMapper.getOperatorCenterOrderList(param);

    }

    @Override
    public List<OperationCenterOrderVo> getOrderByOrderNo(String platformCode,String orderSn,String refundOriginOrderSn) {
        return operationCenterOrderMapper.getOrderByOrderNo(platformCode,orderSn,refundOriginOrderSn);
    }

    @Override
    public Map<String, Object> getOrderStatisticsCount(OperationCenterOrderParam param) {
        return operationCenterOrderMapper.getOrderStatisticsCount(param);
    }

    @Override
    public SysNotify exportExcelOperationCenterOrder(OperationCenterOrderParam param) {
        List<OperationCenterOrderDetailsVo> excelOpCenterOrderList = operationCenterOrderMapper.getExcelOpCenterOrderList(param);
        List<OperationCenterOrderGoodsVO> operationCenterOrderGoodsVOList = new ArrayList<>();
        List<OperationCenterOrderTransactionLogVo> operationCenterOrderTransactionLogVoList = new ArrayList<>();
        operationCenterOrderTransactionLogVoList = operationCenterOrderMapper.getExcelOpCenterOrderTransactionLogList(param);
        for (OperationCenterOrderDetailsVo vo : excelOpCenterOrderList) {
            //将商品详情添加到 list中
            if (CollectionUtils.isNotEmpty(vo.getOperationCenterOrderGoodsVOList())) {
                operationCenterOrderGoodsVOList.addAll(vo.getOperationCenterOrderGoodsVOList());
            }
            //将 状态类型通过枚举进行描述
            vo.setOrderBizTypeDesc(null != vo.getOrderBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(vo.getOrderBizTypeId().intValue()):"");

            vo.setTransactionStatusDesc(null != vo.getTransactionStatusId()? OpCenterTransactionStatusEnum.getDescByCode(vo.getTransactionStatusId().intValue()):"");

            vo.setPlatformAfterSaleStatusDesc(null != vo.getPlatformAftersaleStatusId()? OpCenterPlatformAftersaleStatusEnum.getDescByCode(vo.getPlatformAftersaleStatusId().intValue()):"");

            vo.setOrderPayStatusDesc(null != vo.getOrderPayStatus()? OpCenterOrderPayStatusEnum.getDescByCode(vo.getOrderPayStatus().intValue()):"");
        }
        //商品限制
        operationCenterOrderGoodsVOList= operationCenterOrderGoodsVOList.stream()
                .filter(x -> x.getOrderGoodsId() != null && x.getGoodsTypeId() != OpCenterGoodsTypeEnum.商户承担运费.getCode())
                .map(goodsVO -> {
                    goodsVO.setGoodsTypeDesc(null != goodsVO.getGoodsTypeId() ? OpCenterGoodsTypeEnum.getDescByCode(goodsVO.getGoodsTypeId()) : "");
                    goodsVO.setBizTypeDesc(null != goodsVO.getBizTypeId() ? OpCenterOrderBizTypeEnum.getDescByCode(goodsVO.getBizTypeId().intValue()) : "");
                    return goodsVO;
                }).collect(Collectors.toList());

        //流水限制

        operationCenterOrderTransactionLogVoList= operationCenterOrderTransactionLogVoList.stream()
                .filter(x -> x.getGoodsTypeId() != OpCenterGoodsTypeEnum.商户承担运费.getCode())
                .map(vo -> {
                    vo.setGoodsTypeDesc(null != vo.getGoodsTypeId() ? OpCenterGoodsTypeEnum.getDescByCode(vo.getGoodsTypeId()) : "");
                    vo.setPayStatusDesc(null != vo.getPayStatusId() ? OpCenterOrderPayStatusEnum.getDescByCode(vo.getPayStatusId()) : "");
                    return vo;
                }).collect(Collectors.toList());


        //遍历商品详情-
//        for (OperationCenterOrderGoodsVO goodsVO : operationCenterOrderGoodsVOList) {
//
//            goodsVO.setGoodsTypeDesc(null != goodsVO.getGoodsTypeId() ? OpCenterGoodsTypeEnum.getDescByCode(goodsVO.getGoodsTypeId()) : "");
//            goodsVO.setBizTypeDesc(null != goodsVO.getBizTypeId()? OpCenterOrderBizTypeEnum.getDescByCode(goodsVO.getBizTypeId().intValue()):"");
//        }

        String excelExportPathRoot = excelExportConstant.getPathRoot();
        String excelExportOrderPathTemplate = excelExportConstant.getPathTemplate();
        String excelExportOrderPathStorage = excelExportConstant.getPathStorage();

        String relativePath = File.separator + "excel" + File.separator + "operationCenter" + File.separator + "order" + File.separator;
        String templateRelativePath = excelExportPathRoot + excelExportOrderPathTemplate + relativePath;
        String templateFullPath = templateRelativePath + EXPORT_OPERATION_CENTER_ORDER_TEMPLATE;

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

        String targetFullPath = excelExportPathRoot + excelExportOrderPathStorage;
        String targetFileName = "订单管理_导出_" + strTime + ".xlsx";
        String targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;

        FileUtil.touch(targetWriteFileFullPath);

        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(targetWriteFileFullPath);

        ExcelWriter excelWriter = null;
        WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "订单").build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "商品明细").build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "流水明细").build();


        excelWriter = excelWriterBuilder.withTemplate(templateFullPath).build();

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

        excelWriter.fill(new FillWrapper("detail", excelOpCenterOrderList), fillConfig, writeSheet0);

        excelWriter.fill(new FillWrapper("detail", operationCenterOrderGoodsVOList), fillConfig, writeSheet1);
        excelWriter.fill(new FillWrapper("detail", operationCenterOrderTransactionLogVoList), fillConfig, writeSheet2);


        excelWriter.finish();

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

    }

}
