
import { markRaw, ref } from 'vue';
import { watchDebounced, useWindowSize } from '@vueuse/core';
import echarts from '@/utils/echarts';

const grid = { left: 5, right: 5, top: 20, bottom: 15, containLabel: true };

export default function useLineChart(chartRef, options = { grid: {}, legendData: ref([]), autoSize: true, emptyText: '' }) {
  const chart = ref(null);
  const chartGrid = { ...grid, ...options.grid };
  const xAxisData = ref([]);
  const seriesData = ref([]);
  watchDebounced(
    [xAxisData, seriesData],
    () => {
      paint(true)
     },
    { debounce: 500, maxWait: 1000 },
  )

  const { width } = useWindowSize();
  watchDebounced(
    width,
    () => { options.autoSize && chart.value && chart.value.resize() },
    { debounce: 500, maxWait: 1000 },
  )
  function clear() {
    chart.value && chart.value.clear();
    chart.value = null;
  }

  function setChart() {
    chart.value = markRaw(echarts.init(chartRef.value));
  }

  function paint(repaint = false) {
    if (chartRef.value && !chart.value) {
      setChart();
      repaint = false;
    };
    if (!chart.value) return;
    // if (xAxisData.value.length === 0) {
    //   chart.value.clear();
    //   return
    // }
    chart.value.setOption({
      grid: chartGrid,
      title: {
        show: seriesData.value.length === 0 && options.emptyText, // 是否显示title
        text: options.emptyText,
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 400
        }
      },
      legend: { data: options.legendData && options.legendData.value ? options.legendData.value : [], show: true, padding: [0, 0, 20, 0], right: 10, top: 0 },
      tooltip: { trigger: 'axis' },
      series: getSeriesData(),
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData.value
      },
      yAxis: { type: 'value', minInterval: 1 }
    }, repaint);
  }

  function getSeriesData() {
    if (options.legendData && options.legendData.value.length > 1) {
      return options.legendData.value.map((name, idx) => ({
        name,
        type: 'line',
        stack: name,
        data: seriesData.value[idx] || []
      }))
    }
    return [{ data: seriesData.value, type: 'line', itemStyle: { color: '#006eff' }, label: { show: true, position: 'top' } }]
  }
  // function toggleLegend(name) {
  //   name && chart.value.dispatchAction({
  //     type: 'legendToggleSelect',
  //     name
  //   })
  // }

  return { xAxisData, seriesData, paint, chart, clear }
}