<template>
  <div class="elbutton">
    <el-select v-model="fromDataPlot.comBox1" placeholder="请选择" class="blue-select" style="width: 150px"
      @change="onComBox1">
      <el-option v-for="item in spectralTypeList" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-select clearable v-model="fromDataPlot.comBox2" placeholder="请选择" class="blue-select" style="width: 150px"
      @change="onComBox2">
      <el-option v-for="item in spectralProcessTypeList" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-checkbox class="blue-checkbox" v-model="fromDataPlot.useDarkDn"
      @change="onUseDarkDnChanged">启用暗噪校正</el-checkbox>

    <!-- <el-button class="plotbutton">求导</el-button>
    <el-checkbox v-model="Prameter.smooth" @change="singleshowclicked($event, 'Smooth')">平滑</el-checkbox>
    <el-checkbox @change="singleshowclicked($event, 'single')">单条显示</el-checkbox>
    <el-checkbox @change="singleshowclicked($event, 'Radiance')">Radiance</el-checkbox>

    <el-button class="plotbutton" @click="onsavetcliked">导出数据</el-button> -->
  </div>

  <div class="echartbox">
    <div class="chart-container" ref="chartRef"></div>
  </div>
  <div class="echarts_menu">
    <el-tooltip v-for="(item, index) in echartsMenulist" :key="item.name"
      :ref="el => { if (el) tooltipRefs[index] = el }" class="box-item" effect="dark" :content="item.name"
      placement="bottom">
      <div class="echarts_menu_item" @click="handleMenuClick(item, index)">
        <img v-if="activeName === item.name" class="img2" :src="item.img2">
        <img v-else class="img1" :src="item.img1">
      </div>
    </el-tooltip>
  </div>

  <!-- 图例设置对话框 -->
  <el-dialog style="padding: 0 ; border-radius: 12px; overflow: hidden; min-width:300px; max-width:600px"
    class="legend_my_el_dialog" @close="handleClose" v-model="dialogVisible" width="24%">
    <template #title>
      <div class="legend-dialog-title">图例颜色设置</div>
    </template>
    <div v-for="(seriesItem, index) in option.series" :key="seriesItem.name" class="legend_dialog_item">
      <div class="item_box">
        <span>{{ seriesItem.name }}</span>
        <el-color-picker class="my_color_picker " :model-value="seriesItem.lineStyle?.color || '#000000'"
          @change="(val) => onColorChange(index, val)" />
      </div>
    </div>
  </el-dialog>

  <!-- 保存曲线对话框 -->
  <el-dialog style="padding: 0 ; border-radius: 12px; overflow: hidden; min-width:600px; max-width:800px"
    class="save_curve_dialog" @close="handleSaveDialogClose" v-model="saveDialogVisible" width="30%">
    <template #title>
      <div class="legend-dialog-title">保存曲线</div>
    </template>
    <div class="save-dialog-content">
      <div class="save-select-group">
        <div class="save-select-item">
          <span class="save-label">光谱类型</span>
          <el-select
            v-model="saveOptions.comBox1"
            placeholder="请选择"
            class="save-blue-select"
            style="width: 73%"
            :rules="[{ required: true, message: '请选择光谱类型', trigger: 'change' }]"
            @change="onSaveComBox1"
          >
            <el-option v-for="item in spectralTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="save-select-item">
          <span class="save-label">处理方式</span>
          <el-select
            clearable
            v-model="saveOptions.comBox2"
            placeholder="请选择"
            class="save-blue-select"
            style="width: 73%"
            :rules="[{ required: true, message: '请选择处理方式', trigger: 'change' }]"
            @change="onSaveComBox2"
          >
            <el-option v-for="item in spectralProcessTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>

      <div class="save-setting" style="margin: 8px 0 12px 0; width: 104px;">
        <el-checkbox v-model="saveOptions.useDarkDn" class="blue-checkbox">启用暗噪校正</el-checkbox>
      </div>

      <!-- 文件选择 -->
      <div class="file-selection">
        <div class="selection-header">
          <div class="selection-title">选择要保存的文件</div>
          <el-checkbox v-model="saveOptions.selectAllFiles" :indeterminate="isIndeterminate"
            @change="handleSelectAllFiles" class="my_save_checkbox">全选</el-checkbox>
        </div>
        <div class="file-list">
          <el-checkbox-group v-model="saveOptions.selectedFiles"
            :rules="[{ required: true, message: '请至少选择一个文件', trigger: 'change' }]">
            <el-checkbox class="my_save_checkbox" v-for="(file, index) in fileData" :key="index" :label="file.name"
              @change="updateSelectAllState"> {{ file.name }} </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 文件名设置 -->
      <div class="filename-setting">
        <span class="save-label">文件名</span>
        <el-input v-model="saveOptions.fileName" placeholder="请输入文件名"
          :rules="[{ required: true, message: '请输入文件名', trigger: 'blur' }]" />
      </div>

      <!-- 保存路径设置 -->
      <div class="save-path-setting">
        <span class="save-label">保存路径</span>
        <div class="path-input-group">
          <el-input v-model="saveOptions.savePath" placeholder="请选择保存路径"
            :rules="[{ required: true, message: '请选择保存路径', trigger: 'blur' }]" />
          <el-button class="input-group-button" @click="selectSavePath">选择</el-button>
        </div>
      </div>

      <!-- 保存按钮 -->
      <div class="save-actions">
        <el-button type="primary" @click="saveCurveData" class="input-group-button-primary">保存</el-button>
        <el-button @click="saveDialogVisible = false" class="input-group-button">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import * as echarts from 'echarts';
import 'zrender/lib/svg/svg';
import { ref, reactive, onMounted, onBeforeUnmount, defineExpose, nextTick } from 'vue';
import { spectralTypeList, spectralProcessTypeList, getIrisDataDispose, D1, D2 } from '../../utils/irisDataDispose';
import { save } from '@tauri-apps/api/dialog';
import { invoke } from '@tauri-apps/api/tauri';
import { fs } from '@tauri-apps/api';
import { ElMessage } from 'element-plus';
import { SpectralDataService } from '../../utils/spectralDataService';
// 定义组件名称
defineOptions({
  name: "GuiForPlotShow",
  inheritAttrs: false
});

const emit = defineEmits(['onComBox1', 'onComBox2', 'legendselectchanged', 'useDarkDnChanged'])
const images = import.meta.glob('../assets/*.png', { eager: true, import: 'default' })
const fromDataPlot = ref({
  comBox1: spectralTypeList[0].value,
  comBox2: '',
  useDarkDn: true,
})
const dialogVisible = ref(false);
const colorList = [
  '#877DFB', '#F9948D', '#4FC2DD', '#FBAE58', '#5681ED', '#7ACF97',
  '#8967D6', '#42B7DA', '#3196FB', '#F2CE4D', '#62C3AE', '#6487C9',
  '#E5934F', '#93C45D', '#C87777', '#6DC0D4', '#C8AA91', '#42A0C1',
  '#5AA583', '#8675C2', '#EE534F', '#9CEE8C', '#FF6D00', '#219BE4'
];


const onComBox1 = (val) => {
  emit('onComBox1', val);
};

// 暗噪开关变更事件
const onUseDarkDnChanged = (val) => {
  emit('useDarkDnChanged', !!val);
};


const echartsMenulist = ref([
  {
    name: '重置视图',
    img1: images['../assets/重置视图-未点击.png'],
    img2: images['../assets/重置视图-点击.png'],
  },
  {
    name: '图例设置',
    img1: images['../assets/图例设置-未点击.png'],
    img2: images['../assets/图例设置-点击.png'],
  },
  {
    name: '保存曲线',
    img1: images['../assets/保存曲线-未点击.png'],
    img2: images['../assets/保存曲线-点击.png'],
  },
])

const activeName = ref('');
const fileData = ref([])


// 保存曲线对话框相关数据
const saveDialogVisible = ref(false);
const saveOptions = reactive({
  comBox1: '',
  comBox2: '',
  selectedFiles: [],
  selectAllFiles: false,
  fileName: '',
  savePath: '',
  useDarkDn: true
});

// 添加半选状态
function openSaveCurveDialog(selectedNames) {
  try {
    if (!fileData.value || fileData.value.length === 0) {
      alert('暂无有效的曲线数据！');
      return;
    }
    // 打开弹窗并初始化默认项
    saveDialogVisible.value = true;
    initSaveOptions();

    // 按照外部传入的文件名进行预选（文件名需与 fileData.value[*].name 匹配）
    if (Array.isArray(selectedNames) && selectedNames.length > 0) {
      const onlyNames = selectedNames.map(n => (n || '').toString().split(/[\\\/]/).pop());
      const allNames = fileData.value.map(f => f.name);
      saveOptions.selectedFiles = allNames.filter(n => onlyNames.includes(n));
      updateSelectAllState();
    }
  } catch (error) {
    alert('打开保存对话框失败: ' + error);
  }
}

async function openSaveCurveDialogByPaths(filePaths) {
  try {
    const paths = Array.isArray(filePaths) ? filePaths.filter(Boolean) : [];
    if (paths.length === 0) {
      alert('请选择要导出的文件');
      return;
    }

    // 仅为保存弹窗临时加载数据，不更新图表
    const loaded = await SpectralDataService.loadFileData(paths);
    if (!loaded || loaded.length === 0) {
      alert('未能加载到有效的文件数据');
      return;
    }
    fileData.value = loaded;

    // 打开并初始化弹窗
    saveDialogVisible.value = true;
    initSaveOptions();

    // 预勾选当前传入的文件
    const onlyNames = paths.map(p => (p || '').toString().split(/[\\\/]/).pop());
    const allNames = fileData.value.map(f => f.name);
    saveOptions.selectedFiles = allNames.filter(n => onlyNames.includes(n));
    updateSelectAllState();
  } catch (error) {
    alert('打开保存对话框失败: ' + error);
  }
}

const isIndeterminate = ref(false);

// 处理保存对话框关闭
function handleSaveDialogClose() {
  saveDialogVisible.value = false;
  activeName.value = '';
}

const tooltipRefs = ref([]);

// 处理全选文件
function handleSelectAllFiles(val) {
  if (val) {
    saveOptions.selectedFiles = fileData.value.map(file => file.name);
  } else {
    saveOptions.selectedFiles = [];
  }
  updateSelectAllState();
}

// 更新全选状态
function updateSelectAllState() {
  const selectedCount = saveOptions.selectedFiles.length;
  const totalCount = fileData.value.length;

  if (selectedCount === 0) {
    saveOptions.selectAllFiles = false;
    isIndeterminate.value = false;
  } else if (selectedCount === totalCount) {
    saveOptions.selectAllFiles = true;
    isIndeterminate.value = false;
  } else {
    saveOptions.selectAllFiles = false;
    isIndeterminate.value = true;
  }
}


// 初始化保存对话框数据
function initSaveOptions() {
  saveOptions.comBox1 = fromDataPlot.value.comBox1;
  saveOptions.comBox2 = fromDataPlot.value.comBox2;
  saveOptions.useDarkDn = fromDataPlot.value.useDarkDn;

  // 默认选中所有文件
  if (fileData.value && fileData.value.length > 0) {
    saveOptions.selectedFiles = fileData.value.map(file => file.name);
    saveOptions.selectAllFiles = true;
  } else {
    saveOptions.selectedFiles = [];
    saveOptions.selectAllFiles = false;
  }

  // 更新全选状态
  updateSelectAllState();

  // 设置默认文件名
  const now = new Date();
  const dateStr = now.toISOString().replace(/[\-:.]/g, "_").split("T")[0];
  saveOptions.fileName = `${dateStr}_${saveOptions.comBox1}${saveOptions.comBox2 ? '_' + saveOptions.comBox2 : ''}`;

  saveOptions.savePath = '';
}

async function selectSavePath() {
  try {
    const selectedPath = await save({
      title: '选择保存路径',
      defaultPath: saveOptions.fileName ? `${saveOptions.fileName}.csv` : undefined
    });

    if (selectedPath) {
      saveOptions.savePath = selectedPath;

      if (!saveOptions.fileName) {
        const pathParts = selectedPath.split(/[\\\/]/);
        const fileName = pathParts[pathParts.length - 1];
        if (fileName) {
          saveOptions.fileName = fileName.replace(/\.csv$/i, '');
        }
      }
    }
  } catch (error) {
    alert("选择保存路径出错: " + error);
  }
}

// 保存曲线数据
async function saveCurveData() {
  try {
    if (!saveOptions.comBox1) {
      alert("请选择光谱类型！");
      return;
    }

    if (saveOptions.selectedFiles.length === 0) {
      alert("请至少选择一个文件！");
      return;
    }

    if (!saveOptions.fileName) {
      alert("请输入文件名！");
      return;
    }

    if (!saveOptions.savePath) {
      alert("请选择保存路径！");
      return;
    }

    const targets = getPitchOnData(saveOptions); // 获取数据数组
    if (!targets || !Array.isArray(targets) || targets.length === 0) {
      alert("无有效的数据");
      return;
    }

    // 筛选选中的文件和曲线数据
    const selectedTargets = targets.filter(t => {
      // 检查文件名称是否被选中
      const isFileSelected = saveOptions.selectedFiles.includes(t.environmentData.fileName);
      return isFileSelected;
    });

    if (selectedTargets.length === 0) {
      alert("没有符合条件的数据可以导出！");
      return;
    }

    // 构建CSV内容
    const header = ["wavelength", ...selectedTargets.map(t => t.name)].join(",") + "\n";
    let content = header;

    const length = selectedTargets[0].datax.length;
    for (let i = 0; i < length; i++) {
      let row = [selectedTargets[0].datax[i]];
      for (let j = 0; j < selectedTargets.length; j++) {
        row.push(selectedTargets[j].datay[i]);
      }
      content += row.join(",") + "\n";
    }

    // 使用用户指定的文件名和路径
    let filePath = saveOptions.savePath;

    //校验文件路径以.csv结尾
    if (!filePath.toLowerCase().endsWith(".csv")) {
      filePath += ".csv";
    }
    filePath = filePath.replace(/\\/g, '/');

    // 创建并保存文件
    const bom = '\uFEFF';
    await fs.writeTextFile(filePath, bom + content);
    console.log("文件已成功保存到: " + filePath);

    ElMessage.success(`文件已成功保存到 ${filePath}`)

    saveDialogVisible.value = false;
  } catch (error) {
    alert("保存文件失败: " + error);
  }
}

// 保存弹窗：光谱类型选择变更
function onSaveComBox1(val) {
  try {
    saveOptions.comBox1 = val;

    const targets = getPitchOnData(saveOptions);
    if (!targets || !Array.isArray(targets) || targets.length === 0) {
      const typeLabel = spectralTypeList.find(i => i.value === saveOptions.comBox1)?.label || saveOptions.comBox1;
      ElMessage.warning(`当前数据没有${typeLabel}数据`);
    }
  } catch (error) {
    console.error('保存弹窗光谱类型切换处理失败:', error);
  }
}

// 保存弹窗：处理方式选择变更
function onSaveComBox2(val) {
  try {
    saveOptions.comBox2 = val;

    if (saveOptions.comBox1) {
      const targets = getPitchOnData(saveOptions);
      if (!targets || !Array.isArray(targets) || targets.length === 0) {
        const typeLabel = spectralTypeList.find(i => i.value === saveOptions.comBox1)?.label || saveOptions.comBox1;
        ElMessage.warning(`当前数据没有${typeLabel}数据`);
      }
    }
  } catch (error) {
    console.error('保存弹窗处理方式切换处理失败:', error);
  }
}

// 文件数据处理
function getPitchOnData(saveOptions) {
  try {
    const result = SpectralDataService.processSelectedFiles(
      fileData.value,
      saveOptions.selectedFiles,
      saveOptions.comBox1,
      saveOptions.comBox2,
      saveOptions.useDarkDn
    );
    return result.processedData;
  } catch (error) {
    console.error('处理保存数据失败:', error);
    return [];
  }
}

// 菜单点击事件
function handleMenuClick(item, index) {
  try {
    // 手动隐藏 tooltip
    if (tooltipRefs.value[index]) {
      tooltipRefs.value[index].hide();
    }

    activeName.value = activeName.value === item.name ? '' : item.name;

    if (item.name === '重置视图') {
      const chartDom = chartRef.value;
      const chart = echarts.getInstanceByDom(chartDom);
      if (chart) {
        chart.dispatchAction({
          type: 'dataZoom',
          start: 0,
          end: 100
        });
      }
      setTimeout(() => {
        activeName.value = ''
      }, 500)
    } else if (item.name === '图例设置') {
      if (option.value.series && option.value.series.length > 0 && option.value.series[0].data && option.value.series[0].data.length > 0) {
        dialogVisible.value = true;
      } else {
        activeName.value = ''
        alert("暂无有效的图例！");
      }
    } else if (item.name === '保存曲线') {
      if (option.value.series && option.value.series.length > 0 && fileData.value && fileData.value.length > 0) {
        saveDialogVisible.value = true;
        initSaveOptions()
      } else {
        activeName.value = ''
        alert("暂无有效的曲线数据！");
      }
    }
  } catch (error) {
    alert("系统报错,", error);
  }
}
// 图例颜色改变事件
function onColorChange(index, val) {
  try {
    const chartDom = chartRef.value;
    const chart = echarts.getInstanceByDom(chartDom);
    if (!chart) return;

    // 更新 series 颜色
    option.value.series[index].lineStyle = option.value.series[index].lineStyle || {};
    option.value.series[index].lineStyle.color = val;

    option.value.series[index].itemStyle = option.value.series[index].itemStyle || {};
    option.value.series[index].itemStyle.color = val;

    // 同步更新 legend 的颜色
    if (option.value.legend && option.value.legend.data && option.value.legend.data[index]) {
      option.value.legend.data[index].itemStyle = option.value.legend.data[index].itemStyle || {};
      option.value.legend.data[index].itemStyle.color = val;
    }

    // 局部刷新图表，合并方式为 false，不重置状态
    chart.setOption({
      series: [{
        name: option.value.series[index].name,
        lineStyle: { color: val },
        itemStyle: { color: val }
      }],
      legend: {
        data: option.value.legend.data
      }
    }, false);
  } catch (error) {
    alert("颜色设置出错," + error);
  }
}




function handleClose() {
  dialogVisible.value = false
  activeName.value = ''
}

// 图表创建
function onloaddata(data, files) {
  try {
    fileData.value = files
    Prameter.Data = data;
    option.value.series = [];
    option.value.legend.data = [];

    if (data && data.length > 0) {
      option.value.xAxis = {
        ...option.value.xAxis,
        min: null,
        max: null
      };
      if (Array.isArray(option.value.yAxis)) {
        option.value.yAxis = option.value.yAxis.map(ax => ({ ...ax, min: null, max: null }));
      } else {
        option.value.yAxis = {
          ...option.value.yAxis,
          min: null,
          max: null
        };
      };

      // 遍历数据创建多条折线
      data.forEach((item, index) => {
        let serilatemp = {
          id: item.name + '_' + index,
          name: item.name,
          type: 'line',
          symbol: 'none',
          smooth: true,
          data: item.datax.map((x, i) => [x, item.datay[i]]),
          lineStyle: {
            color: colorList[index % colorList.length]
          }
        };


        serilatemp.data = item.datax.map((x, i) => {
          let y = item.datay[i];
          return [x, y];
        });


        option.value.legend.data.push({
          name: item.name,
          icon: 'rect',
          itemStyle: {
            color: colorList[index % colorList.length]
          }
        });
        option.value.series.push(serilatemp);
      });
    } else {
      // 当数据为空时，恢复默认的xy轴范围
      option.value.xAxis = {
        ...option.value.xAxis,
        min: -100,
        max: 100
      };
      if (Array.isArray(option.value.yAxis)) {
        option.value.yAxis = option.value.yAxis.map(ax => ({ ...ax, min: -100, max: 100 }));
      } else {
        option.value.yAxis = {
          ...option.value.yAxis,
          min: -100,
          max: 100
        };
      };
      option.value.series = [];
      option.value.legend.data = [];
    }
    option.value.legend.itemHeight = 2
    option.value.legend.itemWidth = 16

    // 更新图表
    flushplot();
  } catch (error) {
    alert('图表创建出错', error)
  }

}

// 图表配置
function initChart() {
  const chartDom = chartRef.value;
  let chart = echarts.init(chartDom, null, { renderer: 'svg' });
  option.value = {
    color: colorList,
    grid: {
      left: 10,
      right: 30,
      bottom: 30,
      containLabel: true
    },
    toolbox: {
      left: 'center',
      feature: {
        dataZoom: {},
        restore: {}
      }
    },
    animation: false,
    xAxis: {
      type: 'value',
      min: -100,
      max: 100,
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.2)'
        }
      },
      axisTick: { show: false },
      axisLabel: { color: 'rgba(0, 0, 0, 0.70)' }
    },
    yAxis: [
      {
        type: 'value',
        min: -100,
        max: 100,
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.2)'
          }
        },
        axisTick: { show: false },
        axisLabel: { color: 'rgba(0, 0, 0, 0.70)' },
        position: 'left'
      },
      {
        type: 'value',
        min: -100,
        max: 100,
        axisLine: {
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.2)'
          }
        },
        axisTick: { show: false },
        axisLabel: { color: 'rgba(0, 0, 0, 0.70)' },
        position: 'right'  // 右侧轴
      }
    ],
    dataZoom: [
      // 显式绑定到 x/y 轴，支持框选缩放
      { type: 'inside', xAxisIndex: [0], filterMode: 'none' },
      { type: 'inside', yAxisIndex: [0], filterMode: 'none' },
      { type: 'slider', xAxisIndex: [0], filterMode: 'none', height: 35, bottom: 15 },
      { type: 'slider', yAxisIndex: [0], filterMode: 'none', width: 35, right: 25 }
    ],
    legend: {
      itemHeight: 2,
      itemWidth: 16,
      show: true,
      type: 'scroll',
      orient: 'horizontal',
      icon: 'rect',
      top: 10,
      right: 10,
      height: 30,
      width: 400,
      pageIconColor: '#4271EE',
      pageTextStyle: { color: '#4271EE' },
      itemWidth: 14,
      itemHeight: 10,
      textStyle: { color: 'rgba(0, 0, 0, 0.70)' },
      selectedMode: 'multiple'
    },
    series: [
      {
        data: [],
        type: 'line',
        symbol: 'none',
        smooth: true
      }
    ]
  };

  let selectedLegend = null;
  chart.setOption(option.value, true);

  // 启用“左键框选缩放”模式
  chart.dispatchAction({
    type: 'takeGlobalCursor',
    key: 'dataZoomSelect',
    dataZoomSelectActive: true
  });

  window.addEventListener('resize', echartresize);

  // 监听图例点击事件，控制单条显示与恢复全部
  chart.off('legendselectchanged');
  chart.on('legendselectchanged', (params) => {
    const clickedName = params.name;

    if (selectedLegend === clickedName) {
      emit("legendselectchanged", '')
      selectedLegend = null;
      option.value.series.forEach(item => {
        chart.dispatchAction({ type: 'legendSelect', name: item.name });
      });
    } else {
      emit("legendselectchanged", clickedName)
      selectedLegend = clickedName;
      option.value.series.forEach(item => {
        if (item.name === clickedName) {
          chart.dispatchAction({ type: 'legendSelect', name: item.name });
        } else {
          chart.dispatchAction({ type: 'legendUnSelect', name: item.name });
        }
      });
    }
  });

  // 双击恢复缩放到初始范围
  chart.getZr().off('dblclick');
  chart.getZr().on('dblclick', () => {
    (option.value.dataZoom || []).forEach((_, idx) => {
      chart.dispatchAction({ type: 'dataZoom', dataZoomIndex: idx, start: 0, end: 100 });
    });
  });
}


const onComBox2 = (val) => {
  emit('onComBox2', val);
};


// 响应式数据
const Prameter = reactive({
  smooth: false,
  singleshow: false,
  Radiance: "DN",
  Data: null,
  zoomLock: false
});


// 引用
const chartRef = ref(null);
const option = ref({});

// 强制更新图表
function flushplot() {
  const chartDom = chartRef.value;
  const chart = echarts.getInstanceByDom(chartDom);
  if (chart) {
    setTimeout(() => {
      chart.setOption(option.value, true);
      chart.dispatchAction({
        type: 'dataZoom',
        start: 0,
        end: 100
      });

      chart.dispatchAction({
        type: 'takeGlobalCursor',
        key: 'dataZoomSelect',
        dataZoomSelectActive: true
      });
      chart.resize();
    }, 0);
  }
}

function echartresize() {
  console.log("resize");
  const chartDom = chartRef.value;
  let chart = echarts.getInstanceByDom(chartDom);
  if (chart) chart.resize();
}

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

onBeforeUnmount(() => {
  const chartDom = chartRef.value;
  if (chartDom) {
    let chart = echarts.getInstanceByDom(chartDom);
    if (chart) {
      chart.dispose();
    }
  }
});


// 暴露方法和数据给父组件
defineExpose({
  onloaddata,
  Prameter,
  fromDataPlot,
  openSaveCurveDialog,
  openSaveCurveDialogByPaths
});

</script>

<style scoped lang="less">
.chart-container {
  top: 0;
  width: 100%;
  height: 100%;
}

.echartbox {
  width: 100%;
  height: 100%;
}

.plotbutton {
  margin-right: 20px;
}

.elbutton {
  position: absolute;
  top: 0;
  left: 0;
  height: 40px;
  z-index: 9;
  display: flex;
  justify-content: flex-start;
}

.blue-select :deep(.el-select__wrapper) {
  background-color: rgba(66, 113, 238, 0.10);
  box-shadow: none;
  border: 1.4px solid rgba(66, 113, 238, 1);
}


.blue-select :deep(.el-select__placeholder),
.blue-select :deep(.el-select__caret) {
  color: #4271EE;
}


.blue-select :deep(.el-input__wrapper.is-focus) {}

.blue-select {
  margin-right: 20px;
}

.blue-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: rgba(66, 113, 238, 1);
  border-color: rgba(66, 113, 238, 1);
}

.blue-checkbox :deep(.el-checkbox__input.is-checked+.el-checkbox__label) {
  color: #4271EE;
}

.save-blue-select:deep(.el-select__wrapper) {
  background-color: #fff;
  box-shadow: none;
  border: 1.4px solid #E2E5E7;
}

.save-blue-select :deep(.el-select__placeholder),
.save-blue-select :deep(.el-select__caret) {
  color: #434959;
}


.echarts_menu {
  height: 36px;
  min-width: 120px;
  background: #EDF1FB;
  border-radius: 4px;
  border: 1px solid #D3D8E3;
  position: absolute;
  left: calc(50% - 60px);
  display: flex;
  align-items: center;
  justify-content: space-around;

  .echarts_menu_item {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .img1 {
      width: 18px;
      height: 18px;
    }

    .img2 {
      width: 100%;
      height: 100%;
    }

    &:hover {
      background-color: #DFE3EE;
      border-radius: 4px;
    }
  }

}
</style>

<style lang="less">
:deep(.el-select-dropdown__item.is-selected) {
  color: #4271EE;
}

.legend-dialog-title {
  text-align: left;
  height: 50px;
  line-height: 50px;
  background: #F3F5FA;
  border-radius: 12px 12px 0px 0px;
  padding: 0;
  font-weight: 600;
  padding-left: 30px;
}

.legend_my_el_dialog .el-dialog__header.show-close {
  padding: 0 !important;
  font-size: 16px;
  color: #333333;

  .el-dialog__headerbtn {
    box-shadow: none;
    top: 4px;
    right: 14px;
    font-size: 24px;
    color: #000;

    .el-icon {
      fill: #000;

      path {
        fill: #000;
      }
    }
  }


}

.legend_my_el_dialog {

  .el-dialog__body {
    padding: 0 30px;
    max-height: 65vh;
    overflow-y: auto;
  }

  .legend_dialog_item {
    height: 50px;
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E2E5E7;

    &>.item_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 1;
    }
  }
}

input {
  box-shadow: none;
}


.save_curve_dialog {
  .el-dialog__header.show-close {
    padding: 0 !important;
    font-size: 16px;
    color: #333333;

    .el-dialog__headerbtn {
      box-shadow: none;
      top: 4px;
      right: 14px;
      font-size: 24px;
      color: #000;

      .el-icon {
        fill: #000;

        path {
          fill: #000;
        }
      }
    }
  }

  .el-dialog__body {
    padding: 0 30px 30px;
  }

  .save-dialog-content {
    margin-top: 24px;

    .save-select-group {
      display: flex;

      .save-select-item {
        flex: 1;
        display: flex;
        align-items: center;
        margin-bottom: 15px;



        .save-blue-select {}
      }

      &>.save-select-item:nth-child(1) {
        margin-right: 20px;
      }
    }

    .file-selection {
      margin-bottom: 20px;

      .selection-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      }

      .selection-title {
        font-weight: 500;
      }

      .file-list {
        max-height: 150px;
        overflow-y: auto;
        padding: 10px 24px;
        border: 1px solid #E2E5E7;
        border-radius: 4px;

        .el-checkbox-group {
          display: flex;
          flex-direction: column;
          gap: 10px;
        }
      }

      .my_save_checkbox {
        .el-checkbox__input.is-checked+.el-checkbox__label {
          color: #4271EE;
        }

        .el-checkbox__input.is-checked .el-checkbox__inner {
          border-color: #4271EE;
          background-color: #4271EE;
        }

        .el-checkbox__input.is-indeterminate .el-checkbox__inner {
          background-color: #4271EE;
          border-color: #4271EE;
        }

      }
    }

    .curve-selection {
      margin-bottom: 20px;

      .selection-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      }

      .selection-title {
        margin-bottom: 10px;
        font-weight: 500;
      }

      .curve-list {
        max-height: 200px;
        overflow-y: auto;
        padding: 10px;
        border: 1px solid #E2E5E7;
        border-radius: 4px;

        .el-checkbox-group {
          display: flex;
          flex-direction: column;
          gap: 10px;
        }
      }
    }

    .filename-setting {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      &>div {
        flex: 1;
      }
    }

    .save-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 20px;
    }


    .el-input__wrapper.is-focus {
      box-shadow: 0 0 0 1px #dcdfe6;
    }

    .input-group-button {
      margin-left: 10px;
      box-shadow: none;
      background-color: #EDF1FB;
      color: #6B7181;
      border: 1px solid #D3D8E3;
    }

    .input-group-button-primary {
      box-shadow: none;
      color: #fff;
      background-color: #4271EE;
    }

    .el-button:hover {
      color: #6B7181;
      border-color: #aaabad;
    }

    .input-group-button-primary:hover {
      color: #fff;
      border-color: #4271EE;
    }
  }
}

.save-path-setting {
  margin-top: 15px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;

  .path-input-group {
    display: flex;
    align-items: center;
    flex: 1;




  }

  .path-input-group .el-input {
    flex: 1;
  }
}

.save-label {
  width: 56px;
  text-align: right;
  margin-right: 10px;
  color: #434959;
}
</style>