import * as echarts from 'echarts'
import { MUTICHARTCOLORS } from '@/common/constant'

// 十六进制颜色转 rgba 的工具函数
function hexToRgba(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

const getSerie = (data, index) => {
  return {
    name: data.name,
    type: 'line',
    smooth: true,
    symbol: 'emptyCircle',
    symbolSize: 6,
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
        offset: 0,
        color: hexToRgba(MUTICHARTCOLORS[index], 0.7)
      }, {
        offset: 1,
        color: hexToRgba(MUTICHARTCOLORS[index], 0)
      }])
    },
    emphasis: { focus: 'series' },
    data: data.value
  }
}

const createLineChart = (chartDom, data, option={}) => {
  if (!chartDom.value) return;

  // 先销毁之前的实例
  const existingChart = echarts.getInstanceByDom(chartDom.value);
  if (existingChart) existingChart.dispose();
  
  // 获取容器宽度/高度
  const containerWidth = chartDom.value.clientWidth;
  const containerHeight = chartDom.value.clientHeight;

  const myChart = echarts.init(chartDom.value);
  myChart.setOption({
    color: MUTICHARTCOLORS,
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'cross',
        label: { backgroundColor: '#6a7985' }
      }
    },
    grid: {
      top: 40,
      bottom: 0,
      right: 26,
      left: 12,
      containLabel: true
    },
    legend: {
      show: data?.list?.length>1,
      top: 10,
      icon: 'circle',
      textStyle: {
        color: 'rgba(95, 101, 108, 1)',
        fontFamily: 'Microsoft YaHei',
        fontSize: '14px',
      }
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: data.title,
        axisLine: {
          show: true,
          lineStyle: {
              color: '#e7f3ff',
          },
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: 'rgba(95, 101, 108, 1)',
            fontFamily: 'Microsoft YaHei',
            fontsize: 14,
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        position: 'left',
        name: "项",
        nameLocation: 'end',
        nameGap: 12,
        nameTextStyle: {
          color: '#666',
          fontSize: 14,
          fontWeight: 400,
          padding: [0, 0, 6, -26]
        },
        axisLabel: {
          formatter: '{value}',
          color: '#666',
          fontSize: 14,
          fontWeight: 400
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#e7f3ff',
            type: 'dashed',
          }
        },
      }
    ],
    series: data.list.map(getSerie)
  })
  return myChart
}

export default createLineChart