<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 }
  },
  data() {
    return {
      chart: null,
      resizeObserver: null,
      loadingDht: false,
      dhtResult: null,
      segyLines: [],
      filters: {
        projectName: '',
        block: ''
      },
      // 示例数据，后续可由接口/路由参数加载
      xMin: null,
      xMax: null,
      yMin: null,
      yMax: null,
      verticalLineX: null,
      points: []
    }
  },
  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.chart) {
      this.chart.dispose()
      this.chart = null
    }
    if (this.resizeObserver) {
      try { this.resizeObserver.disconnect() } catch (e) { }
      this.resizeObserver = null
    }
  },
  watch: {
    // 监听idOverride变化，当路由参数变化时重新加载数据
    idOverride(newId, oldId) {
      if (newId !== oldId && newId) {
        console.log('[ysgc] idOverride变化，重新加载数据:', newId);
        this.dhtResult = null; // 清除缓存
        this.loadDht(true);
      }
    }
  },
  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.chart.resize()
    },
    initChart() {
      const el = this.$refs.chartRef
      if (!el) return
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      // 当容器高度为 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
      this.$nextTick(() => {
        this.renderChart()
        this.chart.resize()

        // 确保缩略图正确显示
        if (this.compact) {
          console.log('[ysgc] 缩略图渲染完成')
        }
      })
    },
    // 调用地层/断层图接口（示例），优先从路由参数获取 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)
        if (!id) 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 lines = 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 pairs
        } catch (e) {
          console.error('[ysgc] segy parse error', { index: idx, id: seg && seg.id, err: e })
          return []
        }
      }).filter(line => line.length > 0)

      this.segyLines = lines
      try {
        console.log('[ysgc] segyLines summary', { lines: this.segyLines.length, lengths: this.segyLines.map(l => l.length) })
      } catch (e) { }
    },
    // 生成图表配置
    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 ? 8 : 12,
          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 线
      for (const line of this.segyLines) {
        series.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: line,
          showSymbol: false,
          connectNulls: true,
          smooth: false,
          emphasis: { scale: false },
          encode: { x: 0, y: 1 },
          lineStyle: { color: '#00aa66', width: 2 },
          tooltip: { show: false }
        })
      }
      // 垂直参考线（可选）
      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
      const option = this.buildOption()
      this.chart.setOption(option, true)
      // 确保事件绑定有效
      this.bindChartEvents()
    },
    // 绑定点击/双击事件，把被点击的绿色线条映射为 segy 下标并上报
    bindChartEvents() {
      if (!this.chart) return
      // 解除旧绑定避免重复
      this.chart.off('click')
      this.chart.off('dblclick')

      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
        if (offset < 0 || offset >= this.segyLines.length) return -1
        return offset
      }

      const emitPick = (params) => {
        if (!params || params.seriesType !== 'line') return
        const idx = getLineIndexBySeries(params.seriesIndex)
        if (idx >= 0 && idx < this.segyLines.length) {
          this.$emit('segyLinePick', { index: idx })
        }
      }

      this.chart.on('click', emitPick)
      this.chart.on('dblclick', emitPick)
    }
  }
}
</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>