<template>
  <div class="app-container">
    <div class="seismic-container">
      <!-- 左侧地震图 -->
      <div class="seismic-block">
        <div class="containerBlock">
          <!-- 添加加载状态和错误提示 -->
          <div v-if="loadingError" class="error-message">
            {{ loadingError }}
          </div>
          <div class="toolbar" v-if="isWidgetReady">
            <!-- 左侧内容 -->
            <div class="toolbar-left">
              <!-- 左侧可以留空，或者将来添加其他控件 -->
            </div>
            <!-- 右侧按钮组 -->
            <div class="toolbar-right">
              <div class="color-maps">
                <el-select v-model="currentColorMap" @change="switchColorMap" size="small">
                  <el-option v-for="map in colorMaps" :key="map.value" :label="map.label" :value="map.value">
                    <span class="color-map-option">
                      <span class="color-map-preview" :class="map.value"></span>
                      {{ map.label }}
                    </span>
                  </el-option>
                </el-select>
              </div>
              <toolbar-controls :plots="plots" :data-loaded="isWidgetReady" :show-line-style-panel="showLineStylePanel"
                @toggleLineStylePanel="toggleLineStylePanel" @exporting="exporting = $event"
                @closePrintDialog="showPrintDialog = false" />

              <el-tooltip content="绘制文本" placement="bottom" effect="light">
                <el-button @click="toggleDrawText" :class="{ 'active': isDrawingText }">
                  <i class="el-icon-edit-outline"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="绘制线条" placement="bottom" effect="light">
                <el-button @click="toggleLineStylePanel" :class="{ 'active': showLineStylePanel }">
                  <i class="el-icon-edit"></i>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <canvas ref="plot" id="canvas" />
          <!-- 添加鼠标悬停专用覆盖层 -->
          <div ref="hoverLayer" class="hover-layer"></div>
          <!-- 添加悬停信息显示面板 -->
          <div class="cursor-info-panel" v-if="showCursorInfo && cursorInfo.depth !== null && isHovering">
            <div class="info-pill">
              <span>Depth: {{ cursorInfo.depth !== null ? cursorInfo.depth.toFixed(2) : 'N/A' }}</span>
            </div>
            <div class="info-pill">
              <span>Trace: {{ cursorInfo.trace !== null ? cursorInfo.trace.toFixed(0) : 'N/A' }}</span>
            </div>
            <div class="info-pill">
              <span>Value: {{ cursorInfo.value !== null ?
                (typeof cursorInfo.value === 'string' ? cursorInfo.value :
                  (typeof cursorInfo.value === 'number' ? cursorInfo.value.toFixed(4) : 'N/A'))
                : 'N/A' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧地震图（克隆） -->
      <div class="seismic-block">
        <div class="containerBlock">
          <!-- 这里可以放置第二个地震图的内容 -->
          <!-- 后续可以根据需要添加 -->
        </div>
      </div>
    </div>

    <!-- 其他面板和菜单保持不变 -->
    <!-- ... 其他现有代码 ... -->
  </div>
</template>

<script>
import { SeismicViewWidget } from '@int/geotoolkit/seismic/widgets/SeismicViewWidget';
import { SeismicColors } from '@int/geotoolkit/seismic/util/SeismicColors';
import { SeismicPipeline } from '@int/geotoolkit/seismic/pipeline/SeismicPipeline';
import { SegyReader } from '@int/geotoolkit/seismic/data/SegyReader';
import { StandardSegyFormat } from '@int/geotoolkit/seismic/data/StandardSegyFormat';
import { LocalFile } from '@int/geotoolkit/seismic/data/LocalFile';
import { Plot } from '@int/geotoolkit/plot/Plot';
import { getToken } from '@/utils/auth';
import { Group } from '@int/geotoolkit/scene/Group';
import { Paint } from '@int/geotoolkit/controls/tools/Paint';
import { PaintMode } from '@int/geotoolkit/controls/tools/PaintMode';
import { EditEvents } from '@int/geotoolkit/controls/tools/EditEvents';
import { EditMode } from '@int/geotoolkit/controls/tools/EditMode';
import { Selection, Events as SelectionEvents } from '@int/geotoolkit/controls/tools/Selection';
import { TextStyle } from '@int/geotoolkit/attributes/TextStyle';
import { LineStyle } from '@int/geotoolkit/attributes/LineStyle';
import { FillStyle } from '@int/geotoolkit/attributes/FillStyle';
import { Path } from '@int/geotoolkit/scene/shapes/Path';
import { Text } from '@int/geotoolkit/scene/shapes/Text';  // 添加这行导入
import { LINE_PATTERNS, FILL_PATTERNS, TEXT_PATTERNS, LINESTYLE_PATTERNS, IMAGE_PATTERNS, LS_KEYS, FS_KEYS, TS_KEYS } from '@/api/Patterns.js';
import { SizeMode } from '@int/geotoolkit/scene/shapes/Text';
import { RgbaColor } from '@int/geotoolkit/util/RgbaColor';
import { NormalizationType } from '@int/geotoolkit/seismic/pipeline/NormalizationType';
// 导入新的组件
import ToolbarControls from '@/components/ToolbarControls.vue';
import LineStylePanel from '@/components/LineStylePanel.vue';
import { NoSnapPicking } from '@int/geotoolkit/seismic/data/snap/NoSnapPicking';
import { SnapPicker } from '@int/geotoolkit/seismic/data/snap/SnapPicker';

// 线条样式模式常量
const TEXT_PATTERN_KEYS = Object.keys(TEXT_PATTERNS);
const FILL_PATTERN_KEYS = Object.keys(FILL_PATTERNS);
const LINE_PATTERN_KEYS = Object.keys(LINE_PATTERNS);

// 在export default前添加interpolate函数
const interpolate = function (target, startIndex, endIndex, startColor, endColor) {
  // 添加参数验证
  if (!target || !Array.isArray(target)) {
    console.error('interpolate: target必须是数组');
    return;
  }

  if (typeof startIndex !== 'number' || typeof endIndex !== 'number' ||
    startIndex < 0 || endIndex >= target.length || startIndex > endIndex) {
    console.error(`interpolate: 索引无效 - startIndex: ${startIndex}, endIndex: ${endIndex}, target.length: ${target.length}`);
    return;
  }

  if (!startColor || !endColor ||
    typeof startColor.R !== 'number' || typeof startColor.G !== 'number' || typeof startColor.B !== 'number' ||
    typeof endColor.R !== 'number' || typeof endColor.G !== 'number' || typeof endColor.B !== 'number') {
    console.error('interpolate: 颜色必须包含有效的RGB值');
    return;
  }

  const offset = startIndex;
  const stop = (endIndex - startIndex);
  let r, g, b;

  const stepR = (endColor.R - startColor.R) / (stop);
  const stepG = (endColor.G - startColor.G) / (stop);
  const stepB = (endColor.B - startColor.B) / (stop);

  try {
    for (let i = 0; i <= stop; ++i) {
      r = startColor.R + i * stepR;
      g = startColor.G + i * stepG;
      b = startColor.B + i * stepB;
      target[offset + i] = new RgbaColor(
        Math.round(r < 255 ? r : 255),
        Math.round(g < 255 ? g : 255),
        Math.round(b < 255 ? b : 255),
        255
      );
    }
  } catch (error) {
    console.error(`interpolate: 创建颜色时出错 - ${error.message}`);
  }
};

export default {
  name: "seismic",
  components: {
    ToolbarControls,
    LineStylePanel
  },
  data() {
    return {
      plots: null,
      fileTxt: '',
      widget: null,
      annotationTool: null,
      annotations: null,
      isDrawingText: false,
      showTextStylePanel: false,
      showLineStylePanel: false,
      showPrintDialog: false,
      exporting: false,
      pdfExporting: false,
      // 添加模拟数据
      savedAnnotations: [{
        type: "未知类型",
        text: "地震",
        properties: {
          id: null,
          name: "",
          cssclass: null,
          selectable: true,
          visible: true,
          tag: null,
          localtransform: null,
          clipstyle: null,
          responsivestyle: null,
          renderingfilter: null,
          scalescrollstrategy: {},
          linestyle: {
            links: {
              Invalidate: {
                yn: new Array(33).fill(null),
                stack: 0,
                gDa: false
              }
            },
            silent: false,
            u3: false,
            uL: 33,
            Ek: 1,
            Lx: "rgba(100, 158, 227, 1)",
            Zr: null,
            Jeb: null,
            xVa: [],
            fA: 3,
            Ewa: {
              x: false,
              y: false
            },
            XGa: "round",
            UGa: "butt",
            Cs: null,
            Td: null
          },
          fillstyle: {
            links: {
              Invalidate: {
                yn: new Array(33).fill(null),
                stack: 0,
                gDa: false
              }
            },
            silent: false,
            u3: false,
            uL: 33,
            Ek: 0,
            Lx: "rgba(30, 70, 102, 1)",
            Zr: null,
            Jeb: null,
            Ox: {
              links: {
                Invalidate: {
                  yn: new Array(6).fill(null),
                  stack: 0,
                  gDa: false
                }
              },
              silent: false,
              u3: false,
              uL: 6,
              P6: "",
              v7a: null,
              containerName: null,
              image: {},
              pattern: {},
              zbc: 160,
              ybc: 16,
              cache: {},
              Eba: {
                noforegroundcolor: null
              },
              tv: {},
              p3a: false,
              hCa: false,
              Sga: 160,
              Rga: 16,
              l4: 1,
              m4: 1,
              y4a: false
            },
            iO: false
          },
          ax: 826.370447661679,
          ay: 2.1615720524017465,
          width: 99.99999999999994,
          height: 30.000000000000057,
          rotationangle: 0,
          alignment: 5,
          sizeisindevicespace: true,
          preserveaspectratio: false,
          ispointingup: true,
          preservereadingorientation: true,
          preserverightangle: true,
          useminmaxdimensions: false,
          mindimension: null,
          maxdimension: null,
          layoutstyle: null,
          text: "地震",
          textstyle: {
            links: {
              Invalidate: {
                yn: [],
                stack: 0,
                gDa: false
              }
            },
            silent: false,
            u3: false,
            uL: 0,
            Ek: 0,
            Lx: "rgba(200, 109, 109, 1)",
            Zr: null,
            Jeb: null,
            lH: "bold 22px Arial Black",
            Cua: "middle",
            Vf: "left",
            y9: "100%",
            hS: true,
            E2: true,
            ofa: {
              fontweight: "bold",
              fontsize: "22px",
              fontfamily: "Arial Black",
              fontlineheight: "normal",
              fontstyle: "normal"
            },
            Km: null,
            iGa: "Arial Black",
            eZ: "22px",
            c3: "bold",
            b3: "normal"
          },
          bounds: null,
          layout: {
            readOnly: false,
            x: 0,
            y: 0,
            width: 44,
            height: 22
          },
          sizemode: 3,
          userheight: 30.000000000000057,
          userwidth: 99.99999999999994,
          radius: 10,
          padding: 0,
          transform: "none",
          ellipsisstring: "..."
        },
        textStyle: {
          font: "bold 22px Arial Black",
          color: "rgba(200, 109, 109, 1)",
          size: 22,
          alignment: "left",
          bold: true,
          italic: false
        },
        lineStyle: {
          color: "rgba(100, 158, 227, 1)",
          width: 3,
          pattern: "Solid"
        },
        fillStyle: {
          color: "rgba(30, 70, 102, 1)",
          pattern: "Carets"
        }
      }],
      // 添加鼠标悬停相关的数据
      cursorInfo: {
        depth: null,
        trace: null,
        value: null
      },
      showCursorInfo: true,
      isHovering: false,
      // 添加画笔工具相关属性
      pencilTool: null,
      selectedShape: null,
      selectedShapes: [],
      annotationLayer: null,
      pencilState: {
        isDrawing: false,
        currentPath: null,
        lastPoint: null,
        paths: []
      },
      pencilConfig: {
        minDistance: 2,  // 减小最小距离使绘制更流畅
        lineWidth: 2,
        lineColor: '#0351ad',
        linePattern: 'Solid'
      },
      // 更新颜色映射选择器
      currentColorMap: 'WhiteBlack', // 默认使用黑白渐变
      colorMaps: [
        { value: 'WhiteBlack', label: '黑白渐变' },
        { value: 'CustomGrayScale', label: '灰度渐变' },
        { value: 'CustomRedScale', label: '红色渐变' }
      ], // 可用的颜色映射
      textStyle: {
        color: '#000000',
        size: 22,
        font: 'Sans-serif',
        bold: false,
        italic: false,
        align: 'left',
        wrap: true,
        ellipsis: true,
        borderRadius: 10,
        fixedFont: false,
      },
      lineStyle: {
        color: '#0351ad',
        width: 2,
        pattern: 'Solid'
      },
      fillStyle: {
        color: '#c7e1f6',
        pattern: 'Solid',
        opacity: 100
      },
      fillPatterns: IMAGE_PATTERNS,

      TEXT_PATTERNS: TEXT_PATTERNS,
      FILL_PATTERNS: FILL_PATTERNS,
      LINE_PATTERNS: LINE_PATTERNS,
      LINESTYLE_PATTERNS: LINESTYLE_PATTERNS,
      linePatterns: LINESTYLE_PATTERNS,

      initialLineStyle: null,
      initialTextStyle: null,
      initialFillStyle: null,

      textPatterns: {
        'None': [0, 10],
        'Solid': [],
        'Dash': [20, 4],
        'Dot': [2, 4],
        'DashDot': [20, 4, 2, 4],
        'DashDotDot': [20, 4, 2, 4, 2, 4]
      },

      isWidgetReady: false,
      loadingError: null,
      pipeline: null,
      colorProvider: null,

      // 右键菜单相关数据
      contextMenu: {
        visible: false,
        x: 0,
        y: 0
      },
      contextMenuItems: [
        {
          text: '撤销',
          icon: 'mdi-undo',
          shortcut: 'Ctrl+Z',
          action: 'undo'
        },
        {
          text: '重做',
          icon: 'mdi-redo',
          shortcut: 'Ctrl+Y',
          action: 'redo'
        },
        { type: 'separator' },
        {
          text: '复制',
          icon: 'mdi-content-copy',
          shortcut: 'Ctrl+C',
          action: 'copy'
        },
        {
          text: '粘贴',
          icon: 'mdi-content-paste',
          shortcut: 'Ctrl+V',
          action: 'paste'
        },
        {
          text: '删除',
          icon: 'mdi-delete',
          shortcut: 'Del',
          action: 'delete'
        }
      ],
      clipboard: null, // 用于存储复制的路径
      undoStack: [], // 撤销栈
      redoStack: [], // 重做栈
      _headers: [], // 添加这一行
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.createScene(this.$refs.plot);

      if (this.widget) {
        this.widget.on('ready', () => {
          this.initAnnotationTools(this.widget);
          // 初始化鼠标工具
          this.initCursorTools();
        });
      }
    });

    if (this.$refs.plot) {
      this.$refs.plot.addEventListener('contextmenu', this.showContextMenu);
      document.addEventListener('click', this.hideContextMenu);
      // 添加键盘事件监听
      window.addEventListener('keydown', this.handleKeyDown);

      // 添加鼠标悬停相关事件
      this.$refs.plot.addEventListener('mouseenter', () => {
        this.isHovering = true;
      });
      this.$refs.plot.addEventListener('mouseleave', () => {
        this.isHovering = false;
      });
      this.$refs.plot.addEventListener('mousemove', this.handleMouseMove);
    }
  },
  methods: {
    onFileOpen(evt, plot, fileInfo) {
      evt.stopPropagation();
      evt.preventDefault();
      const files = evt.target.files;
      return this.handleFileSelect(this.plots);
    },
    handleFileSelect(plot) {
      let url = process.env.VUE_APP_BASE_API + "/ndy/dz/getSegyDataFile?fileName=density.segy";
      let fileName = 'density.segy';

      fetch(url, {
        headers: {
          Authorization: "Bearer " + getToken()
        }
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error(`网络请求失败: ${response.status} ${response.statusText}`);
          }
          return response.blob();
        })
        .then((blob) => {
          if (!blob || blob.size === 0) {
            throw new Error('获取到的文件数据为空');
          }

          let filesObj = new File([blob], fileName, { type: blob.type, lastModified: Date.now() });
          let files = [];
          files.push(filesObj);

          if (!this.widget) {
            this.loadingError = 'Widget未初始化，无法加载数据';
            console.error(this.loadingError);
            return;
          }

          if (files.length > 0) {
            const file = new LocalFile(files[0]);
            if (!file) {
              this.loadingError = '无法创建LocalFile对象';
              console.error(this.loadingError);
              return;
            }

            try {
              // 确保 _headers 被重置
              this._headers = [];

              new SegyReader(file, new StandardSegyFormat(), -6)
                .loadMetaData((reader) => {
                  if (reader instanceof Error) {
                    this.loadingError = `加载元数据失败: ${reader.message}`;
                    console.error(this.loadingError);
                    return;
                  }

                  // 获取头信息字段
                  const knownHeaders = reader.getTraceHeaderFields();
                  let cdpHeader = null;

                  // 确保 knownHeaders 存在且是数组
                  if (knownHeaders && Array.isArray(knownHeaders)) {
                    knownHeaders.forEach((field) => {
                      if (field && field.getName) {
                        if (field.getName() === 'CDP') {
                          cdpHeader = field;
                        }
                        this._headers.push({
                          'visible': field.getName() === 'CDP',
                          'name': field.getName(),
                          'color': 'black'
                        });
                      }
                    });
                  }

                  // 如果没有CDP字段，使用第一个可用字段
                  if (cdpHeader == null && this._headers.length > 0) {
                    this._headers[0].visible = true;
                  }

                  reader.readDataSetStatistics((reader, statistics) => {
                    try {
                      if (!statistics) {
                        throw new Error('无法获取数据集统计信息');
                      }

                      const pipeline = new SeismicPipeline(file.name, reader, statistics);
                      if (!pipeline) {
                        throw new Error('无法创建SeismicPipeline');
                      }

                      const colorProvider = SeismicColors.getDefault();
                      if (!colorProvider) {
                        throw new Error('无法获取默认颜色提供者');
                      }

                      // 保存引用以便后续使用
                      this.pipeline = pipeline;
                      this.colorProvider = colorProvider;

                      // 注册颜色映射
                      this.registerColorMaps(colorProvider);

                      // 使用当前选择的颜色映射
                      const colorMap = colorProvider.createNamedColorMap(this.currentColorMap);
                      if (!colorMap) {
                        console.warn(`颜色映射'${this.currentColorMap}'创建失败，回退到默认映射`);
                        // 尝试使用第一个可用的颜色映射
                        if (this.colorMaps.length > 0) {
                          this.currentColorMap = this.colorMaps[0];
                          const fallbackColorMap = colorProvider.createNamedColorMap(this.currentColorMap);
                          if (!fallbackColorMap) {
                            throw new Error('无法创建任何颜色映射');
                          }
                          pipeline.setColorMap(fallbackColorMap);
                        } else {
                          throw new Error('无法创建任何颜色映射，且没有可用的备选映射');
                        }
                      } else {
                        pipeline.setColorMap(colorMap);
                      }

                      // 优化pipeline设置
                      pipeline.setOptions({
                        'normalization': {
                          'type': NormalizationType.RMS,
                          'scale': 0.4  // 增加scale以提高对比度
                        },
                        'plot': {
                          'type': {
                            'Wiggle': false,
                            'InterpolatedDensity': true,
                            'SimpleDensity': false
                          },
                          'decimationSpacing': 5,  // 减小decimationSpacing以提高精度
                        }
                      });

                      if (this.widget) {
                        try {
                          // 设置freezeupdate选项，防止null引用错误
                          this.widget.setOptions({ 'freezeupdate': false });

                          // 设置pipeline并适应边界
                          this.widget.setPipeline(pipeline);
                          this.widget.fitToBounds();
                          this.initAnnotationTools(this.widget);

                          // 在widget中配置坐标轴
                          this.widget.setOptions({
                            'axes': {
                              'samples': {  // Y轴
                                'title': {
                                  'visible': false
                                }
                              },
                              'headers': {  // X轴
                                'fields': this._headers,
                                'options': {
                                  'minimumSpan': 100
                                }
                              }
                            }
                          });
                        } catch (error) {
                          this.loadingError = `设置widget属性失败: ${error.message}`;
                          console.error('Error configuring widget:', error);
                        }
                      } else {
                        throw new Error('Widget在设置pipeline时不可用');
                      }
                    } catch (error) {
                      this.loadingError = `设置pipeline失败: ${error.message}`;
                      console.error('Error setting up pipeline:', error);
                    }
                  });
                });
            } catch (error) {
              this.loadingError = `加载SEGY文件失败: ${error.message}`;
              console.error('Error loading SEGY file:', error);
            }
          }
        })
        .catch(error => {
          this.loadingError = `获取地震数据失败: ${error.message}`;
          console.error('Error fetching seismic data:', error);
        });
    },

    createScene(canvas) {
      try {
        // 创建SeismicViewWidget实例
        this.widget = new SeismicViewWidget(null, {
          'colorbar': {
            'axis': {
              'tickgenerator': {
                'edge': {
                  'tickvisible': false,
                  'labelvisible': false
                }
              }
            }
          },
          'layouttype': 'inside',
          'statusbar': {
            'visible': false
          },
          'freezeupdate': false // 初始化时明确设置freezeupdate为false
        });

        // 创建Plot实例
        this.plots = new Plot({
          'root': this.widget,
          'canvasElement': canvas
        });

        // 确保widget和plot都创建完成后再加载数据
        this.$nextTick(() => {
          this.handleFileSelect(this.plots);
        });
      } catch (error) {
        this.loadingError = `创建场景失败: ${error.message}`;
        console.error('Error creating scene:', error);
      }
    },

    initAnnotationTools(widget) {
      if (!this.checkWidgetStatus()) return;

      try {
        // 创建注释层
        this.annotations = new Group();
        widget.getOverlayLayer().addChild(this.annotations);

        // 创建注释工具
        this.annotationTool = new Paint({
          'layer': widget.getManipulatorLayer(),
          'node': {
            'radius': 10,
            'fillstyle': '#c7e1f6',
            'linestyle': {
              'color': '#0351ad',
              'width': 2
            },
            'textbox': {
              'border': true,
              'borderradius': 10,
              'fixedsize': false,
              'wordwrap': true,
              'padding': 5
            },
            'selectable': true,
            'movable': true,
            'editable': true
          },
          'handles': {
            'anchor': {
              'fillstyle': '#8be73d',
              'linestyle': '#0351ad'
            }
          }
        });

        // 添加选择工具，确保它能选择注释层中的对象
        const selectionTool = new Selection()
          .setNodeFilter((nodes) => nodes.filter((node) =>
            this.annotations.indexOfChild(node) >= 0))
          .addListener(SelectionEvents.onPick, (tool, eventArgs) => {
            // 如果注释工具不可用，则返回
            if (!this.annotationTool.isEnabled() && !this.pencilTool?.isEnabled()) return;

            const selection = eventArgs.getSelection();
            const length = selection.length;

            // 如果没有选中任何形状并且当前处于编辑模式，则清除当前编辑节点
            if (length === 0) {
              if (this.annotationTool.getMode() === PaintMode.Edit) {
                this.annotationTool.editNode(null);
              }
              if (this.pencilTool && this.pencilTool.getMode() === PaintMode.Edit) {
                this.pencilTool.editNode(null);
              }
            }
            // 如果选中了形状，且不是当前正在编辑的形状，则开始编辑该形状
            else if (length > 0) {
              const selectedNode = selection[length - 1];
              const currentTool = this.annotationTool.isEnabled() ? this.annotationTool :
                (this.pencilTool && this.pencilTool.isEnabled() ? this.pencilTool : null);

              if (currentTool && selectedNode !== currentTool.getShape()) {
                currentTool.setEditMode(EditMode.EditNode);
                currentTool.editNode(selectedNode);
                this.selectedShape = selectedNode;
                eventArgs.stopPropagation(true, true);
              }
            }
          });

        widget.getTool().insert(0, selectionTool);

        // 添加事件监听
        this.annotationTool
          .addListener(EditEvents.Start, (tool, command) => {
            this.annotations.addChild(command.getNode());
          })
          .addListener(EditEvents.End, (tool, node) => {
            tool.setEditMode(EditMode.EditNode);
            tool.editNode(node);
            this.selectedShape = node;

            // 保存标注数据
            this.saveAnnotation(node);

            this.requestRepaint();
          });

        this.annotationTool
          .editNode(null)
          .setEnabled(false);

        widget.getTool().insert(0, this.annotationTool);
        this.isWidgetReady = true;

        // 在这里添加调用创建文本的方法
        this.createTextAtPosition();

        // 恢复保存的标注
        this.restoreAnnotations();
      } catch (error) {
        console.error('初始化注释工具时出错:', error);
        this.loadingError = error.message;
      }
    },

    toggleDrawText() {
      if (!this.checkWidgetStatus() || !this.isWidgetReady) {
        console.warn('Widget or annotation tools not ready');
        return;
      }

      if (!this.annotationTool) {
        console.warn('注释工具未初始化');
        return;
      }

      this.isDrawingText = !this.isDrawingText;
      this.showTextStylePanel = this.isDrawingText;

      if (this.isDrawingText) {
        // 确保文本大小为22px
        this.textStyle.size = 22;

        // 创建完整的字体字符串，确保包含字体大小
        const fontString = `${this.textStyle.bold ? 'bold ' : ''}${this.textStyle.italic ? 'italic ' : ''}${this.textStyle.size}px ${this.textStyle.font}`;

        // 先设置属性
        const textProperties = {
          'editmode': EditMode.Create,
          'mode': PaintMode.Text,
          'node': {
            'textstyle': new TextStyle({
              color: this.textStyle.color,
              size: this.textStyle.size,
              font: fontString, // 使用完整的字体字符串
              alignment: this.textStyle.align,
              bold: this.textStyle.bold,
              italic: this.textStyle.italic
            }),
            'textbox': {
              'border': this.textStyle.borderRadius > 0,
              'borderradius': this.textStyle.borderRadius,
              'padding': this.textStyle.borderRadius > 0 ? this.textStyle.borderRadius : 5,
              'fixedsize': this.textStyle.fixedFont
            },
            'selectable': true,
            'movable': true,
            'editable': true,
            'preserveontextfinish': true,
            'preserveonblur': true,
            'autofocus': true,
            'sizemode': this.textStyle.fixedFont ?
              (SizeMode.FixedWidth | SizeMode.FixedHeight) :
              SizeMode.WrappedWidth
          }
        };

        console.log('文本绘制工具配置:', textProperties);
        this.annotationTool.setProperties(textProperties);

        // 添加事件监听器来打印文本绘制数据
        this.annotationTool.addListener(EditEvents.Start, (tool, command) => {
          const node = command.getNode();
          const textStyle = node.getTextStyle ? node.getTextStyle() : null;
          console.log('开始绘制文本:', {
            tool: tool.getMode(),
            node: node,
            properties: node.getProperties(),
            textStyle: textStyle,
            fontSize: textStyle ? textStyle.size || textStyle.font : this.textStyle.size
          });
        });

        this.annotationTool.addListener(EditEvents.Change, (tool, event) => {
          const node = tool.getShape();
          if (node) {
            const textStyle = node.getTextStyle ? node.getTextStyle() : null;
            console.log('文本绘制更新:', {
              properties: node.getProperties(),
              bounds: node.getBounds ? node.getBounds() : null,
              textStyle: textStyle,
              fontSize: textStyle ? textStyle.size || textStyle.font : this.textStyle.size
            });
          }
        });

        this.annotationTool.addListener(EditEvents.End, (tool, node) => {
          if (node) {
            let text = '';
            if (typeof node.getText === 'function') {
              text = node.getText();
            } else if (node.text) {
              text = node.text;
            } else if (node.getProperties && node.getProperties().text) {
              text = node.getProperties().text;
            }

            const textStyle = node.getTextStyle ? node.getTextStyle() : null;
            console.log('文本绘制完成:', {
              properties: node.getProperties(),
              text: text,
              bounds: node.getBounds ? node.getBounds() : null,
              textStyle: textStyle,
              fontSize: textStyle ? textStyle.size || textStyle.font : this.textStyle.size,
              currentTextStyle: this.textStyle
            });
          }
        });

        this.annotationTool.setEnabled(true);
      } else {
        this.annotationTool.setEnabled(false);
        this.annotationTool.editNode(null);
      }
    },

    removeAnnotation() {
      if (this.annotationTool && this.annotationTool.isEnabled() &&
        this.annotationTool.getMode() === PaintMode.Edit &&
        this.annotationTool.getShape()) {
        if (Array.isArray(this.annotationTool.getShape())) {
          this.annotationTool.getShape().forEach((shape) => shape.dispose());
        } else {
          this.annotationTool.getShape().dispose();
        }
        this.annotationTool.editNode(null);
      }
    },

    updateAllStyles() {
      if (this.annotationTool && this.annotationTool.getShape()) {
        const shape = this.annotationTool.getShape();

        // 创建完整的字体字符串
        const fontString = `${this.textStyle.bold ? 'bold ' : ''}${this.textStyle.italic ? 'italic ' : ''}${this.textStyle.size}px ${this.textStyle.font}`;

        // 创建基本文本样式
        const textStyle = new TextStyle({
          'font': fontString,
          'color': this.textStyle.color,
          'alignment': this.textStyle.align
        });

        // 创建线条样式
        const lineStyle = new LineStyle({
          'color': this.lineStyle.color,
          'width': this.lineStyle.width,
          'pattern': this.getProcessedLinePattern(this.lineStyle.pattern)
        });

        // 创建填充样式
        const fillStyle = new FillStyle(
          this.fillStyle.color,
          this.fillPatterns[this.fillStyle.pattern]
        );

        // 设置形状的所有属性
        const shapeProperties = {
          'textstyle': textStyle,
          'linestyle': lineStyle,
          'fillstyle': fillStyle,
          'sizemode': this.textStyle.fixedFont ?
            (SizeMode.FixedWidth | SizeMode.FixedHeight) :
            SizeMode.WrappedWidth,
          'textbox': {
            'border': this.textStyle.borderRadius > 0,
            'borderradius': this.textStyle.borderRadius,
            'padding': this.textStyle.borderRadius > 0 ? this.textStyle.borderRadius : 5
          }
        };

        // 在形状上设置所有属性
        shape.setProperties(shapeProperties);

        // 在工具上设置属性
        this.annotationTool.setProperties({
          'textbox': shapeProperties.textbox,
          'sizemode': shapeProperties.sizemode
        });

        // 打印更新后的样式数据
        console.log('样式更新:', {
          type: shape.getType ? shape.getType() : '未知类型',
          text: shape.getText ? shape.getText() : null,
          properties: shape.getProperties(),
          textStyle: {
            font: fontString,
            color: this.textStyle.color,
            size: this.textStyle.size,
            alignment: this.textStyle.align,
            bold: this.textStyle.bold,
            italic: this.textStyle.italic
          },
          lineStyle: {
            color: this.lineStyle.color,
            width: this.lineStyle.width,
            pattern: this.lineStyle.pattern
          },
          fillStyle: {
            color: this.fillStyle.color,
            pattern: this.fillStyle.pattern
          }
        });

        // 强制重绘
        if (shape.invalidate) {
          shape.invalidate();
        }
      }
    },

    // 修改字体大小变化处理方法
    handleFontSizeChange(value) {
      this.textStyle.size = value;
      this.updateAllStyles();

      // 更新所有已绘制的文本
      if (this.annotations) {
        const children = this.annotations.getChildren();
        if (children) {
          children.forEach(shape => {
            if (shape.getText) {
              const fontString = `${this.textStyle.bold ? 'bold ' : ''}${this.textStyle.italic ? 'italic ' : ''}${value}px ${this.textStyle.font}`;
              const textStyle = new TextStyle({
                font: fontString,
                color: this.textStyle.color,
                alignment: this.textStyle.align
              });

              shape.setProperties({
                'textstyle': textStyle
              });

              // 打印更新的文本数据
              console.log('更新已存在的文本:', {
                text: shape.getText(),
                properties: shape.getProperties(),
                textStyle: {
                  font: fontString,
                  size: value,
                  color: this.textStyle.color,
                  alignment: this.textStyle.align
                }
              });
            }
          });
        }
        this.requestRepaint();
      }
    },

    // 修改字体变化处理方法
    handleFontChange(value) {
      this.textStyle.font = value;
      this.updateAllStyles();

      // 更新所有已绘制的文本
      if (this.annotations) {
        const children = this.annotations.getChildren();
        if (children) {
          children.forEach(shape => {
            if (shape.getText) {
              const fontString = `${this.textStyle.bold ? 'bold ' : ''}${this.textStyle.italic ? 'italic ' : ''}${this.textStyle.size}px ${value}`;
              const textStyle = new TextStyle({
                font: fontString,
                color: this.textStyle.color,
                alignment: this.textStyle.align
              });

              shape.setProperties({
                'textstyle': textStyle
              });

              // 打印更新的文本数据
              console.log('更新已存在的文本:', {
                text: shape.getText(),
                properties: shape.getProperties(),
                textStyle: {
                  font: fontString,
                  color: this.textStyle.color,
                  alignment: this.textStyle.align
                }
              });
            }
          });
        }
        this.requestRepaint();
      }
    },

    // 修改字体样式处理方法
    handleFontStyleChange() {
      this.updateAllStyles();
    },

    updateTextStyle() {
      this.updateAllStyles();
    },

    updateLineStyle() {
      // 创建新的线条样式
      const lineStyle = new LineStyle({
        color: this.lineStyle.color,
        width: this.lineStyle.width,
        pattern: this.getProcessedLinePattern(this.lineStyle.pattern)
      });

      // 如果pencilTool正在使用，更新其属性
      if (this.pencilTool && this.pencilTool.isEnabled()) {
        this.pencilTool.setProperties({
          'node': {
            'linestyle': lineStyle
          }
        });

        // 如果有选中的形状，也更新它的样式
        if (this.selectedShape) {
          this.selectedShape.setProperties({
            'linestyle': lineStyle
          });

          // 打印更新后的线条样式数据
          console.log('线条样式更新:', {
            type: this.selectedShape.getType ? this.selectedShape.getType() : '未知类型',
            properties: this.selectedShape.getProperties(),
            lineStyle: {
              color: this.lineStyle.color,
              width: this.lineStyle.width,
              pattern: this.lineStyle.pattern
            }
          });

          this.requestRepaint();
        }
      }

      // 更新所有已绘制的线条
      if (this.annotations) {
        const children = this.annotations.getChildren();
        if (children) {
          children.forEach(shape => {
            if (shape instanceof Path) {
              shape.setProperties({
                'linestyle': lineStyle
              });

              // 打印每个更新的线条数据
              console.log('更新已存在的线条:', {
                type: shape.getType ? shape.getType() : '未知类型',
                properties: shape.getProperties(),
                lineStyle: {
                  color: this.lineStyle.color,
                  width: this.lineStyle.width,
                  pattern: this.lineStyle.pattern
                }
              });
            }
          });
        }
        this.requestRepaint();
      }
    },

    updateFillStyle() {
      this.updateAllStyles();
    },

    getFillPatternStyle(key) {
      // 基本样式对象
      const baseStyle = {
        height: '24px',
        width: '100%',
        marginTop: '5px',
        marginBottom: '5px',
        border: '1px solid #ddd',
        background: 'white' // 设置白色背景以便更好显示样式
      };

      // 如果是Solid模式，直接使用设置的颜色
      if (key === 'Solid') {
        return {
          ...baseStyle,
          background: this.fillStyle.color
        };
      }

      // 如果是None，显示透明背景
      if (key === 'None') {
        return {
          ...baseStyle,
          background: 'transparent'
        };
      }

      // 使用FILL_PATTERNS中的URL作为背景
      if (this.FILL_PATTERNS && this.FILL_PATTERNS[key]) {
        return {
          ...baseStyle,
          backgroundImage: `url(${this.FILL_PATTERNS[key]})`,
          backgroundRepeat: 'repeat',
          backgroundSize: 'auto'
        };
      }

      // 默认返回基本样式
      return baseStyle;
    },

    getLinePatternStyle(key) {
      let dashStyle = '';

      // 使用处理后的线条模式
      const patternArray = this.getProcessedLinePattern(key);
      if (patternArray && patternArray.length > 0) {
        dashStyle = patternArray.join('px ') + 'px';
      }

      return {
        background: 'transparent',
        backgroundImage: `url(${this.LINE_PATTERNS[key]})`,
        backgroundRepeat: 'no-repeat',
        backgroundSize: 'contain',
        backgroundPosition: 'center',
        height: '20px',
        width: '100%',
        margin: '5px 0'
      };
    },

    getProcessedLinePattern(pattern) {
      // 如果pattern是数组，直接返回
      if (Array.isArray(pattern)) {
        return pattern;
      }

      // 如果pattern是LINESTYLE_PATTERNS的键，使用该值
      if (this.linePatterns && this.linePatterns[pattern]) {
        return this.linePatterns[pattern];
      }

      // 根据常见的模式名称提供默认数组
      if (typeof pattern === 'string') {
        switch (pattern) {
          case 'Dash':
            return [20, 4];
          case 'Dot':
            return [2, 4];
          case 'DashDot':
            return [20, 4, 2, 4];
          case 'DashDotDot':
            return [20, 4, 2, 4, 2, 4];
          case 'ShortDash':
            return [10, 4];
          case 'LongDash':
            return [40, 4];
          case 'DashLongDash':
            return [20, 4, 40, 4];
          case 'Solid':
          case 'None':
          default:
            return []; // 默认为实线
        }
      }

      // 默认返回空数组（实线）
      console.log('使用默认实线模式，无法识别模式:', pattern);
      return [];
    },

    debounce(fn, delay = 300) {
      let timer = null;
      return (...args) => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    checkWidgetStatus() {
      if (!this.widget) {
        console.warn('Widget未初始化');
        this.loadingError = 'Widget未初始化';
        return false;
      }

      // 检查widget的关键方法是否可用
      const requiredMethods = ['setPipeline', 'fitToBounds', 'getOverlayLayer', 'getManipulatorLayer', 'getTool', 'invalidate'];
      for (const method of requiredMethods) {
        if (typeof this.widget[method] !== 'function') {
          console.error(`Widget缺少关键方法: ${method}`);
          this.loadingError = `Widget初始化不完整，缺少方法: ${method}`;
          return false;
        }
      }

      try {
        // 验证freezeupdate设置是否正常工作
        this.widget.setOptions({ 'freezeupdate': false });
      } catch (error) {
        console.error('设置widget选项失败:', error);
        this.loadingError = `Widget选项设置失败: ${error.message}`;
        return false;
      }

      return true;
    },

    // 修改边框圆角更新方法
    handleBorderRadiusChange(value) {
      // 确保值为数字
      const radius = parseInt(value) || 0;
      this.textStyle.borderRadius = radius;
      this.updateAllStyles();
    },

    // 修改固定字体更新方法
    handleFixedFontChange(value) {
      this.textStyle.fixedFont = value;
      this.updateAllStyles();
    },

    // 添加清除所有工具状态的方法
    clearAllTools() {
      this.showTextStylePanel = false;
      this.showLineStylePanel = false;
      this.isDrawingText = false;

      if (this.annotationTool) {
        this.annotationTool.setEnabled(false);
        this.annotationTool.editNode(null);
      }

      if (this.pencilTool) {
        this.pencilTool.setEnabled(false);
        const widget = this.plots.getRoot();
        if (widget && widget.getTool()) {
          widget.getTool().remove(this.pencilTool);
        }
      }

      this.requestRepaint();
    },

    // 修改请求重绘的方法
    requestRepaint() {
      // 只调用有invalidate方法的对象
      if (this.widget) {
        this.widget.invalidate();
      }
      if (this.annotations) {
        this.annotations.invalidate();
      }
      if (this.plots && this.plots.getRoot()) {
        this.plots.getRoot().invalidate();
      }
    },

    // 添加更新选择视觉反馈的方法
    updateSelectionVisualFeedback() {
      // 更新所有形状的选中状态
      if (this.annotationLayer) {
        const children = this.annotationLayer.getChildren();
        if (children) {
          children.forEach(shape => {
            const isSelected = this.selectedShapes.indexOf(shape) >= 0;
            shape.setProperties({
              'selected': isSelected
            });
          });
        }
      }
      this.requestRepaint();
    },

    // 添加切换颜色映射的方法
    switchColorMap(colorMapName) {
      if (!this.pipeline || !this.colorProvider) {
        console.error('Pipeline or colorProvider not initialized');
        return;
      }

      this.currentColorMap = colorMapName;

      // 添加额外的检查，确保colorMap不为null
      const colorMap = this.colorProvider.createNamedColorMap(colorMapName);
      if (!colorMap) {
        console.error(`创建颜色映射失败: ${colorMapName}可能未正确注册`);
        return;
      }

      // 使用有效的colorMap
      this.pipeline.setColorMap(colorMap);

      // 使用正确的方法更新视图
      if (this.widget) {
        this.widget.invalidate(); // 使组件重新渲染
        this.widget.fitToBounds(); // 调整视图以适应数据
      } else {
        console.error('Widget不可用，无法更新视图');
      }

      // 如果plots对象存在redraw方法，使用它来触发重绘
      if (this.plots && typeof this.plots.redraw === 'function') {
        this.plots.redraw();
      }

      console.log(`切换到颜色映射: ${colorMapName}`);
    },

    // 添加注册颜色映射的方法
    registerColorMaps(colorProvider) {
      if (!colorProvider) {
        console.error('colorProvider为空，无法注册颜色映射');
        return;
      }

      try {
        // 注册黑白渐变色映射（与seismicplot一致）
        colorProvider.register('WhiteBlack', (map) => {
          if (!map) {
            console.error('WhiteBlack映射对象为空');
            return;
          }

          const colors = new Array(255);

          try {
            // 白色到黑色的渐变
            interpolate(colors, 0, 254, {
              A: 255,
              R: 255,
              G: 255,
              B: 255
            }, {
              A: 255,
              R: 0,
              G: 0,
              B: 0
            });

            map.set(colors);
          } catch (error) {
            console.error('设置WhiteBlack颜色映射失败:', error);
          }
        });

        // 注册灰度渐变色映射
        colorProvider.register('CustomGrayScale', (map) => {
          if (!map) {
            console.error('CustomGrayScale映射对象为空');
            return;
          }

          const colors = new Array(255);

          try {
            // -4000到181范围保持纯白色
            interpolate(colors, 0, 110, {
              A: 255,
              R: 255,
              G: 255,
              B: 255
            }, {
              A: 255,
              R: 255,
              G: 255,
              B: 255
            });

            // 181开始，从(253,253,253)开始到566
            interpolate(colors, 111, 120, {
              A: 255,
              R: 253,
              G: 253,
              B: 253
            }, {
              A: 255,
              R: 240,
              G: 240,
              B: 240
            });

            // 566开始，颜色开始变深
            interpolate(colors, 121, 160, {
              A: 255,
              R: 240,
              G: 240,
              B: 240
            }, {
              A: 255,
              R: 180,
              G: 180,
              B: 180
            });

            // 继续渐变到深色
            interpolate(colors, 161, 254, {
              A: 255,
              R: 180,
              G: 180,
              B: 180
            }, {
              A: 255,
              R: 6,
              G: 6,
              B: 6
            });

            map.set(colors);
          } catch (error) {
            console.error('设置CustomGrayScale颜色映射失败:', error);
          }
        });

        // 注册新的红色系列渐变映射
        colorProvider.register('CustomRedScale', (map) => {
          if (!map) {
            console.error('CustomRedScale映射对象为空');
            return;
          }

          const colors = new Array(255);

          try {
            // 第1段：起始红色到红棕色 (0-20%)
            interpolate(colors, 0, 40, {
              A: 255,
              R: 246,
              G: 40,
              B: 26
            }, {
              A: 255,
              R: 221,
              G: 139,
              B: 102
            });

            // 第2段：红棕色到浅褐色 (20-40%)
            interpolate(colors, 41, 84, {
              A: 255,
              R: 221,
              G: 139,
              B: 102
            }, {
              A: 255,
              R: 215,
              G: 198,
              B: 146
            });

            // 第3段：浅褐色到白色 (40-60%)
            interpolate(colors, 85, 126, {
              A: 255,
              R: 215,
              G: 198,
              B: 146
            }, {
              A: 255,
              R: 251,
              G: 250,
              B: 255
            });

            // 第4段：白色到灰紫色 (60-75%)
            interpolate(colors, 127, 168, {
              A: 255,
              R: 251,
              G: 250,
              B: 255
            }, {
              A: 255,
              R: 110,
              G: 110,
              B: 138
            });

            // 第5段：灰紫色到深灰 (75-90%)
            interpolate(colors, 169, 210, {
              A: 255,
              R: 110,
              G: 110,
              B: 138
            }, {
              A: 255,
              R: 50,
              G: 49,
              B: 54
            });

            // 第6段：保持深灰到结束 (90-100%)
            interpolate(colors, 211, 254, {
              A: 255,
              R: 50,
              G: 49,
              B: 54
            }, {
              A: 255,
              R: 50,
              G: 49,
              B: 54
            });

            map.set(colors);
          } catch (error) {
            console.error('设置CustomRedScale颜色映射失败:', error);
          }
        });

        console.log('颜色映射注册成功');
      } catch (error) {
        console.error('注册颜色映射失败:', error);
      }
    },

    toggleLineStylePanel() {
      // 如果工具已经激活，则停用
      if (this.showLineStylePanel) {
        this.deactivatePencilTool();
        return;
      }

      this.clearAllTools();
      this.showLineStylePanel = true;

      if (!this.checkWidgetStatus() || !this.isWidgetReady) return;

      const widget = this.plots.getRoot();
      if (!widget) return;

      // 确保注释层存在
      if (!this.annotations) {
        this.annotations = new Group();
        widget.getOverlayLayer().addChild(this.annotations);
        this.annotations.setVisible(true);
      }

      // 创建或更新铅笔工具
      if (!this.pencilTool) {
        const lineStyle = new LineStyle({
          color: this.lineStyle.color,
          width: this.lineStyle.width,
          pattern: this.getProcessedLinePattern(this.lineStyle.pattern)
        });

        const pencilProperties = {
          'layer': widget.getManipulatorLayer(),
          'mode': PaintMode.Pencil,
          'editmode': EditMode.Create,
          'node': {
            'linestyle': lineStyle,
            'selectable': true,
            'movable': true,
            'editable': true
          }
        };

        console.log('线条绘制工具配置:', pencilProperties);
        this.pencilTool = new Paint(pencilProperties);

        // 添加事件监听
        this.pencilTool
          .addListener(EditEvents.Start, (tool, command) => {
            const node = command.getNode();
            console.log('开始绘制线条:', {
              tool: tool.getMode(),
              properties: node.getProperties()
            });
            this.annotations.addChild(node);
          })
          .addListener(EditEvents.Change, (tool, event) => {
            const node = tool.getShape();
            if (node) {
              console.log('线条绘制更新:', {
                properties: node.getProperties(),
                bounds: node.getBounds ? node.getBounds() : null
              });
            }
          })
          .addListener(EditEvents.End, (tool, node) => {
            if (node) {
              console.log('线条绘制完成:', {
                properties: node.getProperties(),
                bounds: node.getBounds ? node.getBounds() : null
              });
            }

            if (node && this.annotations.indexOfChild(node) === -1) {
              this.annotations.addChild(node);
            }

            tool.setEditMode(EditMode.EditNode);
            tool.editNode(node);
            this.selectedShape = node;
            this.requestRepaint();
          });
      }

      // 设置工具为活动状态
      this.pencilTool.setMode(PaintMode.Pencil);
      this.pencilTool.setEditMode(EditMode.Create);

      // 获取工具管理器并添加工具
      const toolManager = widget.getTool();

      try {
        toolManager.remove(this.pencilTool);
      } catch (e) {
        // 忽略错误，工具可能已经被移除
      }

      toolManager.insert(0, this.pencilTool);
      this.pencilTool.setEnabled(true);
    },

    deactivatePencilTool() {
      this.showLineStylePanel = false;
      if (this.pencilTool) {
        this.pencilTool.setEnabled(false);
        const widget = this.plots.getRoot();
        if (widget && widget.getTool()) {
          try {
            widget.getTool().remove(this.pencilTool);
          } catch (e) {
            // 忽略错误，工具可能已经被移除
          }
        }

        // 清除选中的形状
        this.selectedShape = null;
      }
    },

    zoomIn() {
      if (this.plots && this.dataLoaded && !this.zoomInProgress) {
        // ... 放大实现
      }
    },

    zoomOut() {
      if (this.plots && this.dataLoaded && !this.zoomInProgress) {
        // ... 缩小实现
      }
    },

    async exportToPDF(data) {
      if (!this.plots || !this.isWidgetReady) {
        this.$message.warning('请等待数据加载完成');
        return;
      }

      try {
        // 处理PDF导出逻辑...
        this.$message.success('PDF导出成功');
      } catch (error) {
        console.error('导出PDF时发生错误:', error);
        this.$message.error('导出PDF失败: ' + error.message);
      } finally {
        // 确保无论导出成功还是失败，都关闭弹窗
        this.showPrintDialog = false;
      }
    },

    /**
     * 显示右键菜单
     */
    showContextMenu(event) {
      event.preventDefault();

      // 获取当前活动的工具和选中的形状
      const activeTool = this.pencilTool && this.pencilTool.isEnabled() ? this.pencilTool :
        (this.annotationTool && this.annotationTool.isEnabled() ? this.annotationTool : null);

      // 如果没有活动工具或选中的形状，则不显示菜单
      if (!activeTool || !activeTool.getShape()) return;

      const rect = this.$refs.plot.getBoundingClientRect();
      this.contextMenu.x = event.clientX - rect.left;
      this.contextMenu.y = event.clientY - rect.top;
      this.contextMenu.visible = true;

      // 记录当前右键菜单使用的工具
      this._contextMenuTool = activeTool;

      event.stopPropagation();
    },

    /**
     * 隐藏右键菜单
     */
    hideContextMenu() {
      this.contextMenu.visible = false;
      this._contextMenuTool = null;
    },

    /**
     * 检查菜单项是否可用
     */
    isMenuItemEnabled(action) {
      // 获取当前活动的工具
      const tool = this._contextMenuTool;

      if (!tool) return false;

      switch (action) {
        case 'undo':
          // 使用工具的getHistory方法获取历史记录对象
          return tool.getHistory && tool.getHistory() && tool.getHistory().canUndo();
        case 'redo':
          // 使用工具的getHistory方法获取历史记录对象
          return tool.getHistory && tool.getHistory() && tool.getHistory().canRedo();
        case 'copy':
        case 'delete':
          return tool.getShape() != null;
        case 'paste':
          return this.clipboard !== null;
        default:
          return true;
      }
    },

    /**
     * 处理菜单动作
     */
    handleMenuAction(action) {
      if (!this.isMenuItemEnabled(action)) return;

      const tool = this._contextMenuTool;

      if (!tool) {
        this.hideContextMenu();
        return;
      }

      switch (action) {
        case 'undo':
          // 使用工具的undo方法或history对象的undo方法
          if (tool.undo) {
            tool.undo();
          } else if (tool.getHistory && tool.getHistory()) {
            tool.getHistory().undo();
          }
          break;
        case 'redo':
          // 使用工具的redo方法或history对象的redo方法
          if (tool.redo) {
            tool.redo();
          } else if (tool.getHistory && tool.getHistory()) {
            tool.getHistory().redo();
          }
          break;
        case 'copy':
          this.copyShape(tool);
          break;
        case 'paste':
          this.pasteShape();
          break;
        case 'delete':
          this.deleteShape(tool);
          break;
      }

      this.hideContextMenu();
      this.requestRepaint();
    },

    copyShape(tool) {
      const shape = tool.getShape();
      if (!shape) return;

      // 存储形状的克隆
      this.clipboard = Array.isArray(shape) ?
        shape.map(node => node.clone()) :
        [shape.clone()];
    },

    pasteShape() {
      if (!this.clipboard || this.clipboard.length === 0) return;

      // 创建偏移量，以便粘贴的形状不会完全覆盖原始形状
      const offset = 20;

      // 克隆并移动复制的形状
      this.clipboard.forEach(node => {
        const clone = node.clone();

        // 移动克隆的形状
        if (clone.translate) {
          clone.translate(offset, offset);
        }

        // 添加到注释层
        this.annotations.addChild(clone);
      });

      this.requestRepaint();
    },

    deleteShape(tool) {
      const shape = tool.getShape();
      if (!shape) return;

      // 如果是数组，删除所有选中的形状
      if (Array.isArray(shape)) {
        shape.forEach(node => {
          const index = this.annotations.indexOfChild(node);
          if (index >= 0) {
            this.annotations.removeChild(node);
          }
        });
      } else {
        // 删除单个形状
        const index = this.annotations.indexOfChild(shape);
        if (index >= 0) {
          this.annotations.removeChild(shape);
        }
      }

      // 清除工具当前编辑的节点
      tool.editNode(null);

      this.requestRepaint();
    },

    handleKeyDown(event) {
      // 检查是否有活动的工具
      const activeTool = this.pencilTool && this.pencilTool.isEnabled() ? this.pencilTool :
        (this.annotationTool && this.annotationTool.isEnabled() ? this.annotationTool : null);

      if (!activeTool) return;

      // 获取历史记录对象
      const history = activeTool.getHistory && activeTool.getHistory();

      // Ctrl+Z: 撤销
      if (event.ctrlKey && event.key === 'z') {
        if (activeTool.undo) {
          activeTool.undo();
          this.requestRepaint();
          event.preventDefault();
        } else if (history && history.canUndo && history.canUndo()) {
          history.undo();
          this.requestRepaint();
          event.preventDefault();
        }
      }

      // Ctrl+Y: 重做
      else if (event.ctrlKey && event.key === 'y') {
        if (activeTool.redo) {
          activeTool.redo();
          this.requestRepaint();
          event.preventDefault();
        } else if (history && history.canRedo && history.canRedo()) {
          history.redo();
          this.requestRepaint();
          event.preventDefault();
        }
      }

      // Delete: 删除
      else if (event.key === 'Delete') {
        if (activeTool.getShape()) {
          this.deleteShape(activeTool);
          event.preventDefault();
        }
      }
    },

    // 添加一个新方法，用于切换形状的编辑状态
    toggleShapeEditMode(shape) {
      if (!shape) return;

      // 获取活动工具
      const activeTool = this.pencilTool && this.pencilTool.isEnabled() ? this.pencilTool :
        (this.annotationTool && this.annotationTool.isEnabled() ? this.annotationTool : null);

      if (!activeTool) return;

      // 如果当前不是编辑模式，则切换到编辑模式
      if (activeTool.getMode() !== PaintMode.Edit) {
        activeTool.setMode(PaintMode.Edit);
      }

      // 如果当前编辑的不是这个形状，则开始编辑这个形状
      if (activeTool.getShape() !== shape) {
        activeTool.setEditMode(EditMode.EditNode);
        activeTool.editNode(shape);
        this.selectedShape = shape;
      }

      this.requestRepaint();
    },

    getElementIcon(mdiIcon) {
      // 将Vuetify的mdi图标转换为Element UI图标
      const iconMap = {
        'mdi-undo': 'el-icon-refresh-left',
        'mdi-redo': 'el-icon-refresh-right',
        'mdi-content-copy': 'el-icon-document-copy',
        'mdi-content-paste': 'el-icon-document-add',
        'mdi-delete': 'el-icon-delete'
      };

      return iconMap[mdiIcon] || 'el-icon-warning';
    },

    // 添加鼠标悬停相关事件
    initCursorTools() {
      // 实现鼠标悬停相关事件的初始化逻辑
    },

    // 添加鼠标移动处理方法
    handleMouseMove(event) {
      if (!this.widget || !this.isHovering) return;

      const rect = this.$refs.plot.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      // 获取当前pipeline
      const pipeline = this.pipeline;
      if (!pipeline) return;

      try {
        // 获取可见区域的模型限制
        const modelLimits = this.widget.getVisibleSeismicModelLimits();
        if (!modelLimits) return;

        // 计算相对坐标
        const width = rect.width;
        const height = rect.height;
        const relativeX = x / width;
        const relativeY = y / height;

        // 计算实际坐标
        const traceX = modelLimits.getLeft() + (modelLimits.getWidth() * relativeX);
        const depthY = modelLimits.getTop() + (modelLimits.getHeight() * relativeY);

        // 使用SnapPicker获取采样值
        const strategy = new NoSnapPicking();
        SnapPicker.pickSample(traceX, depthY, strategy, pipeline, this.widget, (sample) => {
          if (sample) {
            this.cursorInfo = {
              depth: sample.location.y,
              trace: sample.traceNumber,
              value: sample.sampleValue
            };
          } else {
            this.cursorInfo = {
              depth: depthY,
              trace: traceX,
              value: null
            };
          }
        });
      } catch (error) {
        console.error('获取坐标信息时出错:', error);
        this.cursorInfo = {
          depth: null,
          trace: null,
          value: null
        };
      }
    },

    // 添加保存标注数据的方法
    saveAnnotation(node) {
      if (!node) return;

      try {
        // 获取文本样式
        const textStyle = node.getTextStyle();
        let fontSize = 22; // 默认字体大小

        // 从字体字符串中提取字体大小
        if (textStyle && textStyle.getFont) {
          const fontString = textStyle.getFont();
          const fontSizeMatch = fontString.match(/(\d+)px/);
          if (fontSizeMatch) {
            fontSize = parseInt(fontSizeMatch[1], 10);
          }
        }

        const annotationData = {
          type: node.getType ? node.getType() : 'text',
          text: node.getText ? node.getText() : '',
          properties: node.getProperties(),
          position: {
            x: node.getProperties().ax,
            y: node.getProperties().ay
          },
          styles: {
            textStyle: {
              font: textStyle ? textStyle.getFont() : '',
              color: textStyle ? textStyle.getColor() : '#000000',
              size: fontSize,
              alignment: textStyle ? textStyle.getAlignment() : 'left',
              bold: textStyle ? Boolean(textStyle.getFont().includes('bold')) : false,
              italic: textStyle ? Boolean(textStyle.getFont().includes('italic')) : false
            },
            lineStyle: {
              color: node.getLineStyle ? node.getLineStyle().getColor() : '#000000',
              width: node.getLineStyle ? node.getLineStyle().getWidth() : 1,
              pattern: node.getLineStyle ? node.getLineStyle().getPattern() : []
            },
            fillStyle: {
              color: node.getFillStyle ? node.getFillStyle().getColor() : 'transparent',
              pattern: node.getFillStyle ? node.getFillStyle().getPattern() : 'Solid'
            }
          }
        };

        // 将标注数据添加到数组中
        this.savedAnnotations.push(annotationData);

        console.log('标注数据已保存:', annotationData);
      } catch (error) {
        console.error('保存标注数据时出错:', error);
        // 添加更详细的错误日志
        console.error('错误详情:', {
          hasNode: Boolean(node),
          hasTextStyle: Boolean(node && node.getTextStyle),
          hasGetProperties: Boolean(node && node.getProperties),
          nodeType: node ? (node.getType ? node.getType() : 'unknown') : 'null',
          error: error.message
        });
      }
    },

    // 添加恢复标注数据的方法
    restoreAnnotations() {
      if (!this.annotations || !this.widget || !this.savedAnnotations || this.savedAnnotations.length === 0) {
        console.log('无法恢复标注：缺少必要组件或数据');
        return;
      }

      try {
        this.savedAnnotations.forEach(data => {
          try {
            // 创建文本节点
            const textNode = new Text({
              text: data.text,
              x: data.properties.ax,
              y: data.properties.ay,
              width: data.properties.width,
              height: data.properties.height,
              sizemode: data.properties.sizemode || SizeMode.WrappedWidth,
              selectable: true,
              movable: true,
              editable: true
            });

            // 设置样式
            textNode.setProperties({
              'textstyle': new TextStyle({
                color: data.properties.textstyle.Lx,
                font: data.properties.textstyle.lH,
                alignment: data.properties.textstyle.Vf
              }),
              'linestyle': new LineStyle({
                color: data.properties.linestyle.Lx,
                width: data.properties.linestyle.fA,
                pattern: []
              }),
              'fillstyle': new FillStyle({
                color: data.properties.fillstyle.Lx
              })
            });

            // 添加到标注层
            this.annotations.addChild(textNode);

            console.log('成功创建标注:', {
              text: data.text,
              position: { x: data.properties.ax, y: data.properties.ay },
              size: { width: data.properties.width, height: data.properties.height }
            });
          } catch (error) {
            console.error('恢复单个标注时出错:', error);
          }
        });

        // 强制重绘
        if (this.widget && typeof this.widget.invalidate === 'function') {
          this.widget.invalidate();
        }

        console.log('所有标注数据已恢复');
      } catch (error) {
        console.error('恢复标注数据时出错:', error);
      }
    },

    // 添加在指定位置创建文本的方法
    createTextAtPosition() {
      if (!this.widget || !this.annotations) {
        console.warn('Widget or annotations layer not ready');
        return;
      }

      try {
        // 创建文本节点
        const textNode = new Text({
          text: "地震",
          x: 826.370447661679,  // 指定的x坐标
          y: 2.1615720524017465, // 指定的y坐标
          width: 100,
          height: 30,
          sizemode: SizeMode.WrappedWidth,
          selectable: true,
          movable: true,
          editable: true
        });

        // 设置文本样式
        textNode.setProperties({
          'textstyle': new TextStyle({
            color: 'rgba(200, 109, 109, 1)',
            font: 'bold 22px Arial Black',
            alignment: 'left'
          }),
          'linestyle': new LineStyle({
            color: 'rgba(100, 158, 227, 1)',
            width: 3,
            pattern: []
          }),
          'fillstyle': new FillStyle({
            color: 'rgba(30, 70, 102, 1)'
          })
        });

        // 添加到标注层
        this.annotations.addChild(textNode);

        // 强制重绘
        this.widget.invalidate();

        console.log('文本标注已创建在指定位置');
      } catch (error) {
        console.error('创建文本标注时出错:', error);
      }
    },
  },

  beforeDestroy() {
    // 清理资源
    if (this.plots) {
      this.plots.dispose();
    }
    if (this.annotationTool) {
      this.annotationTool.dispose();
    }
    if (this.pencilTool) {
      this.pencilTool.dispose();
    }

    if (this.$refs.plot) {
      this.$refs.plot.removeEventListener('contextmenu', this.showContextMenu);
      document.removeEventListener('click', this.hideContextMenu);
      // 移除键盘事件监听
      window.removeEventListener('keydown', this.handleKeyDown);

      // 移除鼠标悬停相关事件
      this.$refs.plot.removeEventListener('mouseenter', () => {
        this.isHovering = true;
      });
      this.$refs.plot.removeEventListener('mouseleave', () => {
        this.isHovering = false;
      });
      this.$refs.plot.removeEventListener('mousemove', this.handleMouseMove);
    }
  }
}
</script>

<style>
/* 修改现有样式 */
.app-container {
  width: 100%;
  height: calc(100vh - 90px);
  overflow: hidden;
}

.seismic-container {
  display: flex;
  width: 100%;
  height: calc(100vh - 110px);
  gap: 20px;
  padding: 20px;
}

.seismic-block {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
  height: 100%;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.containerBlock {
  height: 100%;
  display: flex;
  flex-direction: column;
}

#canvas {
  width: 100% !important;
  height: calc(100% - 80px) !important; /* 减去toolbar的高度 */
  margin-top: 10px;
}

/* 默认样式：单屏幕时显示两个地震图 */
.seismic-block {
  flex: 1;
  max-width: calc(50% - 10px); /* 确保每个块占据一半宽度减去间距 */
}

/* 媒体查询：处理双屏/扩展屏显示 */
@media screen and (min-width: 3000px) { /* 双屏/扩展屏的宽度通常大于3000px */
  .seismic-container {
    justify-content: space-between;
    width: 200vw; /* 扩展到两个屏幕的宽度 */
    padding: 20px 40px; /* 增加左右padding */
  }

  .seismic-block {
    max-width: calc(50vw - 60px); /* 每个块占据一个屏幕的宽度，减去padding和间距 */
    flex: 0 0 auto; /* 防止伸缩 */
  }

  .seismic-block:nth-child(2) {
    display: block; /* 显示第二个地震图 */
  }
}

.toolbar {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-grow: 1;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: auto;
}

/* 统一按钮样式 */
.toolbar .el-button {
  width: 40px;
  height: 40px;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0;
}

.toolbar .el-button [class^="el-icon-"] {
  font-size: 16px;
  margin: 0;
}

.toolbar .el-button:not(.el-button--text) {
  border: 1px solid #ddd;
  background-color: #fff;
}

.toolbar .el-button-group .el-button {
  margin-right: -1px;
}

.toolbar .el-button-group .el-button:first-child {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.toolbar .el-button-group .el-button:last-child {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-right: 0;
}

.toolbar .el-button-group .el-button:not(:first-child):not(:last-child) {
  border-radius: 0;
}

.toolbar .el-button:hover {
  background-color: #e6e6e6;
}

.toolbar .el-button.active {
  background-color: #e6e6e6;
  border-color: #adadad;
  color: #409EFF;
}

/* 鼠标悬停信息面板样式 */
.cursor-info-panel {
  position: absolute;
  bottom: 40px;
  right: 20px;
  background-color: transparent;
  z-index: 100;
  display: flex;
  font-size: 13px;
  gap: 5px;
  pointer-events: none;
  /* 添加此属性使鼠标事件可以穿透面板 */
}

.info-pill {
  background-color: rgba(75, 75, 75, 0.8);
  color: white;
  border-radius: 4px;
  padding: 3px 8px;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  pointer-events: none;
  /* 添加此属性使鼠标事件可以穿透信息块 */
}

/* 鼠标悬停覆盖层样式 */
.hover-layer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 5;
  cursor: crosshair;
  background-color: transparent;
  pointer-events: none;
  /* 关键：允许事件穿透，保持悬浮功能 */
}

/* 样式面板相关样式 */
.style-panel {
  position: fixed;
  right: -300px;
  top: 0;
  width: 300px;
  height: 100vh;
  background-color: #fff;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  z-index: 1000;
  overflow-y: auto;
}

.style-panel-visible {
  right: 0;
}

.style-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ddd;
}

.style-panel-header h3 {
  margin: 0;
  font-size: 16px;
}

.style-content {
  padding: 15px;
}

.style-section-title {
  font-weight: bold;
  margin: 10px 0;
  color: #333;
}

.style-item {
  margin-bottom: 15px;
}

.style-label {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.style-divider {
  height: 1px;
  background-color: #eee;
  margin: 15px 0;
}

.text-style-buttons {
  display: flex;
  gap: 5px;
}

.pattern-preview-fill {
  width: 100%;
  height: 24px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 调整滑块和输入框的样式 */
.el-slider {
  margin-top: 8px;
}

.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-color-picker {
  width: 100%;
}

/* 添加错误和加载状态样式 */
.error-message {
  color: red;
  padding: 10px;
  margin: 10px;
  background-color: #fff3f3;
  border: 1px solid #ffa7a7;
  border-radius: 4px;
}

.loading-message {
  text-align: center;
  padding: 20px;
  color: #666;
}

.color-maps {
  margin-right: 10px;
}

.color-maps .el-select {
  width: 140px;
}

.color-maps-label {
  margin-right: 8px;
  font-size: 14px;
  color: #666;
}

.toolbar-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.is-active {
  background-color: #e6e6e6;
  border-color: #adadad;
}

.context-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1001;
  padding: 5px 0;
}

.context-menu-separator {
  height: 1px;
  background-color: #eee;
  margin: 5px 0;
}

.context-menu-item {
  padding: 8px 16px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.context-menu-item:hover {
  background-color: #f5f5f5;
}

.context-menu-item.disabled {
  color: #999;
  cursor: not-allowed;
}

.context-menu-item.disabled:hover {
  background-color: transparent;
}

.shortcut {
  font-size: 12px;
  color: #999;
  margin-left: 16px;
}

.pattern-preview-line {
  width: 100%;
  height: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: flex-start;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;
    margin: 5px 0;
  }

  .toolbar-right {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .color-maps {
    margin-right: 0;
  }
}

.color-map-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-map-preview {
  width: 40px;
  height: 20px;
  border: 1px solid #ddd;
  border-radius: 2px;
}

.WhiteBlack {
  background: linear-gradient(to right, white, black);
}

.CustomGrayScale {
  background: linear-gradient(to right,
      rgb(255, 255, 255) 50%,
      /* -4000到181保持白色 */
      rgb(253, 253, 253) 55%,
      /* 181开始的颜色 */
      rgb(240, 240, 240) 65%,
      /* 到566的颜色 */
      rgb(180, 180, 180) 80%,
      /* 566后的过渡色 */
      rgb(6, 6, 6) 100%
      /* 最终颜色 */
    );
}

.CustomRedScale {
  background: linear-gradient(to right, #F62814, #DD8B66, #D7C692, #FBFAFF, #6E6E8A, #323136);
}
</style>
