package cn.iocoder.yudao.module.member.controller.admin.customizeExcel;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.member.controller.admin.customizeExcel.vo.*;
import cn.iocoder.yudao.module.member.service.customizeExcel.CustomizeExcelService;
import cn.iocoder.yudao.module.member.util.CustomMergeStrategy;
import cn.iocoder.yudao.module.system.api.carteen.CarteenApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;


@Tag(name = "管理后台 - 自定义表格导出")
@RestController
@RequestMapping("/member/export")
@Validated
public class CustomizeExcelController {

    @Resource
    private CustomizeExcelService excelService;
    @Resource
    private CarteenApi carteenApi;

    @GetMapping("/orderExcel")
    @Operation(summary = "导出订单详情")
    @OperateLog(type = EXPORT)
    public void exportBusinessExcel(String startTime,String endTime,Long carteenId,
              HttpServletResponse response) throws IOException {

        List<OrderExcelVO> orderExcelVOS = excelService.exportOrderExcel(startTime, endTime,carteenId);
        for(OrderExcelVO vo : orderExcelVOS){
            vo.setStoreName(carteenApi.getCarteenById(carteenId).getStoresName());
        }
        // 导出 Excel
        ExcelUtils.write(response, "订单详情统计.xlsx", "数据", OrderExcelVO.class,
                orderExcelVOS);
    }
    @GetMapping("/orderExcel1")
    @Operation(summary = "导出订单详情")
    @OperateLog(type = EXPORT)
    public void exportBusinessExcel1(String startTime,String endTime,Long carteenId,
                                    HttpServletResponse response) throws IOException {

        List<OrderExcelVO> orderExcelVOS = excelService.exportOrderExcel(startTime, endTime,carteenId);
        exporOrderDate(orderExcelVOS,response);
    }
    /**
     * 根据时间导出多个sheet 页
     * @param
     * @param data1
     * @param response
     * @throws IOException
     */
    public void exporOrderDate(List<OrderExcelVO> data1,HttpServletResponse response) throws IOException {
        data1.forEach(f->
        {
            f.setDayTime(f.getDayTime().substring(0,10));
            if(f.getNickname()==null  ){
                f.setNickname("null");
            }
            if(f.getMobile()==null){
                f.setMobile("null");
            }
        });
        Map<String, List<OrderExcelVO>> collect = data1.stream().collect(Collectors.groupingBy(OrderExcelVO::getDayTime));
        // 按key（时间）排序，将数据按时间顺序放入列表
        List<Map.Entry<String, List<OrderExcelVO>>> sortedEntries = collect.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())  // 按时间排序
                .collect(Collectors.toList());
        long l = System.currentTimeMillis();
        // 设置文件名和响应内容类型
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单详情统计.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try (SXSSFWorkbook workbook = new SXSSFWorkbook(); OutputStream outputStream = response.getOutputStream()) {
            for (Map.Entry<String, List<OrderExcelVO>> entry : sortedEntries) {
                // 创建一个Sheet
                Sheet sheet = workbook.createSheet("数据"+entry.getKey());
                // 处理数据和写入逻辑
                createHeader(sheet, workbook);  // 创建表头
                int rowNum = 1;
                // 写入数据
                for (OrderExcelVO order : data1) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(order.getDayTime());
                    row.createCell(1).setCellValue(order.getNickname());
                    row.createCell(2).setCellValue(order.getMobile());
                    row.createCell(3).setCellValue(order.getTimeSlot());
                    row.createCell(4).setCellValue(order.getTotalMoney().toString());
                    row.createCell(5).setCellValue(order.getDishesName());
                    row.createCell(5).setCellValue(order.getUnitPrice()==null?"0.00":order.getUnitPrice().toString());
                    row.createCell(7).setCellValue(order.getWeight());
                    row.createCell(8).setCellValue(order.getPrice().toString());
                }
                List<OrderExcelVO> data = entry.getValue();
                List<List<String>> collect1 = Stream.of(data.stream().map(OrderExcelVO::getNickname).collect(Collectors.toList()), data.stream().map(OrderExcelVO::getMobile).collect(Collectors.toList()), data.stream().map(f -> f.getTotalMoney().toString()).collect(Collectors.toList())).collect(Collectors.toList());
                Map<Integer, Integer> map = new HashMap<>();
                map.put(1, 0); // 第三列合并
                map.put(2, 1); // 第三列合并
                map.put(3, 2); // 第三列合并
                map.put(4, 2); // 第四列合并
                CustomMergeStrategy customMergeStrategy = new CustomMergeStrategy(collect1, map);
                customMergeStrategy.merge(sheet,4);
                // 将数据写入输出流
            }
            workbook.write(outputStream);
            outputStream.flush();
            System.out.println( System.currentTimeMillis()-l);
        }
    }
    // 创建表头
    private void createHeader(Sheet sheet, SXSSFWorkbook workbook) {
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("日期");
        header.createCell(1).setCellValue("用户名");
        header.createCell(2).setCellValue("手机");
        header.createCell(3).setCellValue("总价");
        header.createCell(4).setCellValue("时间段");
        header.createCell(5).setCellValue("菜名");
        header.createCell(6).setCellValue("单价（元/50g）");
        header.createCell(7).setCellValue("重量（g）");
        header.createCell(8).setCellValue("价格（元）");
    }

    @GetMapping("/storeOrderExcel")
    @Operation(summary = "导出超市订单详情")
    @OperateLog(type = EXPORT)
    public void exportStoreOrderExcel(String startTime,String endTime,Long carteenId,
                                    HttpServletResponse response) throws IOException {

        List<StoreOrderExcelVO> orderExcelVOS = excelService.exportStoreOrderExcel(startTime, endTime,carteenId);
        // 导出 Excel
        ExcelUtils.write(response, "订单详情统计.xlsx", "数据", StoreOrderExcelVO.class,
                orderExcelVOS);
    }

    @GetMapping("/storeSaleGoodsExcel")
    @Operation(summary = "导出超市商品售卖详情")
    @OperateLog(type = EXPORT)
    public void exportStoreSaleGoodsExcel(String startTime,String endTime,Long carteenId,
                                      HttpServletResponse response) throws IOException {

        List<StoreSaleGoodsVO> orderExcelVOS = excelService.exportStoreSaleGoodsExcel(startTime, endTime,carteenId);
        // 导出 Excel
        ExcelUtils.write(response, "商品售卖详情统计.xlsx", "数据", StoreSaleGoodsVO.class,
                orderExcelVOS);
    }


    @GetMapping("/groupOrderExcel")
    @Operation(summary = "导出部门食堂订单详情")
    @OperateLog(type = EXPORT)
    public void exportGroupOrderExcel(String startTime,String endTime,Long carteenId,Long groupId,
                                          HttpServletResponse response) throws IOException {

        List<GroupOrderVO> orderExcelVOS = excelService.exportGroupOrderExcel(startTime, endTime,carteenId,groupId);
        // 导出 Excel
        ExcelUtils.write(response, "部门订单详情统计.xlsx", "数据", GroupOrderVO.class,
                orderExcelVOS);
    }

    @GetMapping("/groupStoreOrderExcel")
    @Operation(summary = "导出部门超市订单详情")
    @OperateLog(type = EXPORT)
    public void exportGroupStoreOrderExcel(String startTime,String endTime,Long carteenId,Long groupId,
                                      HttpServletResponse response) throws IOException {
        List<GroupStoreOrderVO> orderExcelVOS = excelService.exportGroupStoreOrderExcel(startTime, endTime,carteenId,groupId);
        // 导出 Excel
        ExcelUtils.write(response, "超市订单.xlsx", "数据", GroupStoreOrderVO.class,
                orderExcelVOS);
    }


    @GetMapping("/subsidyExcel")
    @Operation(summary = "三峡路社区食堂补贴")
    @OperateLog(type = EXPORT)
    public void exportSubsidyExcel(String startTime,String endTime,Long carteenId,
                                           HttpServletResponse response) throws IOException {
        List<SubsidyExcelVO> orderExcelVOS = excelService.exportSubsidyExcel(startTime, endTime,carteenId);
        // 导出 Excel
        ExcelUtils.write(response, "三峡路社区食堂补贴.xlsx", "数据", SubsidyExcelVO.class,
                orderExcelVOS);
    }


    @GetMapping("/cashAmountExcel")
    @Operation(summary = "现金充值导出")
    @OperateLog(type = EXPORT)
    public void exportCashAmountExcel(String startTime,String endTime,Long carteenId,
                                   HttpServletResponse response) throws IOException {
        List<CashAmountExcelVO> orderExcelVOS = excelService.exportCashAmountExcel(startTime, endTime,carteenId);
        // 导出 Excel
        ExcelUtils.write(response, "现金充值.xlsx", "数据", CashAmountExcelVO.class,
                orderExcelVOS);
    }

    @GetMapping("/activityMxExcel")
    @Operation(summary = "活动付款明细导出")
    @OperateLog(type = EXPORT)
    public void exportActivityMx(HttpServletResponse response) throws IOException {
        List<ActivityMxVO> orderExcelVOS = excelService.exportActivityMx();
        // 导出 Excel
        ExcelUtils.write(response, "现金充值.xlsx", "数据", ActivityMxVO.class,
                orderExcelVOS);
    }

    @GetMapping("/activityReserveExcel")
    @Operation(summary = "活动预定桌数导出")
    @OperateLog(type = EXPORT)
    public void exportActivityReserve(HttpServletResponse response) throws IOException {
        List<ActivityReserveVO> orderExcelVOS = excelService.exportActivityReserve();
        // 导出 Excel
        ExcelUtils.write(response, "现金充值.xlsx", "数据", ActivityReserveVO.class,
                orderExcelVOS);
    }

    @GetMapping("/overspending")
    @Operation(summary = "组内每天超过37元的数据")
    @OperateLog(type = EXPORT)
    public void exportOverspending(String startTime,String endTime,Long groupId,HttpServletResponse response) throws IOException {
        List<OverspendingVO> overspendingVOS = excelService.exportOverspending(startTime, endTime, groupId);
        // 导出 Excel
        ExcelUtils.write(response, "现金充值.xlsx", "数据", OverspendingVO.class,
                overspendingVOS);
    }
}