<template>
  <div v-if="spinning" class="spinning">
    <a-spin :spinning="true" />
  </div>
  <div v-if="!spinning" ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts">
  import { defineComponent, PropType, ref, Ref, reactive, watchEffect, watch, nextTick } from 'vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
  import EchartsUtil from '/@/utils/echartsUtil';
  import { merge } from 'lodash-es';
  import { columns } from '/@/views/monitor/datalog/datalog.data';
  type ChartColumn = {
    legend: string;
    seriesName: string;
    ymax: number;
    yname: string;
    linetype: string;
    yaxispos: string;
    color: string;
    sort: number;
    xRotate: number;
    dataIndex: string;
  };
  export default defineComponent({
    name: 'BarAndLine',
    props: {
      chartsColumns: {
        type: Array as PropType<ChartColumn[]>,
        default: () => [],
      },
      chartsColumnsType: {
        type: String,
      },
      chartsType: {
        type: String,
        default: '',
      },
      dataSource: {
        type: Array,
        default: () => [],
      },
      option: {
        type: Object,
        default: () => ({}),
      },
      xAxisPropType: {
        type: String,
        required: true,
      },
      width: {
        type: String as PropType<string>,
        default: '100%',
      },
      height: {
        type: String as PropType<string>,
        default: 'calc(100vh - 78px)',
      },
    },
    emits: ['refresh'],
    setup(props, { emit }) {
      const spinning = ref<boolean>(true);
      const chartRef = ref<HTMLDivElement | null>(null);
      const { setOptions, echarts } = useECharts(chartRef as Ref<HTMLDivElement>);
      const chartData = props.chartsColumnsType ? getTableHeaderColumns(props.chartsColumnsType) : [];
      let chartsColumns = (props.chartsColumns.length > 0 ? props.chartsColumns : chartData) as ChartColumn[];
      // let groupedByColumns = {};
      const option = reactive({
        name: '',
        color: ['#7B68EE', '#0000CD', '#6495ED', '#00BFFF', '#AFEEEE', '#008080', '#00FA9A', '#2E8B57', '#FAFAD2', '#DAA520'],
        tooltip: {},
        grid: {},
        toolbox: {
          feature: {
            saveAsImage: {
              iconStyle: {
                borderColor: '#ffffff',
              },
              show: true,
            },
          },
        },
        dataZoom: {},
        legend: {
          textStyle: {
            color: '#ffffff', // 字体颜色
          },
          top: '20',
        },
        timeline: null,
        xAxis: {},
        yAxis: null,
        series: null,
      });
      let optionUtil;

      watchEffect(() => {
        props.dataSource && props.xAxisPropType && option.series && initCharts();
      });

      watch([() => props.chartsType, () => props.chartsColumns], ([newChartsType, newChartsColumns]) => {
        spinning.value = true;
        chartsColumns = newChartsColumns;
        optionUtil.initChartOption(newChartsType, newChartsColumns);
        spinning.value = false;
        initCharts(true);
        emit('refresh');
      });

      // watch(yMax, (newVal) => {
      //   // y轴最大值变化，需要重新更新
      //   chartsColumns = chartsColumns.map((column: ChartColumn) => {
      //     column['ymax'] = newVal;
      //   });
      //   optionUtil.initChartOption(props.chartsType, chartsColumns);
      //   spinning.value = false;
      //   initCharts(true);
      //   emit('refresh');
      // });

      function initChartsOption() {
        // debugger;
        optionUtil = new EchartsUtil(merge(option, props.option));
        optionUtil.initChartOption(props.chartsType, chartsColumns);
      }
      initChartsOption();

      function initCharts(isRefresh = false) {
        debugger;
        if (props.dataSource.length < 1) return;
        //轴数据
        let isFresh = false;
        if (option.series && option.series.length === chartsColumns.length) {
          let xAxisData = props.dataSource.map((item) => item[props.xAxisPropType]);
          chartsColumns = [...chartsColumns].filter((propType: any, index) => {
            if (!propType) return;
            if (props.chartsType == 'listMonitor') {
              option.series[index].type = 'bar';
            }
            option.series[index].data = props.dataSource.map((item) => Number(item[propType.dataIndex]) || 0);
            console.log('nnn', option.series[index].data);
            // 这里动态计算echarts y轴最大值
            const max = Math.max(...option.series[index].data);
            const digitCount = max.toFixed(0).length;
            let yMax = 0;
            if (digitCount < 2) {
              yMax = 10;
            } else if (digitCount < 3) {
              const n = Number((Number(max.toFixed(0)) / 10).toFixed(0));
              yMax = (n + 1) * 10;
            } else if (digitCount < 4) {
              const n = Number((Number(max.toFixed(0)) / 100).toFixed(0));
              yMax = (n + 1) * 100;
            } else if (digitCount < 5) {
              const n = Number((Number(max.toFixed(0)) / 1000).toFixed(0));
              yMax = (n + 1) * 1000;
            } else if (digitCount < 6) {
              const n = Number((Number(max.toFixed(0)) / 10000).toFixed(0));
              yMax = (n + 1) * 10000;
            }

            if (yMax != 0 && yMax !== propType?.ymax) {
              propType.ymax = yMax;
              isFresh = true;
            }
            return true;
          });
          option.xAxis[0].data = xAxisData;
          if (isFresh) {
            spinning.value = true;
            optionUtil.initChartOption(props.chartsType, chartsColumns);
            spinning.value = false;
            initCharts(true);
            emit('refresh');
            nextTick(() => {
              setOptions(option, true);
            });
          } else {
            // console.log('echarts监测列表数据', option.xAxis[0].data);
            setOptions(option, isRefresh);
          }
        }
      }
      setTimeout(() => {
        spinning.value = false;
        initCharts(true);
      }, 1000);
      return { chartRef, spinning };
    },
  });
</script>
<style lang="less" scoped>
  .spinning {
    display: flex;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
  }
</style>
