<template>
  <div ref="chartRef" class="line-chart" :style="{ width: width, height: height }"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import * as echarts from 'echarts'

interface ChartDataItem {
  date: string
  value: number
}
interface ChartMulDataItem {
  date: string
  values: Array<{
    value: number
    percentage?: string
    seriesName?: string
  }>
}

interface Props {
  data: ChartDataItem[] | ChartMulDataItem[]
  width?: string
  height?: string
  title?: string
  color?: string
  showGrid?: boolean
  showTooltip?: boolean
  showLegend?: boolean
  smooth?: boolean
  areaStyle?: boolean
  isMultiSeries?: boolean
  seriesNames?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  height: '270px',
  title: '',
  color: '#167AF0',
  showGrid: true,
  showTooltip: true,
  showLegend: false,
  smooth: false,
  areaStyle: false,
  isMultiSeries: false,
  seriesNames: () => ['系列1', '系列2']
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 生成系列数据
const seriesData = computed(() => {
  if (!props.isMultiSeries) {
    const values = (props.data as ChartDataItem[]).map(item => item.value)
    return [
      {
        name: props.title || '数据',
        type: 'line',
        data: values,
        smooth: props.smooth,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: props.color,
          width: 2
        },
        itemStyle: {
          color: props.color,
          borderWidth: 2,
          borderColor: props.color,
        },
        emphasis: {
          itemStyle: {
            color: props.color,
            borderWidth: 2,
            borderColor: props.color,
          }
        }
      }
    ]
  } else {
    const multiData = props.data as ChartMulDataItem[]
    if (!multiData || multiData.length === 0 || !multiData[0].values) {
      return []
    }
    
    const colors = [
      'rgba(22, 122, 240, 1)',
      'rgba(159, 91, 255, 1)',
      'rgba(255, 157, 0, 1)',
      'rgba(40, 167, 69, 1)',
      'rgba(220, 53, 69, 1)'
    ]
    
    return multiData[0].values.map((_, index) => ({
      name: props.seriesNames[index] || `系列${index + 1}`,
      type: 'line',
      data: multiData.map((item) => item.values[index]?.value || 0),
      smooth: props.smooth,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        color: colors[index % colors.length],
        width: 2
      },
      itemStyle: {
        color: colors[index % colors.length],
        borderWidth: 2,
        borderColor: colors[index % colors.length],
      },
      emphasis: {
        itemStyle: {
          color: colors[index % colors.length],
          borderWidth: 2,
          borderColor: colors[index % colors.length],
        }
      },
    }))
  }
})

// 获取图例数据
const legendData = computed(() => {
  if (!props.isMultiSeries) {
    return [props.title || '数据']
  } else {
    const multiData = props.data as ChartMulDataItem[]
    if (!multiData || multiData.length === 0 || !multiData[0].values) {
      return []
    }
    return multiData[0].values.map((_, index) => 
      props.seriesNames[index] || `系列${index + 1}`
    )
  }
})

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return

  const dates = props.data.map(item => item.date)

  const option: echarts.EChartsOption = {
    tooltip: props.showTooltip ? {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#E5E5E5',
      borderWidth: 1,
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: props.color,
          width: 1,
          type: 'dashed'
        }
      },
      formatter: function(params: any) {
        if (props.isMultiSeries) {
          let html = `<div style="padding: 8px; text-align: left;">
            <div style="font-weight: 900; margin-bottom: 4px; font-size: 14px;">${params[0].name}</div>`
          
          params.forEach((param: any) => {
            html += `<div style="color: ${param.color}; font-size: 14px; font-weight: 500; margin: 2px 0;">
              <i style="width: 10px; height: 10px; background: ${param.color}; border-radius: 50%; display: inline-block; margin-right: 4px;"></i>
              <span style="color: rgba(100, 100, 100, 1); ">${param.seriesName}:</span> ${param.value}
            </div>`
          })
          
          html += '</div>'
          return html
        } else {
          const data = params[0]
          return `<div style="padding: 8px; text-align: left;">
            <div style="font-weight: 900; margin-bottom: 4px; font-size: 14px;">${data.name}</div>
            <div style="color: ${props.color}; font-size: 14px; font-weight: 500;">
              <i style="width: 10px; height: 10px; background: ${props.color}; border-radius: 50%; display: inline-block; margin-right: 4px;"></i>
              <span style="color: rgba(100, 100, 100, 1); ">${data.seriesName}:</span> ${data.value}
            </div>
          </div>`
        }
      }
    } : undefined,
    legend: props.showLegend ? {
      data: legendData.value,
      bottom: '0px',
      textStyle: {
        fontSize: 12,
        color: '#666'
      },
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 30,
      selectedMode: true,
      itemStyle: {
        borderWidth: 0
      },
    } : undefined,
    grid: {
      left: '0%',
      right: '0%',
      bottom: props.showLegend ? '60px' : '0',
      top: '10px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#E5E5E5'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(100, 100, 100, 1)',
        fontSize: 14
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(100, 100, 100, 1)',
        fontSize: 14,
      },
      splitLine: props.showGrid ? {
        lineStyle: {
          color: 'rgba(230, 230, 230, 1)',
          type: 'dashed'
        }
      } : {
        show: false
      }
    },
    series: seriesData.value as any
  }

  chartInstance.setOption(option)
}

// 监听数据变化
watch(() => props.data, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

// 暴露方法给父组件
defineExpose({
  getChartInstance: () => chartInstance,
  resize: handleResize
})
</script>

<style scoped lang="scss">
.line-chart {
  display: block;
  box-sizing: border-box;
}
</style> 