import { getIrisDataDispose, D1, D2 } from '../utils/irisDataDispose';
import { invoke } from "@tauri-apps/api/tauri";

/**
 * 光谱数据处理服务
 */
export class SpectralDataService {
  /**
   * 提取文件名
   */
  static extractFileName(filePath) {
    const match = filePath.match(/[^\\\/]+$/);
    return match ? match[0] : '';
  }

  /**
   * 加载文件数据
   */
  static async loadFileData(filePaths) {
    const fileData = [];
    for (const path of filePaths) {
      try {
        const src = await invoke("getoneirisfile", { path });
        const fileName = this.extractFileName(path);
        fileData.push({ data: src, name: fileName });
      } catch (error) {
        console.error(`加载文件失败: ${path}`, error);
      }
    }
    return fileData;
  }

  /**
   * 处理光谱数据
   */
  static processSpectralData(fileData, spectralType, processType = '', useDarkDn = true) {
    const spectralDataList = [];
    const imageList = [];

    for (const element of fileData) {
      if (!element.data) continue;

      try {
        // 传入暗噪开关
        const dispose = new getIrisDataDispose(element.data, spectralType, useDarkDn);
        const datay = dispose.initData();
        const datax = dispose.getSpectralInfoData();
        const environmentData = dispose.environmentData;
        const img = dispose.parseImageData(element.data.image_info_section);
        if (img && img.length) {
          imageList.push(img);
        } else {
          imageList.push([{
            name: element.name,
            url: 'jzsb'
          }]);
        }
        if (datay?.normalArray && datax) {
          spectralDataList.push({
            name: datay?.name || '',
            datax: datax,
            datay: datay.normalArray,
            environmentData: { ...environmentData, fileName: element.name }
          });
        }

      } catch (error) {
        console.error(`处理光谱数据失败: ${element.name}`, error);
      }
    }

    return {
      spectralDataList,
      imageList,
      processedData: this.applyProcessing(spectralDataList, processType)
    };
  }

  /**
   * 应用数据处理（D1/D2等）
   * 注意：该方法需要在类内部，避免顶层出现 static 关键字导致语法错误
   */
  static applyProcessing(spectralDataList, processType) {
    if (!processType) return spectralDataList;

    switch (processType) {
      case 'D1':
        return spectralDataList.map(item => ({
          name: item.name + '_D1',
          datax: item.datax,
          datay: D1(item.datay),
          environmentData: item.environmentData
        }));
      case 'D2':
        return spectralDataList.map(item => ({
          name: item.name + '_D2',
          datax: item.datax,
          datay: D2(item.datay),
          environmentData: item.environmentData
        }));
      default:
        return spectralDataList;
    }
  }

  /**
   * 批量处理选定文件的光谱数据
   */
  static processSelectedFiles(fileData, selectedFileNames, spectralType, processType = '', useDarkDn = true) {
    const filteredData = fileData.filter(file =>
      selectedFileNames.includes(file.name)
    );
    // 透传暗噪开关
    return this.processSpectralData(filteredData, spectralType, processType, useDarkDn);
  }
}