package org.dromara.zhishu.listener;

import com.alibaba.excel.EasyExcel;
import org.dromara.zhishu.domain.dto.request.ZhishuShopGoodsRequest;
import org.dromara.zhishu.domain.vo.SaveGoodsVo;
import org.dromara.zhishu.service.IZhishuShopGoodsService;
import org.dromara.zhishu.util.ExcelFileHandlerUtil;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.nio.file.Paths;
import java.util.*;

@Component
public class StartupListener implements CommandLineRunner {

    @Autowired
    private IZhishuShopGoodsService zhishuShopGoodsService;

    @Override
    public void run(String... args) throws Exception {
        String baseDir = UrlUtil.getUrl();
        Collection<String> types = Arrays.asList("New", "Changed");

        Map<String, Map<Long, List<ZhishuShopGoodsRequest>>> groupedData =
                ExcelFileHandlerUtil.readExcelByTypeAndShopId(baseDir, types, ZhishuShopGoodsRequest.class);

        // 打印结果
        groupedData.forEach((type, shopMap) -> {
//            System.out.println("Type: " + type);
            shopMap.forEach((shopId, list) -> {
//                System.out.println("  Shop ID: " + shopId + ", 记录数: " + list.size());
                // 指定读取需要的商品Excel文件路径
                String baseUrl = UrlUtil.getUrl();
                String goodsExcelPath = Paths.get(baseUrl, type + "_" + shopId + "_0.xlsx").toString();
                try {
//                    System.out.println("尝试读取数据：path-" + goodsExcelPath);
                    // 尝试读取新增的数据
                    List<ZhishuShopGoodsRequest> dataList = EasyExcel.read(goodsExcelPath)
                            .head(ZhishuShopGoodsRequest.class)
                            .sheet("New_" + shopId + "_0")
                            .doReadSync();
                    // 将list中所有productId取出
                    List<String> productIdList = list.stream().map(ZhishuShopGoodsRequest::getProductId).distinct().toList();
                    // 将dataList中productId存在与list中的数据移除
                    List<ZhishuShopGoodsRequest> exportDataList = dataList.stream().filter(zhishuShopGoodsRequest -> !productIdList.contains(zhishuShopGoodsRequest.getProductId())).toList();
                    // 将剩余的dataList数据覆盖到原excel中
                    ExcelFileHandlerUtil.handleExport(exportDataList, baseUrl, type, shopId.toString(), ZhishuShopGoodsRequest.class);
                    // 调用方法重新执行这些数据
                    SaveGoodsVo saveGoodsVo = new SaveGoodsVo(null, 1, shopId, null);
                    zhishuShopGoodsService.saveShopGoodsInDb(saveGoodsVo);
                    // 数据处理完毕删除异常文件
                    ExcelFileHandlerUtil.deleteFilesByPrefix(UrlUtil.getUrl(), "Error_" + type + "_" + shopId);
                } catch (Exception e) {
                    // 读取不到说明没有对应需要处理的数据，不做处理，仅记录日志以防其他未知原因导致，不抛出异常
//                    System.out.println("未能读取新增数据文件: " + goodsExcelPath + "原因：{}" + e.getMessage());
                }
            });


        });
    }
}
