<template>
  <el-main style="height: 100%; width: 100%; overflow: auto;display: flex
;
    flex-direction: column;
    justify-content: space-between;">
    <el-row class="secondhang">
      <GuiForPlotShow @onComBox1="onComBox1" @onComBox2="onComBox2" @legendselectchanged="legendselectchanged"
        @useDarkDnChanged="onUseDarkDnChanged" ref="ASDPlotShow" class="plotcontainer">
      </GuiForPlotShow>
    </el-row>
    <el-row class="firsthang">
      <el-col :span="8" class="diveinfo">
        <GuiForDivesInfo ref="GuiForDivesInforef"></GuiForDivesInfo>
      </el-col>
      <el-col :span="16">
        <PictureDisplayInterface ref="PictureDisplayInterfaceRef"></PictureDisplayInterface>
        <!-- <div class="imageAndMap">

        </div>
        地图 -->
        <!-- <MapContainer></MapContainer> -->
        <!-- <a-image v-if="imgeList.length > 0" width="200" :src="imgeList[0].url" /> -->
      </el-col>
    </el-row>

  </el-main>
</template>

<script setup>
import GuiForPlotShow from "./GuiForPlotShow.vue";
import GuiForDivesInfo from "./GuiForDivesInfo.vue";
import PictureDisplayInterface from "./PictureDisplayInterface.vue";
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { spectralTypeList, spectralProcessTypeList, getIrisDataDispose } from '../../utils/irisDataDispose';
import { SpectralDataService } from '../../utils/spectralDataService';
import { ElMessage } from 'element-plus';
import EventBus from "../../eventBus.js";

defineOptions({
  name: "GuiForDataShow"
});

const fromData = ref({
  comBox1: spectralTypeList[0].value,
  comBox2: '',
});
const useDarkDn = ref(true);
const ASDPlotShow = ref(null);
const GuiForDivesInforef = ref(null);
const PictureDisplayInterfaceRef = ref(null);
const spectralDataList = ref([]);
const spectralDataForInfo = ref([]); // 新增：专供 Info/图片使用的数据
const imgeList = ref([]);
const fileData = ref([]);

async function onloaddata(data) {
  // 重置数据
  spectralDataList.value = [];
  spectralDataForInfo.value = []; // 新增：同步清空
  imgeList.value = [];
  fileData.value = [];
  if (!data || data.length === 0) {
    updateChildComponents([], [], []);
    return;
  }

  try {
    // 加载文件数据
    fileData.value = await SpectralDataService.loadFileData(data);

    // 处理数据
    await processSpectralData();

    if (!spectralDataList.value || spectralDataList.value.length === 0) {
      const typeLabel = spectralTypeList.find(i => i.value === fromData.value.comBox1)?.label || fromData.value.comBox1;
      ElMessage.warning(`当前数据没有${typeLabel}数据`);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    updateChildComponents([], [], []);
  }
}

async function processSpectralData() {
  try {
    const result = SpectralDataService.processSpectralData(
      fileData.value,
      fromData.value.comBox1,
      fromData.value.comBox2,
      useDarkDn.value
    );


    spectralDataList.value = result.spectralDataList;
    imgeList.value = result.imageList;

    // 新增：构造独立于 spectralDataList 的 spectralDataForInfo
    if (Array.isArray(result.spectralDataList) && result.spectralDataList.length > 0) {
      spectralDataForInfo.value = result.spectralDataList;
    } else {
      // fallback：基于 fileData 提取 environmentData 作为占位项
      const envOnlyList = [];
      for (const item of fileData.value) {
        try {
          const dispose = new getIrisDataDispose(item.data, fromData.value.comBox1, useDarkDn.value);
          const env = dispose?.environmentData;
          if (env) {
            envOnlyList.push({
              name: item.name || '',
              datax: [],
              datay: [],
              environmentData: { ...env, fileName: item.name },
              isEnvironmentOnly: true
            });
          }
        } catch (e) {
          console.warn('提取环境信息失败:', e);
        }
      }
      spectralDataForInfo.value = envOnlyList;
    }

    updateChildComponents(
      result.processedData,
      spectralDataForInfo.value,
      result.imageList
    );
  } catch (error) {
    console.error('处理光谱数据失败:', error);
  }
}

function updateChildComponents(processedData, spectralData, imageData) {

  ASDPlotShow.value?.onloaddata(processedData, fileData.value);
  GuiForDivesInforef.value?.onloaddata(spectralData);
  PictureDisplayInterfaceRef.value?.onloaddata(imageData, spectralData);
}

// 光谱类型
const onComBox1 = async (e) => {
  fromData.value.comBox1 = e;
  await processSpectralData();

  if (!spectralDataList.value || spectralDataList.value.length === 0) {
    const typeLabel = spectralTypeList.find(i => i.value === fromData.value.comBox1)?.label || fromData.value.comBox1;
    ElMessage.warning(`当前数据没有${typeLabel}数据`);
  }
};

// 处理方式
const onComBox2 = async (val) => {
  fromData.value.comBox2 = val;
  if (fromData.value.comBox1) {
    await processSpectralData();

    if (!spectralDataList.value || spectralDataList.value.length === 0) {
      const typeLabel = spectralTypeList.find(i => i.value === fromData.value.comBox1)?.label || fromData.value.comBox1;
      ElMessage.warning(`当前数据没有${typeLabel}数据`);
    }
  }
};

const legendselectchanged = (nameTable) => {
  if (nameTable) {
    const filteredImages = imgeList.value.filter(element => {
      if (!element || element.length === 0) return false;
      return element.some(item => {
        const str = item.name.split('.')[0];
        const str1 = (str || '').toString()?.split('_')[0];
        return nameTable.split('_')[0] === str1;
      });
    });
    const selectedSpectral = spectralDataList.value.filter(e =>
      nameTable.includes(e.name)
    );

    if (selectedSpectral.length > 0) {
      GuiForDivesInforef.value?.onloaddata(selectedSpectral);
      PictureDisplayInterfaceRef.value?.onloaddata(filteredImages, selectedSpectral);
    }
  } else {
    GuiForDivesInforef.value?.onloaddata(spectralDataForInfo.value);
    PictureDisplayInterfaceRef.value?.onloaddata(imgeList.value, spectralDataForInfo.value);
  }
};

function openSaveCurveDialog(selectedPaths) {
  const selectedNames = Array.isArray(selectedPaths)
    ? selectedPaths.map(p => (p || '').toString().split(/[\\\/]/).pop()).filter(Boolean)
    : [];
  ASDPlotShow.value?.openSaveCurveDialog(selectedNames);
}

function openSaveCurveDialogByPaths(selectedPaths) {
  ASDPlotShow.value?.openSaveCurveDialogByPaths(selectedPaths || []);
}

defineExpose({
  onloaddata,
  openSaveCurveDialog,
  openSaveCurveDialogByPaths
});

// 新增：统一清理函数，响应 triggerClearData
function clearAll() {
  // 清空本组件状态
  spectralDataList.value = [];
  spectralDataForInfo.value = []; // 新增：同步清空
  imgeList.value = [];
  fileData.value = [];
  // 通知子组件清空
  ASDPlotShow.value?.onloaddata([], []);            // 清空图表
  GuiForDivesInforef.value?.onloaddata([]);         // 清空设备信息
  PictureDisplayInterfaceRef.value?.clear?.();      // 清空图片显示
}

onMounted(() => {
  EventBus.on('triggerClearData', clearAll);
});

onBeforeUnmount(() => {
  EventBus.off('triggerClearData', clearAll);
});
// 新增：接收子组件复选框切换事件
const onUseDarkDnChanged = async (val) => {
  useDarkDn.value = !!val;
  await processSpectralData();
};
</script>

<style scoped>
.plotcontainer {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.firsthang {
  height: 42%;
  width: 100%;
  overflow: hidden;
}

.secondhang {
  height: 56%;
  width: 100%;
  text-align: center;
  overflow: hidden;
  position: relative;
}

.imageAndMap {
  width: 100%;
  height: 100%;
  background: #FDFDFD;
  border-radius: 4px;
  margin-left: 24px;
}
</style>