package com.czg.service.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.czg.excel.ExcelExportUtil;
import com.czg.excel.SheetData;
import com.czg.order.param.TableSummaryParam;
import com.czg.order.service.TableSummaryService;
import com.czg.order.vo.TableSummaryExportVo;
import com.czg.service.order.mapper.ShopTableOrderStatisticMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 台桌统计Service实现类
 *
 * @author tankaikai
 * @since 2025-03-07 15:32
 */
@Service
public class TableSummaryServiceImpl implements TableSummaryService {

    @Resource
    private ShopTableOrderStatisticMapper shopTableOrderStatisticMapper;

    @Override
    public void summaryExportList(TableSummaryParam param, HttpServletResponse response) {
        if (param.getBeginDate() == null && param.getEndDate() == null) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算 30 天前的日期
            LocalDate startDate = currentDate.minusDays(30);

            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 格式化日期
            String formattedStartDate = startDate.format(formatter);
            String formattedEndDate = currentDate.format(formatter);

            param.setBeginDate(formattedStartDate + " 00:00:00");
            param.setEndDate(formattedEndDate + " 23:59:59");
        }

        List<TableSummaryExportVo> list = shopTableOrderStatisticMapper.findSummaryExportList(param);
        if (CollUtil.isEmpty(list)) {
            ExcelExportUtil.exportToResponse(new ArrayList<>(), TableSummaryExportVo.class, "台桌统计", response);
            return;
        }

        // === Step 1: 按日期计算 当日总销售额 ===
        Map<String, BigDecimal> dailyTotalMap = list.stream()
                .collect(Collectors.groupingBy(
                        TableSummaryExportVo::getCreateDate,
                        Collectors.reducing(BigDecimal.ZERO, TableSummaryExportVo::getAmount, BigDecimal::add)
                ));

        // === Step 2: 按 台桌+日期 计算 每台桌当日销售额 ===
        Map<String, BigDecimal> tableDailyTotalMap = list.stream()
                .collect(Collectors.groupingBy(
                        vo -> vo.getTableCode() + "_" + vo.getCreateDate(),
                        Collectors.reducing(BigDecimal.ZERO, TableSummaryExportVo::getAmount, BigDecimal::add)
                ));


        // === Step 3: 回填字段 ===
        for (TableSummaryExportVo vo : list) {
            String dateKey = vo.getCreateDate();
            String tableDateKey = vo.getTableCode() + "_" + dateKey;

            // 设置“总销售额” = 该台桌当天总销售额
            vo.setSalesAmount(tableDailyTotalMap.getOrDefault(tableDateKey, BigDecimal.ZERO));

            // 设置“当日总销售额” = 当天所有台桌总和
            vo.setTotalSalesAmount(dailyTotalMap.getOrDefault(dateKey, BigDecimal.ZERO));
        }

        // === Step 4: 导出 ===
        List<SheetWriteHandler> strategies = calculateMergeCells(list);
        ExcelExportUtil.exportMultipleSheetsToResponse(
                List.of(new SheetData()
                        .setData(list)
                        .setSheetName("台桌统计")
                        .setHandlers(strategies)
                        .setClazz(TableSummaryExportVo.class)),
                "台桌统计",
                response);
    }

    /**
     * 计算需要合并的单元格信息
     */
    private List<SheetWriteHandler> calculateMergeCells(List<TableSummaryExportVo> list) {
        List<SheetWriteHandler> mergeInfos = new ArrayList<>();
        if (CollUtil.isEmpty(list)) {
            return mergeInfos;
        }

        // 按日期分组（用于合并“日期”和“当日总销售额”列）
        Map<String, List<TableSummaryExportVo>> byDate = list.stream()
                .collect(Collectors.groupingBy(TableSummaryExportVo::getCreateDate));

        int currentRow = 1; // Excel 数据从第1行开始（第0行为标题）

        // 按日期排序
        List<String> sortedDates = byDate.keySet().stream().sorted().toList();

        for (String date : sortedDates) {
            List<TableSummaryExportVo> dateGroup = byDate.get(date);
            int dateSize = dateGroup.size();

            // 合并“日期”列（第0列）和“当日总销售额”列（第9列）
            if (dateSize > 1) {
                mergeInfos.add(ExcelExportUtil.createMergeStrategy(currentRow, currentRow + dateSize - 1, 0, 0));
                mergeInfos.add(ExcelExportUtil.createMergeStrategy(currentRow, currentRow + dateSize - 1, 9, 9));
            }

            // 在日期组内，按台桌分组（用于合并“台桌”和“总销售额”列）
            Map<String, List<TableSummaryExportVo>> byTable = dateGroup.stream()
                    .collect(Collectors.groupingBy(TableSummaryExportVo::getTableName));

            int tableStartRow = currentRow;
            List<String> sortedTables = byTable.keySet().stream().sorted().toList();

            for (String table : sortedTables) {
                List<TableSummaryExportVo> tableGroup = byTable.get(table);
                int tableSize = tableGroup.size();

                // 合并“台桌”列（第1列）和“总销售额”列（第8列）
                if (tableSize > 1) {
                    mergeInfos.add(ExcelExportUtil.createMergeStrategy(tableStartRow, tableStartRow + tableSize - 1, 1, 1));
                    mergeInfos.add(ExcelExportUtil.createMergeStrategy(tableStartRow, tableStartRow + tableSize - 1, 8, 8));
                }

                tableStartRow += tableSize;
            }

            currentRow += dateSize;
        }

        return mergeInfos;
    }
}