package com.cn.fdapfe.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jmatio.io.MatFileReader;
import com.jmatio.types.MLArray;
import com.jmatio.types.MLDouble;
import com.opencsv.exceptions.CsvValidationException;

import com.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileToJsonConverter {

    public static JSONArray convertFileToJsonArray(String filePath) throws IOException {
        if (filePath.endsWith(".csv")) {
            return convertCsvToJsonArray(filePath);
        } else if (filePath.endsWith(".mat")) {
            return convertMatToJsonArray(filePath);
        } else {
            throw new IllegalArgumentException("Unsupported file format. Only .csv and .mat are supported.");
        }
    }

    private static JSONArray convertCsvToJsonArray(String csvFilePath) throws IOException {
        JSONArray jsonArray = new JSONArray();
        try (CSVReader reader = new CSVReader(new FileReader(csvFilePath))) {
            List<String> headerList = new ArrayList<>();
            String[] line;
            boolean isHeader = true;
            while ((line = reader.readNext()) != null) {
                if (isHeader) {
                    for (String header : line) {
                        headerList.add(header);
                    }
                    isHeader = false;
                } else {
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 0; i < line.length; i++) {
                        jsonObject.put(headerList.get(i), line[i]);
                    }
                    jsonArray.add(jsonObject); // 使用add替代put
                }
            }
        } catch (CsvValidationException e) {
            throw new RuntimeException(e);
        }
        return jsonArray;
    }

    public static JSONArray convertMatToJsonArray(String matFilePath) throws IOException {
        JSONArray jsonArray = new JSONArray();
        try {
            MatFileReader matFileReader = new MatFileReader(matFilePath);
            Map<String, MLArray> content = matFileReader.getContent();

            for (Map.Entry<String, MLArray> entry : content.entrySet()) {
                MLArray mlArray = entry.getValue();
                if (mlArray instanceof MLDouble) {
                    MLDouble matrix = (MLDouble) mlArray;
                    int[] dimensions = matrix.getDimensions();

                    // 校验至少是二维矩阵
                    if (dimensions.length < 2) {
                        System.err.println("跳过低维数据: " + entry.getKey());
                        continue;
                    }

                    // 获取各维度大小（MATLAB维度顺序：[行, 列, 页]）
                    int rows = dimensions[0];
                    int cols = dimensions[1];
                    int pages = (dimensions.length > 2) ? dimensions[2] : 1;

                    // 获取矩阵数据（jmatio返回一维数组，按列优先存储）
//                        double[] data = matrix.getArray();

                    // 构建JSON结构
                    for (int page = 0; page < pages; page++) {
                        JSONObject pageObj = new JSONObject();
                        pageObj.put("page", page + 1); // 页码从1开始

                        JSONArray tableData = new JSONArray();
                        for (int row = 0; row < rows; row++) {
                            JSONObject rowObj = new JSONObject();
                            for (int col = 0; col < cols; col++) {
                                // 计算一维数组中的索引（考虑列优先存储）
                                int index = row + col * rows + page * rows * cols;
//                                rowObj.put("col_" + (col + 1), data[index]);
                            }
                            tableData.add(rowObj);
                        }
                        pageObj.put("data", tableData);
                        jsonArray.add(pageObj);
                    }
                }
            }
        } catch (Exception e) {
            throw new IOException("三维矩阵转换失败: " + matFilePath, e);
        }
        return jsonArray;
    }


    // 将二维数组转换为三维数组（处理jmatio的数据存储格式）
    private static double[][][] convertTo3DArray(double[][] rawData, int rows, int cols, int pages) {
        double[][][] data3D = new double[pages][cols][rows];
        int elementsPerPage = rows * cols;

        for (int page = 0; page < pages; page++) {
            int startIdx = page * elementsPerPage;
            for (int col = 0; col < cols; col++) {
                System.arraycopy(
                        rawData[col],
                        startIdx,
                        data3D[page][col],
                        0,
                        rows
                );
            }
        }
        return data3D;
    }
}