<template>
  <div class="ysgc-container" :class="{ compact }">
    <!-- <el-form :inline="true" size="small" class="toolbar" label-width="80px">
          <el-form-item label="项目名称">
              <el-input v-model="filters.projectName" placeholder="请输入" class="input" />
          </el-form-item>
          <el-form-item label="区块">
              <el-input v-model="filters.block" placeholder="请输入" class="input" />
          </el-form-item>
      </el-form> -->
    <div ref="chartRef" class="chart"
      :style="compact ? { width: (width || 260) + 'px', height: (height || 160) + 'px' } : {}"></div>
  </div>

</template>

<script>
import * as echarts from 'echarts'
import { toDht } from '@/api/ysqqXmxx/ysqqXmxx'

export default {
  name: 'YsgcIndex',
  props: {
    compact: { type: Boolean, default: false },
    width: { type: Number, default: 0 },
    height: { type: Number, default: 0 },
    idOverride: { type: [String, Number], default: null },
    // 外部传入需要高亮的 SEGY 线下标（来自 index2.vue 的当前显示/选中）
    activeSegyIndex: { type: Number, default: null },
    // 支持多条同时高亮
    activeSegyIndices: { type: Array, default: () => [] },
    // 点击线后跳转路由；传字符串为 path，或路由对象；不传则仅抛事件
    navigateTo: { type: [String, Object], default: null }
  },
  data() {
    return {
      chart: null,
      resizeObserver: null,
      loadingDht: false,
      dhtResult: null,
      segyLines: [],
      // 与 segyLines 同步的元信息（如 id、名称）
      segyMetas: [],
      filters: {
        projectName: '',
        block: ''
      },
      // 示例数据，后续可由接口/路由参数加载
      xMin: null,
      xMax: null,
      yMin: null,
      yMax: null,
      verticalLineX: null,
      points: [],
      // 防抖定时器，避免频繁渲染
      renderTimer: null,
      // 标记是否正在渲染，避免重复渲染
      isRendering: false
    }
  },
  mounted() {
    // 仅使用延迟初始化，确保容器有尺寸后再 init
    this.deferInit()
    window.addEventListener('resize', this.resizeChart)
    // 若路由中带有 id，则尝试调用接口
    this.loadDht()
    // 兜底：在下一帧强制渲染一次（compact 时保证首屏显示）
    this.$nextTick(() => setTimeout(() => {
      if (this.chart) {
        this.renderChart()
        this.chart.resize()
      }
    }, 50))

    // 对于缩略图模式，确保即使在隐藏状态下也能渲染
    if (this.compact) {
      // 强制初始化并渲染
      this.$nextTick(() => {
        this.initChart()
        this.renderChart()
      })
    }
  },
  created() {
    // 尽早触发接口调用，进入页面即发起请求
    this.loadDht()
  },
  activated() {
    // 当页面被 keep-alive 缓存后再次进入时，确保尺寸和图表刷新
    this.deferInit()
    this.resizeChart()
    // 强制重新加载数据，确保路由参数变化时数据能更新
    this.loadDht(true)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
    // 清除防抖定时器
    if (this.renderTimer) {
      clearTimeout(this.renderTimer)
      this.renderTimer = null
    }
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    if (this.resizeObserver) {
      try { this.resizeObserver.disconnect() } catch (e) { }
      this.resizeObserver = null
    }
  },
  watch: {
    // 监听idOverride变化，当路由参数变化时重新加载数据
    idOverride(newId, oldId) {
      // 严格验证：只有当 newId 有有效值且与旧值不同时才触发
      const newIdValid = newId != null && newId !== 'null' && newId !== 'undefined' && String(newId).trim() !== ''
      if (newId !== oldId && newIdValid) {
        this.dhtResult = null; // 清除缓存
        this.loadDht(true);
      }
    },
    // 外部高亮线变化，刷新图表
    activeSegyIndex(newVal, oldVal) {
      console.log('[ysgc] activeSegyIndex watch 触发:', { oldVal, newVal, equal: newVal === oldVal })
      // 只有当值真正改变时才触发渲染，避免重复触发
      if (newVal === oldVal) return
      this._requestRender()
    },
    activeSegyIndices(newVal, oldVal) {
      // 只有当值真正改变时才触发渲染，避免重复触发
      if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return
      this._requestRender()
    }
  },
  methods: {
    // 等待容器有有效尺寸再初始化，避免 echarts 容器宽高为 0 报错
    deferInit() {
      const tryInit = () => {
        const el = this.$refs.chartRef
        if (!el) return
        // 缩略图模式：尺寸已知，直接初始化
        if (this.compact) {
          this.initChart()
          return
        }
        let w = el.clientWidth
        let h = el.clientHeight
        //console.log('[ysgc] before size', w, h)
        if (w === 0) {
          el.style.width = '800px'
          w = el.clientWidth
        }
        if (h === 0) {
          // 若元素当前不可见（display: none）或父容器高度为 0，clientHeight 依然为 0
          // 使用 ResizeObserver 监听直到有高度后再初始化
          if (!this.resizeObserver) {
            this.resizeObserver = new ResizeObserver(entries => {
              for (const entry of entries) {
                const cr = entry.contentRect
                if (cr.height > 0 && cr.width > 0) {
                  //console.log('[ysgc] ResizeObserver visible', cr.width, cr.height)
                  if (this.resizeObserver) {
                    try { this.resizeObserver.disconnect() } catch (e) { }
                    this.resizeObserver = null
                  }
                  this.initChart()
                }
              }
            })
            this.resizeObserver.observe(el)
          }
        }
        //console.log('[ysgc] after size', w, h)
        // 即使高度为 0，也先用回退尺寸初始化，待可见后再 resize
        this.initChart()
        // 兜底：稍后再尝试一次 resize
        setTimeout(() => this.resizeChart(), 150)
      }
      this.$nextTick(tryInit)
    },
    resizeChart() {
      if (this.chart && !this.isRendering) {
        // resize 时不要触发渲染，避免循环
        this.chart.resize()
      }
    },
    initChart() {
      const el = this.$refs.chartRef
      if (!el) return
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      // 重置事件绑定标记，允许重新绑定事件
      this._eventsBound = false
      // 当容器高度为 0 时，先用显式宽高初始化，等可见后再 resize
      const initWidth = this.compact ? (this.width || 260) : (el.clientWidth || 800)
      const initHeight = this.compact ? (this.height || 160) : (el.clientHeight || 600)
      this.chart = echarts.init(el, null, { width: initWidth, height: initHeight })

      // 初始渲染
      this.renderChart()
      this.resizeChart()
      this.bindChartEvents()

      // 对于缩略图模式，确保渲染成功
      if (this.compact) {
        //console.log('[ysgc] 缩略图初始化完成', initWidth, initHeight)
      }
    },
    // 数据变化后自动刷新（确保缩略图及时绘制）
    _requestRender() {
      if (!this.chart) return
      // 如果正在渲染，取消之前的定时器
      if (this.renderTimer) {
        clearTimeout(this.renderTimer)
        this.renderTimer = null
      }
      // 如果正在渲染中，直接返回，避免重复渲染
      if (this.isRendering) return
      
      // 使用防抖机制，避免频繁触发
      this.renderTimer = setTimeout(() => {
        this.renderTimer = null
        if (!this.chart) return
        this.isRendering = true
        this._internalRender = true
        this.$nextTick(() => {
          try {
            this.renderChart()
            // resize 可能会触发事件，延迟执行避免循环
            setTimeout(() => {
              if (this.chart && !this.isRendering) {
                this.chart.resize()
              }
            }, 10)
          } finally {
            this.isRendering = false
            this._internalRender = false
          }
        })
      }, 50)
    },
    // 调用地层/断层图接口（示例），优先从路由参数获取 id
    loadDht(forceReload = false) {
      if (this.loadingDht || (this.dhtResult && !forceReload)) return
      try {
        const route = this.$route || {}
        const params = route.params || {}
        const query = route.query || {}
        const id = this.idOverride != null ? this.idOverride : (params.zbid || query.zbid || params.id || query.id)
        // 严格验证 id：排除 null、undefined、空字符串、字符串 "null"、"undefined"
        if (!id || id === 'null' || id === 'undefined' || String(id).trim() === '') {
          return
        }
        this.loadingDht = true
        toDht(id)
          .then(res => {
            // 根据后端返回结构做适配：优先取 data 字段
            this.dhtResult = (res && (res.data !== undefined ? res.data : res)) || null
            this.applyDhtResult()
            if (this.chart) this._requestRender()
          })
          .catch(err => {
            // 保留错误日志，避免打断现有流程
            //console.error('[ysgc] toDht error:', err)
          })
          .finally(() => {
            this.loadingDht = false
          })
      } catch (e) {
        //console.error('[ysgc] loadDht failed:', e)
      }
    },
    // 将接口返回的数据应用到图表状态
    applyDhtResult() {
      const data = this.dhtResult || {}
      // 边界
      this.xMin = data.xmin != null ? Number(data.xmin) : this.xMin
      this.xMax = data.xmax != null ? Number(data.xmax) : this.xMax
      this.yMin = data.ymin != null ? Number(data.ymin) : this.yMin
      this.yMax = data.ymax != null ? Number(data.ymax) : this.yMax
      // 井点
      const list = Array.isArray(data.ysqqXmxxJxxList) ? data.ysqqXmxxJxxList : []
      if (list.length) {
        this.points = list
          .filter(it => it && it.x != null && it.y != null)
          .map(it => ({ name: String(it.jh || ''), x: Number(it.x), y: Number(it.y) }))
      }
      // 线（SEGY）
      const segys = Array.isArray(data.ysqqXmxxSegy) ? data.ysqqXmxxSegy : []
      //console.log(segys, 'segys');
      const linesWithMeta = segys.map((seg, idx) => {
        try {
          const arr = typeof seg.x === 'string' ? JSON.parse(seg.x) : (Array.isArray(seg.x) ? seg.x : [])
          // 若存在有效的 sxh，则按 sxh 升序连线；否则按原始顺序
          const enriched = arr
            .filter(p => p && p.x != null && p.y != null)
            .map(p => ({ sxh: Number(p.sxh), x: Number(p.x), y: Number(p.y) }))
            .filter(p => Number.isFinite(p.x) && Number.isFinite(p.y))
          const hasSxh = enriched.every(p => Number.isFinite(p.sxh))
          const ordered = hasSxh ? enriched.sort((a, b) => a.sxh - b.sxh) : enriched
          const pairs = ordered.map(p => [p.x, p.y])
          try {
            const cloneForLog = pairs.map(it => [it[0], it[1]])
            //console.log('[ysgc] segy parsed', { index: idx, id: seg && seg.id, points: cloneForLog.length, sample: cloneForLog.slice(0, 5) })
            //console.log('[ysgc] segy full points', { index: idx, id: seg && seg.id, pointsArray: cloneForLog })
          } catch (e) { }
          return {
            line: pairs,
            meta: { id: seg && seg.id, name: seg && (seg.name || seg.segyName || seg.jbsegyName || seg.xbsegyName), originalIndex: idx }
          }
        } catch (e) {
          //console.error('[ysgc] segy parse error', { index: idx, id: seg && seg.id, err: e })
          return { line: [], meta: { id: seg && seg.id, originalIndex: idx } }
        }
      }).filter(item => item.line.length > 0)

      this.segyLines = linesWithMeta.map(item => item.line)
      // 保存元信息（保持与 lines 的顺序一致，只包含有效线条）
      this.segyMetas = linesWithMeta.map(item => item.meta)
      try {
        //console.log('[ysgc] segyLines summary', { lines: this.segyLines.length, lengths: this.segyLines.map(l => l.length) })
        //console.log('[ysgc] segyMetas summary', { metas: this.segyMetas.length, ids: this.segyMetas.map(m => m.id) })
      } catch (e) { }
    },
    // 对外方法：设置/清除高亮（便于通过 ref 调用）
    setActiveSegyIndex(index) {
      this.$emit('update:activeSegyIndex', index)
      // 注意：不要直接修改 props，Vue 不允许直接修改 props
      // 如果父组件使用了 v-model，会自动更新；否则通过事件传递
      this._requestRender()
    },
    clearActiveSegy() {
      this.setActiveSegyIndex(null)
    },
    // 生成图表配置
    buildOption() {
      // 若未提供边界，则根据数据自动估算
      const allXs = []
      const allYs = []
      for (const p of this.points) { allXs.push(p.x); allYs.push(p.y) }
      for (const line of this.segyLines) {
        for (const [lx, ly] of line) { allXs.push(lx); allYs.push(ly) }
      }
      if (allXs.length && (this.xMin == null || this.xMax == null)) {
        const padX = Math.max(1, Math.round((Math.max(...allXs) - Math.min(...allXs)) * 0.02))
        this.xMin = this.xMin != null ? this.xMin : Math.min(...allXs) - padX
        this.xMax = this.xMax != null ? this.xMax : Math.max(...allXs) + padX
      }
      if (allYs.length && (this.yMin == null || this.yMax == null)) {
        const padY = Math.max(1, Math.round((Math.max(...allYs) - Math.min(...allYs)) * 0.02))
        this.yMin = this.yMin != null ? this.yMin : Math.min(...allYs) - padY
        this.yMax = this.yMax != null ? this.yMax : Math.max(...allYs) + padY
      }

      const series = []
      // 井点散点图
      if (this.points && this.points.length) {
        series.push({
          type: 'scatter',
          symbolSize: this.compact ? 4 : 6,
          data: this.points.map(p => [p.x, p.y, p.name]),
          itemStyle: { color: '#2d72ff', borderColor: '#2d72ff' },
          label: this.compact ? { show: false } : { show: true, position: 'top', color: '#333', formatter: params => params.data[2] }
        })
      }
      // 叠加 SEGY 线
      // 统一计算选中集合（基于原始索引）
      const activeOriginalIndices = new Set(
        Array.isArray(this.activeSegyIndices) && this.activeSegyIndices.length
          ? this.activeSegyIndices
          : (this.activeSegyIndex != null ? [this.activeSegyIndex] : [])
      )
      // console.log('[ysgc] buildOption 高亮调试:', {
      //   activeSegyIndex: this.activeSegyIndex,
      //   activeSegyIndices: this.activeSegyIndices,
      //   activeOriginalIndices: Array.from(activeOriginalIndices),
      //   segyLinesLength: this.segyLines.length,
      //   segyMetasLength: this.segyMetas ? this.segyMetas.length : 0,
      //   segyMetas: this.segyMetas
      // })
      for (let li = 0; li < this.segyLines.length; li++) {
        const line = this.segyLines[li]
        // 获取当前线条的元信息，包括原始索引
        const meta = this.segyMetas && this.segyMetas[li] ? this.segyMetas[li] : {}
        // 使用原始索引来判断是否高亮
        const originalIdx = meta.originalIndex != null ? meta.originalIndex : li
        const isLineActive = activeOriginalIndices.has(originalIdx)
        // //console.log(`[ysgc] 线条 ${li}:`, {
        //   originalIdx,
        //   isLineActive,
        //   meta,
        //   activeOriginalIndices: Array.from(activeOriginalIndices),
        //   hasOriginalIdx: activeOriginalIndices.has(originalIdx)
        // })
        
        series.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: line,
          showSymbol: false,
          silent: false,
          connectNulls: true,
          smooth: false,
          emphasis: { scale: false },
          encode: { x: 0, y: 1 },
          z: 10,
          zlevel: 1,
          lineStyle: {
            color: isLineActive ? '#FF6B6B' : '#409EFF',
            width: isLineActive ? 4 : 2,
            opacity: 1
          },
          // 提升可点击体验
          cursor: 'pointer',
          emphasis: { lineStyle: { width: 6 } },
          tooltip: {
            show: true,
            formatter: (p) => {
              const v = p && p.data
              return v ? `X：${v[0]}<br/>Y：${v[1]}` : ''
            }
          }
        })
      }
      // 垂直参考线（可选）
      if (this.verticalLineX != null && this.yMin != null && this.yMax != null) {
        series.push({
          type: 'line',
          data: [[this.verticalLineX, this.yMin], [this.verticalLineX, this.yMax]],
          showSymbol: false,
          lineStyle: { color: '#222', width: 2 },
          tooltip: { show: false }
        })
      }

      return {
        backgroundColor: this.compact ? '#f2f2f2' : '#ffffff',
        grid: this.compact ? { top: 6, left: 6, right: 6, bottom: 6, containLabel: false } : { top: 40, left: 50, right: 40, bottom: 50, containLabel: true },
        xAxis: this.compact ? { 
          type: 'value', 
          min: this.xMin, 
          max: this.xMax, 
          scale: true, 
          axisLine: { show: false }, 
          axisTick: { show: false }, 
          axisLabel: { show: false }, 
          splitLine: { 
            show: true, 
            lineStyle: { 
              color: '#e0e0e0', 
              opacity: 0.8,
              width: 1
            } 
          } 
        } : { type: 'value', min: this.xMin, max: this.xMax, scale: false, axisLine: { show: true }, axisTick: { show: true }, axisLabel: { color: '#666' }, splitLine: { show: true, lineStyle: { color: '#9bb3e7', opacity: 0.6 } } },
        yAxis: this.compact ? { 
          type: 'value', 
          min: this.yMin, 
          max: this.yMax, 
          scale: true, 
          axisLine: { show: false }, 
          axisTick: { show: false }, 
          axisLabel: { show: false }, 
          splitLine: { 
            show: true, 
            lineStyle: { 
              color: '#e0e0e0', 
              opacity: 0.8,
              width: 1
            } 
          } 
        } : { type: 'value', min: this.yMin, max: this.yMax, scale: false, axisLine: { show: true }, axisTick: { show: true }, axisLabel: { color: '#666' }, splitLine: { show: true, lineStyle: { color: '#9bb3e7', opacity: 0.6 } } },
        series,
        // 提示框
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(33, 41, 54, 0.95)',
          borderColor: '#1f6feb',
          borderWidth: 0,
          padding: [8, 10],
          textStyle: { color: '#fff', fontSize: this.compact ? 10 : 12, fontWeight: 500 },
          extraCssText: 'box-shadow: 0 6px 16px rgba(0,0,0,.20); border-radius: 8px;',
          formatter: params => {
            const formatNum = n => {
              if (n == null || isNaN(n)) return '-'
              return Number(n).toLocaleString('zh-CN')
            }
            if (params && params.seriesType === 'scatter') {
              const d = params.data || []
              const name = d[2] || ''
              const x = d[0]
              const y = d[1]
              return (name ? name + '<br/>' : '') + `X：${formatNum(x)}<br/>Y：${formatNum(y)}`
            }
            if (params && params.seriesType === 'line') {
              const d = params.data || []
              const x = d[0]
              const y = d[1]
              return `X：${formatNum(x)}<br/>Y：${formatNum(y)}`
            }
            const v = Array.isArray(params && params.value) ? params.value[1] : (params && params.value)
            return v != null ? formatNum(v) : ''
          }
        }
      }
    },
    // 渲染或更新图表
    renderChart() {
      if (!this.chart) return
      try {
        const option = this.buildOption()
        this.chart.setOption(option, true)
        // 确保事件绑定有效（只在必要时绑定）
        this.bindChartEvents()
      } catch (e) {
        // 渲染失败时重置状态
        this.isRendering = false
        this._internalRender = false
        //console.error('[ysgc] renderChart error:', e)
      }
    },
    // 绑定点击/双击事件，把被点击的绿色线条映射为 segy 下标并上报
    bindChartEvents() {
      if (!this.chart) return
      // 使用标记避免重复绑定
      if (this._eventsBound) return
      this._eventsBound = true
      
      // 解除旧绑定避免重复
      this.chart.off('click')
      this.chart.off('dblclick')
      if (this._zrClick) {
        try { this.chart.getZr().off('click', this._zrClick) } catch (e) {}
        this._zrClick = null
      }

      const getLineIndexBySeries = (seriesIndex) => {
        // 如果有井点散点，最前面占 1 个 series
        const hasPoints = Array.isArray(this.points) && this.points.length > 0
        const base = hasPoints ? 1 : 0
        // 现在每条 SEGY 线只对应一个 line series
        if (seriesIndex < base) return -1
        const offset = seriesIndex - base
        // console.log('[ysgc] getLineIndexBySeries 计算:', {
        //   seriesIndex,
        //   hasPoints,
        //   base,
        //   offset,
        //   segyLinesLength: this.segyLines.length
        // })
        if (offset < 0 || offset >= this.segyLines.length) return -1
        return offset
      }

      const emitPick = (params) => {
        //console.log('[ysgc] emitPick 被调用:', params)
        if (!params) {
          //console.log('[ysgc] emitPick: params 为空，返回')
          return
        }
        // 允许 componentType 不存在或为 'series'
        if (params.componentType && params.componentType !== 'series') {
          //console.log('[ysgc] emitPick: componentType 不匹配', params.componentType)
          return
        }
        if (params.seriesType !== 'line') {
          //console.log('[ysgc] emitPick: seriesType 不是 line', params.seriesType)
          return
        }
        const idx = getLineIndexBySeries(params.seriesIndex)
        //console.log('[ysgc] emitPick: 计算出的 idx', { seriesIndex: params.seriesIndex, idx, segyLinesLength: this.segyLines.length })
        if (idx >= 0 && idx < this.segyLines.length) {
          const meta = this.segyMetas && this.segyMetas[idx] ? this.segyMetas[idx] : {}
          const originalIdx = meta.originalIndex != null ? meta.originalIndex : idx
          const payload = { 
            index: idx, 
            originalIndex: originalIdx,
            id: meta.id, 
            meta 
          }
          // console.log('[ysgc] emitPick 发送事件:', {
          //   filteredIndex: idx,
          //   originalIndex: originalIdx,
          //   id: meta.id,
          //   meta,
          //   payload
          // })
          this.$emit('segyLinePick', payload)

          if (this.navigateTo) {
            try {
              const currentRoute = this.$route || {}
              const routeId = this.idOverride != null ? this.idOverride : (currentRoute.params && (currentRoute.params.zbid || currentRoute.params.id)) || (currentRoute.query && (currentRoute.query.zbid || currentRoute.query.id))
              const base = typeof this.navigateTo === 'string' ? { path: this.navigateTo } : { ...(this.navigateTo || {}) }
              const next = {
                ...base,
                query: {
                  ...(base.query || {}),
                  segyIndex: idx,
                  segyId: meta.id,
                  id: routeId
                }
              }
              
              // 延迟执行，确保事件先处理完；如果当前路由相同，使用 replace
              this.$nextTick(() => {
                try {
                  const currentPath = this.$route && this.$route.path
                  const isSamePath = currentPath === next.path || currentPath === base.path
                  if (isSamePath) {
                    this.$router && this.$router.replace(next)
                  } else {
                    this.$router && this.$router.push(next)
                  }
                } catch (err) {
                  //console.error('[ysgc] navigation error:', err)
                }
              })
            } catch (e) { 
              //console.error('[ysgc] navigation error:', e)
            }
          }
        }
      }

      this.chart.on('click', emitPick)
      this.chart.on('dblclick', emitPick)

      // ZRender 兜底命中：即使未命中 series，也能根据像素距离选线
      const zrClick = (e) => {
        if (!e) return
        if (!Array.isArray(this.segyLines) || this.segyLines.length === 0) return
        const pt = [e.offsetX, e.offsetY]
        const toPixel = (xy) => this.chart.convertToPixel({ xAxisIndex: 0, yAxisIndex: 0 }, xy)
        const distPointSeg = (p, a, b) => {
          const vx = b[0] - a[0], vy = b[1] - a[1]
          const wx = p[0] - a[0], wy = p[1] - a[1]
          const c1 = vx*wx + vy*wy
          if (c1 <= 0) return Math.hypot(p[0]-a[0], p[1]-a[1])
          const c2 = vx*vx + vy*vy
          if (c2 <= 0) return Math.hypot(p[0]-a[0], p[1]-a[1])
          const t = Math.min(1, Math.max(0, c1 / c2))
          const proj = [a[0] + t*vx, a[1] + t*vy]
          return Math.hypot(p[0]-proj[0], p[1]-proj[1])
        }
        let bestIdx = -1
        let bestDist = Infinity
        for (let li = 0; li < this.segyLines.length; li++) {
          const line = this.segyLines[li]
          for (let j = 1; j < line.length; j++) {
            const a = toPixel(line[j-1])
            const b = toPixel(line[j])
            const d = distPointSeg(pt, a, b)
            if (d < bestDist) { bestDist = d; bestIdx = li }
          }
        }
        const threshold = 8 // 像素阈值
        //console.log('[ysgc] zrClick 检测结果:', { bestIdx, bestDist, threshold, hasPoints: Array.isArray(this.points) && this.points.length > 0 })
        if (bestIdx >= 0 && bestDist <= threshold) {
          // bestIdx 是 segyLines 的索引（过滤后的索引）
          // 需要转换为 echarts series 的索引
          const hasPoints = Array.isArray(this.points) && this.points.length > 0
          const base = hasPoints ? 1 : 0
          const seriesIndex = base + bestIdx
          // 构造与 series click 相同的负载
          const fake = { seriesType: 'line', seriesIndex: seriesIndex }
          //console.log('[ysgc] zrClick 构造 fake params:', { bestIdx, seriesIndex, fake })
          emitPick(fake)
        }
      }
      this.chart.getZr().on('click', zrClick)
      this._zrClick = zrClick
    }
  }
}
</script>

<style lang="scss" scoped>
.ysgc-container {
  display: flex;
  flex-direction: column;
  height: 88vh;
  overflow: hidden;
  /* 避免出现滚动条 */
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 80px;
  padding: 10px 0 8px 10px;
}

.field {
  display: flex;
  align-items: center;
}

.label {
  font-size: 20px;
  font-weight: 600;
  margin-right: 16px;
}

.input {
  width: 180px;
}

.chart {
  flex: 1;
  min-height: 0;
  /* 让 flex 子项在容器内收缩，避免溢出 */
  width: 100%;
  margin: 0;
  /* 取消外边距，防止产生滚动条 */
  background: #fff;
  border: 1px solid #e0e0e0;
}
</style>