<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, Ref, reactive, watchEffect } from 'vue';
import { useECharts } from '/@/hooks/web/useECharts';
import { cloneDeep } from 'lodash-es';
export default defineComponent({
  name: 'single-line',
  props: {
    chartData: {
      type: Array,
      default: () => [],
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '100%',
    },
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions, echarts } = useECharts(chartRef as Ref<HTMLDivElement>);
    const option = reactive({

      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, .6)',
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
      },
      legend: {
        // right: 'center',
        top: '4%',
        type: 'plain',
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
        // icon:'rect',
        itemGap: 15,
        itemWidth: 10,
        icon: 'path://M0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z',
        data: [],
      },
      xAxis: {
        type: 'category',
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [],
    });

    watchEffect(() => {
      initCharts();
      // props.chartData && initCharts();
    });

    function initCharts() {
      if (props.option) {
        Object.assign(option, cloneDeep(props.option));
      }
      let seriesData = props.chartData.map((item, index) => {
        return item.val;
      });
      let seriesData1 = props.chartData.map((item, index) => {
        return item.val1;
      });
      let seriesData2 = props.chartData.map((item, index) => {
        return item.val2;
      });
      let xAxisData = props.chartData.map((item) => {
        return item.name;
      });
      let legendData = option.series.map(item => {
        return {
          name: item.name
        }
      })

      option.series.forEach((el: any, index) => {
        if (el.data == 'val') {
          option.series[index].data = seriesData;
        } else if (el.data == 'val1') {
          option.series[1].data = seriesData1;
        } else if (el.data == 'val2') {
          option.series[2].data = seriesData2;
        }
      });



      option.xAxis.data = xAxisData;
      option.legend.data = legendData
      setOptions(option);
      //   window.onresize = function () {
      //   myChart.resize();
      // };
    }

    return { chartRef };
  },
});
</script>
