<template>
  <BaseCard title="活牛/鲜肉价格趋势">
    <div class="chart-wrapper">
      <div ref="chartRef" class="chart"></div>
      <img
        ref="baseRef"
        class="chart-base"
        src="/images/底座.png"
        alt=""
      />
    </div>
  </BaseCard>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import BaseCard from './BaseCard.vue'
import { bindChartBaseSync, syncChartBaseToGrid } from '../utils/chartBaseLayout.js'

const chartRef = ref(null)
const baseRef = ref(null)
let chartInstance = null
let tipTimer = null
let unbindChartBaseSync = null

const CHART_GRID_BOTTOM = 30
const API_URL = '/api/dashboard/price-trend'

const chartData = ref({
  labels: [],
  liveCattlePrice: [],
  beefPrice: [],
  unit: '元/kg',
  liveUnit: '元/kg',
  beefUnit: '元/kg'
})

const toRawValue = (item) => {
  if (item === null || item === undefined || item === '') {
    return null
  }
  const num = Number(item)
  return Number.isFinite(num) ? num : null
}

const toChartValue = (item) => {
  const raw = toRawValue(item)
  return raw == null ? 0 : raw
}

const calcAxisMax = (rawValues) => {
  const numeric = rawValues.filter((item) => item != null && item > 0)
  const maxVal = numeric.length ? Math.max(...numeric) : 0
  if (maxVal === 0) {
    return 75
  }

  const step = 15
  const raw = maxVal * 1.15
  return Math.max(step * 3, Math.ceil(raw / step) * step)
}

const getDataIndicesWithValues = (rawLive, rawBeef) => {
  const indices = []
  const len = Math.max(rawLive.length, rawBeef.length)

  for (let i = 0; i < len; i += 1) {
    if (rawLive[i] != null || rawBeef[i] != null) {
      indices.push(i)
    }
  }

  return indices
}

const buildOption = () => {
  const labels = chartData.value.labels
  const rawLive = chartData.value.liveCattlePrice.map(toRawValue)
  const rawBeef = chartData.value.beefPrice.map(toRawValue)
  const liveSeries = rawLive.map(toChartValue)
  const beefSeries = rawBeef.map(toChartValue)
  const liveUnit = chartData.value.liveUnit || chartData.value.unit || '元/kg'
  const beefUnit = chartData.value.beefUnit || chartData.value.unit || '元/kg'
  const yAxisUnit = liveUnit === beefUnit ? liveUnit : `${liveUnit} / ${beefUnit}`

  const axisMax = calcAxisMax([...rawLive, ...rawBeef])

  return {
    animation: true,
    animationDuration: 700,
    animationEasing: 'cubicOut',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(8, 28, 58, 0.92)',
      borderColor: 'rgba(45, 189, 255, 0.85)',
      borderWidth: 1,
      padding: [10, 14],
      textStyle: {
        color: '#d8ecff',
        fontSize: 12,
        fontFamily: 'Microsoft YaHei, sans-serif'
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.65)',
          type: 'dashed',
          width: 1
        }
      },
      formatter: (params) => {
        if (!params?.length) {
          return ''
        }

        const dataIndex = params[0].dataIndex
        let html = `<div style="font-weight:700;margin-bottom:6px;">${params[0].axisValue}</div>`

        params.forEach((item) => {
          const raw = item.seriesName === '活牛价格'
            ? rawLive[dataIndex]
            : rawBeef[dataIndex]

          if (raw == null) {
            return
          }

          const unitLabel = item.seriesName === '活牛价格' ? liveUnit : beefUnit
          html += `<div style="margin-top:4px;">
            <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${item.color};margin-right:6px;"></span>
            ${item.seriesName}: ${Number(raw).toFixed(1)}${unitLabel}
          </div>`
        })

        return html
      }
    },
    grid: {
      left: 52,
      right: 52,
      bottom: CHART_GRID_BOTTOM,
      top: 42,
      containLabel: false
    },
    xAxis: {
      type: 'category',
      data: labels,
      boundaryGap: false,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#8ecfff',
        fontSize: 12,
        fontFamily: 'Microsoft YaHei, sans-serif',
        margin: 8
      }
    },
    yAxis: {
      type: 'value',
      name: `价格(${yAxisUnit})`,
      min: 0,
      max: axisMax,
      interval: 15,
      splitLine: {
        lineStyle: {
          color: 'rgba(80, 160, 220, 0.22)',
          type: 'dashed'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#8ecfff',
        fontSize: 12,
        fontFamily: 'Microsoft YaHei, sans-serif'
      },
      nameTextStyle: {
        color: '#8ecfff',
        fontSize: 12,
        fontFamily: 'Microsoft YaHei, sans-serif',
        padding: [0, 0, 0, 0]
      }
    },
    series: [
      {
        name: '活牛价格',
        type: 'line',
        data: liveSeries,
        smooth: 0.35,
        connectNulls: true,
        symbol: 'circle',
        symbolSize: (value) => (value > 0 ? 7 : 0),
        showSymbol: true,
        lineStyle: {
          color: '#00d4ff',
          width: 3,
          shadowColor: 'rgba(0, 212, 255, 0.55)',
          shadowBlur: 10
        },
        itemStyle: {
          color: '#00d4ff',
          borderColor: '#ffffff',
          borderWidth: 2,
          shadowColor: 'rgba(0, 212, 255, 0.8)',
          shadowBlur: 8
        },
        areaStyle: {
          origin: 'start',
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 212, 255, 0.42)' },
            { offset: 1, color: 'rgba(0, 212, 255, 0.02)' }
          ])
        },
        emphasis: {
          scale: true,
          focus: 'series'
        },
        z: 3
      },
      {
        name: '牛肉价格',
        type: 'line',
        data: beefSeries,
        smooth: 0.35,
        connectNulls: true,
        symbol: 'circle',
        symbolSize: (value) => (value > 0 ? 7 : 0),
        showSymbol: true,
        lineStyle: {
          color: '#3dff7a',
          width: 3,
          shadowColor: 'rgba(61, 255, 122, 0.55)',
          shadowBlur: 10
        },
        itemStyle: {
          color: '#3dff7a',
          borderColor: '#ffffff',
          borderWidth: 2,
          shadowColor: 'rgba(61, 255, 122, 0.8)',
          shadowBlur: 8
        },
        areaStyle: {
          origin: 'start',
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(61, 255, 122, 0.38)' },
            { offset: 1, color: 'rgba(61, 255, 122, 0.02)' }
          ])
        },
        emphasis: {
          scale: true,
          focus: 'series'
        },
        z: 2
      }
    ]
  }
}

const startTipCarousel = () => {
  stopTipCarousel()

  const rawLive = chartData.value.liveCattlePrice.map(toRawValue)
  const rawBeef = chartData.value.beefPrice.map(toRawValue)
  const indices = getDataIndicesWithValues(rawLive, rawBeef)

  if (!chartInstance || !indices.length) {
    return
  }

  let currentPos = 0
  tipTimer = setInterval(() => {
    chartInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: indices[currentPos]
    })
    currentPos = (currentPos + 1) % indices.length
  }, 2800)
}

const stopTipCarousel = () => {
  if (tipTimer) {
    clearInterval(tipTimer)
    tipTimer = null
  }
}

const renderChart = () => {
  if (!chartInstance) {
    return
  }
  chartInstance.setOption(buildOption(), true)
  startTipCarousel()
}

const loadData = async () => {
  try {
    const response = await fetch(API_URL)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const result = await response.json()
    if (result.code !== 1 || !result.data) {
      throw new Error(result.message || '接口返回异常')
    }

    chartData.value = {
      labels: result.data.labels || [],
      liveCattlePrice: (result.data.liveCattlePrice ?? result.data.live_cattle_price ?? []).map(toRawValue),
      beefPrice: (result.data.beefPrice ?? result.data.beef_price ?? []).map(toRawValue),
      unit: result.data.unit || result.data.liveUnit || '元/kg',
      liveUnit: result.data.liveUnit || result.data.unit || '元/kg',
      beefUnit: result.data.beefUnit || result.data.unit || '元/kg'
    }
    renderChart()
  } catch (error) {
    console.error('加载价格趋势数据失败:', error)
  }
}

const handleResize = () => {
  chartInstance?.resize()
  syncChartBaseToGrid(chartInstance, baseRef.value)
}

onMounted(async () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    unbindChartBaseSync = bindChartBaseSync(chartInstance, baseRef.value)
  }
  await loadData()
  window.addEventListener('resize', handleResize)
  window.addEventListener('dataReloaded', loadData)
})

onUnmounted(() => {
  stopTipCarousel()
  unbindChartBaseSync?.()
  unbindChartBaseSync = null
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('dataReloaded', loadData)
  chartInstance?.dispose()
})
</script>

<style scoped>
.chart-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 0 4px;
  overflow: visible;
}

.chart {
  width: 100%;
  flex: 1;
  min-height: 0;
}

.chart-base {
  display: block;
  width: 100%;
  height: 90px;
  object-fit: fill;
  flex-shrink: 0;
  pointer-events: none;
  user-select: none;
  margin-top: -26px;
}
</style>
