<template>
  <l-echart
    ref="chartRef"
    type="2d"
    class="line-chart"
  />
</template>

<script setup lang="ts">
interface TimeSeriesData {
  time: string
  value: number
}

interface ChartData {
  title: string
  unit: string
  color: string
  data: TimeSeriesData[]
}

const props = defineProps<{
  echarts: any
  chartData: ChartData
}>()

const emit = defineEmits(['init'])

const chartRef = ref<any>(null)
let chart: any = null
const chartOption = ref<any>({})

// 初始化图表
async function initChart() {
  await nextTick()
  if (!chartRef.value || !props.chartData.data.length)
    return

  try {
    chart = await chartRef.value.init(props.echarts)
    createOptions()
    refreshChart()
    emit('init', chart)
  }
  catch (error) {
    console.error('Chart initialization error:', error)
  }
}

// 刷新图表
function refreshChart() {
  if (!chart)
    return
  chart.setOption(chartOption.value, true)
}

// 创建图表配置
function createOptions() {
  const { title, unit, color, data } = props.chartData

  chartOption.value = {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0]
        return `${param.axisValue}： ${param.value} ${unit}`
      },
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '3%',
      top: '20%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time),
      axisLabel: {
        rotate: 45,
        fontSize: 10,
      },
    },
    yAxis: {
      type: 'value',
      name: unit,
      nameGap: 15,
    },
    series: [
      {
        data: data.map(item => item.value),
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color,
        },
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: `${color}80`, // 80是透明度
              },
              {
                offset: 1,
                color: `${color}20`, // 20是透明度
              },
            ],
          },
        },
      },
    ],
  }
}

// 监听数据变化
watch(() => props.chartData, () => {
  if (chart) {
    createOptions()
    refreshChart()
  }
  else {
    initChart()
  }
}, { deep: true })

// 组件挂载
onMounted(() => {
  initChart()
})

// 组件卸载
onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})

// 暴露方法给父组件
defineExpose({
  initChart,
  refreshChart,
})
</script>

<style lang="scss" scoped>
.line-chart {
  @apply w-full h-[300px];
}
</style>
