<!--
  折线图组件
  支持多条折线、面积图、平滑曲线
-->

<template>
  <BaseChart
    :option="chartOption"
    :height="height"
    :loading="loading"
    @ready="handleReady"
    @click="handleClick"
  />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import BaseChart from './BaseChart.vue'
import { lineChartOption, echartsTheme, formatNumber } from '@/utils/echarts'
import type { LineChartConfig } from '@/types/charts'

/** Props */
interface Props {
  data: Array<{ name: string; value: number; [key: string]: any }>
  series?: Array<{ name: string; data: number[]; color?: string }>
  title?: string
  area?: boolean
  smooth?: boolean
  xAxisLabel?: string
  yAxisLabel?: string
  height?: string
  showDataZoom?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  series: undefined,
  title: '',
  area: false,
  smooth: true,
  xAxisLabel: '',
  yAxisLabel: '',
  height: '400px',
  showDataZoom: false,
})

/** Emits */
interface Emits {
  (e: 'ready', chart: any): void
  (e: 'click', item: any): void
}

const emit = defineEmits<Emits>()

/** 加载状态 */
const loading = ref(false)

/** 图表配置 */
const chartOption = computed(() => {
  // 如果提供了系列数据，使用系列数据
  if (props.series && props.series.length > 0) {
    const categories = props.data.map((item) => item.name)

    return {
      ...lineChartOption,
      title: {
        ...lineChartOption.title,
        text: props.title,
      },
      tooltip: {
        ...lineChartOption.tooltip,
        formatter: (params: any) => {
          if (Array.isArray(params)) {
            let result = `${params[0].name}<br/>`
            params.forEach((param: any) => {
              result += `${param.marker} ${param.seriesName}: ${formatNumber(param.value)}<br/>`
            })
            return result
          }
          return `${params.name}<br/>${params.seriesName}: ${formatNumber(params.value)}`
        },
      },
      legend: {
        ...lineChartOption.legend,
        data: props.series.map((s) => s.name),
      },
      xAxis: {
        ...lineChartOption.xAxis,
        data: categories,
        name: props.xAxisLabel,
      },
      yAxis: {
        ...lineChartOption.yAxis,
        name: props.yAxisLabel,
      },
      dataZoom: props.showDataZoom
        ? [
            {
              type: 'slider',
              show: true,
              start: 0,
              end: 100,
              xAxisIndex: 0,
            },
          ]
        : undefined,
      series: props.series.map((s, index) => ({
        type: 'line',
        name: s.name,
        data: s.data,
        smooth: props.smooth,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2,
          color: s.color || echartsTheme.color[index % echartsTheme.color.length],
        },
        itemStyle: {
          color: s.color || echartsTheme.color[index % echartsTheme.color.length],
        },
        areaStyle: props.area
          ? {
              opacity: 0.1,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: s.color || echartsTheme.color[index % echartsTheme.color.length] },
                { offset: 1, color: 'rgba(255, 255, 255, 0)' },
              ]),
            }
          : undefined,
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderWidth: 2,
            borderColor: '#fff',
          },
        },
      })),
    }
  }

  // 单系列数据
  const categories = props.data.map((item) => item.name)
  const values = props.data.map((item) => item.value)

  return {
    ...lineChartOption,
    title: {
      ...lineChartOption.title,
      text: props.title,
    },
    tooltip: {
      ...lineChartOption.tooltip,
      formatter: (params: any) => {
        return `${params.name}<br/>${params.seriesName}: ${formatNumber(params.value)}`
      },
    },
    xAxis: {
      ...lineChartOption.xAxis,
      data: categories,
      name: props.xAxisLabel,
    },
    yAxis: {
      ...lineChartOption.yAxis,
      name: props.yAxisLabel,
    },
    dataZoom: props.showDataZoom
      ? [
          {
            type: 'slider',
            show: true,
            start: 0,
            end: 100,
            xAxisIndex: 0,
          },
        ]
      : undefined,
    series: [
      {
        type: 'line',
        name: props.yAxisLabel || '数值',
        data: values,
        smooth: props.smooth,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2,
        },
        itemStyle: {
          color: echartsTheme.color[0],
        },
        areaStyle: props.area
          ? {
              opacity: 0.1,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: echartsTheme.color[0] },
                { offset: 1, color: 'rgba(255, 255, 255, 0)' },
              ]),
            }
          : undefined,
        emphasis: {
          focus: 'series',
        },
      },
    ],
  }
})

/** 处理图表就绪 */
const handleReady = (chart: any) => {
  emit('ready', chart)
}

/** 处理点击事件 */
const handleClick = (params: any) => {
  const item = props.data.find((d) => d.name === params.name)
  if (item) {
    emit('click', { ...item, ...params })
  }
}

/** 暴露方法 */
defineExpose({
  loading,
})
</script>
