package org.dromara.zhishu.util;

import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvException;
import org.dromara.zhishu.domain.vo.RunningTaskNumVo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtils {

    public static List<Map<String, Object>> readLargeCsvAsMap(String fileUrl, int page, int pageSize) throws Exception {
        List<Map<String, Object>> result = new ArrayList<>();
        HttpURLConnection connection = (HttpURLConnection) new URL(fileUrl).openConnection();

        try (InputStreamReader isr = new InputStreamReader(connection.getInputStream());
             CSVReader reader = new CSVReader(isr)) {

            // 读取表头
            String[] headers = reader.readNext();
            if (headers == null) return result;

            // 跳过前N行（不加载到内存）
            long skipLines = (page - 1) * pageSize;
            while (skipLines-- > 0 && reader.readNext() != null);

            // 读取当前页
            String[] line;
            int count = 0;
            while (count < pageSize && (line = reader.readNext()) != null) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 0; i < headers.length; i++) {
                    row.put(headers[i], i < line.length ? line[i] : null);
                }
                result.add(row);
                count++;
            }
        } finally {
            connection.disconnect();
        }
        return result;
    }

    public static List<RunningTaskNumVo> queryCsvData(String csvUrl, Long taskId) {
        // 读取CSV文件
        List<String[]> csvData = null;
        try {
            csvData = readCsvFromUrl(csvUrl);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (CsvException e) {
            throw new RuntimeException(e);
        }

        // 处理数据并分组统计
        Map<String, RunningTaskNumVo> resultMap = new HashMap<>();

        // 跳过表头行
        for (int i = 1; i < csvData.size(); i++) {
            String[] row = csvData.get(i);

            // 解析CSV行数据
            Long currentTaskId = Long.parseLong(row[1]);
            Long shopId = Long.parseLong(row[9]);
            String status = row[5];

            // 只处理指定taskId的数据
            if (!currentTaskId.equals(taskId)) {
                continue;
            }

            // 创建分组键
            String groupKey = shopId + "_" + status;

            // 更新统计结果
            RunningTaskNumVo vo = resultMap.computeIfAbsent(groupKey, k -> {
                RunningTaskNumVo newVo = new RunningTaskNumVo();
                newVo.setTaskId(taskId);
                newVo.setShopId(shopId);
                newVo.setStatus(status);
                newVo.setAllNum(0);
                return newVo;
            });

            vo.setAllNum(vo.getAllNum() + 1);
        }

        return new ArrayList<>(resultMap.values());
    }

    private static List<String[]> readCsvFromUrl(String csvUrl) throws IOException, CsvException {
        URL url = new URL(csvUrl);
        try (CSVReader reader = new CSVReaderBuilder(new InputStreamReader(url.openStream()))
                .withSkipLines(0) // 不跳过任何行，包括表头
                .build()) {
            return reader.readAll();
        }
    }


    /**
     * 查询店铺日志
     */
    public static List<RunningTaskNumVo> queryTaskDataFromCsv(String csvUrl, Long taskId, Long shopId) {
        List<RunningTaskNumVo> result = new ArrayList<>();
        Map<String, RunningTaskNumVo> groupMap = new HashMap<>();

        try (CSVReader reader = new CSVReader(new InputStreamReader(new URL(csvUrl).openStream()))) {
            // 读取CSV头
            String[] headers = reader.readNext();
            if (headers == null) return result;

            // 确定各字段索引
            int taskIdIndex = findIndex(headers, "task_id");
            int shopIdIndex = findIndex(headers, "shop_id");
            int statusIndex = findIndex(headers, "status");
            int callbackIndex = findIndex(headers, "call_back_data");

            String[] line;
            while ((line = reader.readNext()) != null) {
                // 解析字段
                Long currentTaskId = Long.parseLong(line[taskIdIndex]);
                Long currentShopId = Long.parseLong(line[shopIdIndex]);
                int status = Integer.parseInt(line[statusIndex]);
                String callBackData = line[callbackIndex];

                // 应用过滤条件
                if (!currentTaskId.equals(taskId) ||
                        !currentShopId.equals(shopId) ||
                        status == 0 || status == 1 || status == 2) {
                    continue;
                }

                // 处理call_back_data分组逻辑
                String processedCallback = processCallbackData(callBackData);

                // 创建分组键
                String groupKey = status + "_" + processedCallback;

                // 更新统计结果
                RunningTaskNumVo vo = groupMap.computeIfAbsent(groupKey, k -> {
                    RunningTaskNumVo newVo = new RunningTaskNumVo();
                    newVo.setTaskId(taskId);
                    newVo.setShopId(shopId);
                    newVo.setStatus(String.valueOf(status));
                    newVo.setMsg(processedCallback);
                    newVo.setAllNum(0);
                    return newVo;
                });

                vo.setAllNum(vo.getAllNum() + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("处理CSV文件时出错");
        }

        result.addAll(groupMap.values());
        return result;
    }

    private static String processCallbackData(String callBackData) {
        if (callBackData == null) {
            return "";
        }
        if (callBackData.contains("上传成功")) {
            return "上传成功";
        } else if (callBackData.contains("属性[ISBN编号]校验错误")) {
            return "属性[ISBN编号]校验错误";
        }
        return callBackData;
    }

    private static int findIndex(String[] headers, String columnName) {
        for (int i = 0; i < headers.length; i++) {
            if (columnName.equalsIgnoreCase(headers[i])) {
                return i;
            }
        }
        throw new IllegalArgumentException("CSV中未找到列: " + columnName);
    }

    public static List<Map<String, Object>> readCsvAsMap(String fileUrl) throws Exception {
        List<Map<String, Object>> result = new ArrayList<>();
        HttpURLConnection connection = (HttpURLConnection) new URL(fileUrl).openConnection();

        try (InputStreamReader isr = new InputStreamReader(connection.getInputStream());
             CSVReader reader = new CSVReaderBuilder(isr).build()) {

            // 读取表头
            String[] headers = reader.readNext();
            if (headers == null) return result;

            // 读取所有数据行
            String[] line;
            while ((line = reader.readNext()) != null) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 0; i < headers.length; i++) {
                    row.put(headers[i], i < line.length ? line[i] : null);
                }
                result.add(row);
            }
        } finally {
            connection.disconnect();
        }
        return result;
    }
}
