<template>
  <div ref="chartRef" class="item"></div>
</template>
<script lang="ts" setup>
  import * as echarts from 'echarts';
  import { ref, unref, onMounted, markRaw, watch, inject } from 'vue';

  import { isNumber } from 'min-dash';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { chartType } from '../../../types';
  import { cloneDeep } from 'lodash-es';
  import { refreshChart } from '../../../types/tool';

  const { t } = useI18n();
  const chartRef = ref<HTMLDivElement>();
  const props = defineProps({
    config: { type: Object, default: () => {} },
    refreshkey: String,
  });
  const widgetFormModel = inject('widgetFormModel', ref<any>({}));
  const myEcharts = ref<any>();
  const data = ref(cloneDeep(props.config) || {});
  watch(
    () => [props.config, props.refreshkey],
    async () => {
      data.value = cloneDeep(props.config) || {};
      changeApiData();
      myEcharts.value = markRaw(echarts.init(unref(chartRef) as HTMLDivElement));
      initChart(true);
      setTimeout(() => {
        resizeChart();
      }, 1);
    },
    { deep: true },
  );
  onMounted(async () => {
    changeApiData();
    myEcharts.value = markRaw(echarts.init(unref(chartRef) as HTMLDivElement));
    initChart(true);
    setTimeout(() => {
      resizeChart();
    }, 1);
  });

  async function changeApiData() {
    let config = data.value;

    await refreshChart(config.apiConfig, config, widgetFormModel.value);
    // 折/柱状图
    if (props.config.chartType == chartType.line) {
    }
    // 漏斗图
    if (props.config.chartType == chartType.funnel) {
      let labelKey = 'name';
      if (config.labelKey) {
        labelKey = config.labelKey;
      } else {
        config.labelKey = 'name';
      }
      let valueKey = 'value';
      if (config.labelKey) {
        valueKey = config.valueKey;
      } else {
        config.valueKey = 'value';
      }
      config.echarts.legend.width = config.autoWidth
        ? 'auto'
        : config.echarts.legend.width === 'auto'
        ? 200
        : config.echarts.legend.width;
      if (config.echarts && config.echarts.series) {
        config.echarts.series[0].data = config.apiData.map((ele) => {
          return { name: ele[labelKey], value: ele[valueKey] };
        });
      }
      // 图例
      config.echarts.legend.data = config.echarts.series[0].data.map((ele) => {
        return ele.name;
      });
    }
    // 饼图
    if (props.config.chartType == chartType.pie) {
      config.echarts.color = config.colors;
      config.echarts.legend.width = config.autoWidth
        ? 'auto'
        : config.echarts.legend.width === 'auto'
        ? 200
        : config.echarts.legend.width;
      let labelKey = config.labelKey ? config.labelKey : 'name';
      let valueKey = config.valueKey ? config.valueKey : 'value';
      if (config.echarts && config.echarts.series) {
        config.echarts.series[0].data = config.apiData.map((ele, idx) => {
          return {
            name: ele[labelKey],
            value: ele[valueKey],
            selected: idx === config.defaultSelect,
          };
        });
      }
    }
    // 仪表盘
    if (props.config.chartType == chartType.gauge) {
      let labelKey = config.labelKey ? config.labelKey : 'name';
      let valueKey = config.valueKey ? config.valueKey : 'value';
      if (config.echarts && config.echarts.series && config.echarts.series[0]) {
        // 仪表盘只显示第一条数据
        config.echarts.series[0].data = config.apiData
          .filter((_, i) => i === 0)
          .map((ele) => {
            return { name: ele[labelKey], value: isNumber(ele[valueKey]) ? ele[valueKey] : 0 };
          });
      }
    }
    // 雷达图
    if (props.config.chartType == chartType.radar) {
      // 根据指标来显示数据
      let legendData = [];
      if (config.apiData.length > 0) {
        legendData = config.apiData.map((ele) => {
          return ele[config.labelKey];
        });
        if (config.echarts && config.echarts.radar && config.echarts.radar.indicator) {
          config.echarts.radar.indicator.forEach((element, index) => {
            config.echarts.series[0].data[index].value = [];
            config.echarts.series[0].data[index].name = '';
            if (
              element.value &&
              config.echarts.series[0].data &&
              config.echarts.series[0].data[index]
            ) {
              let values = [];
              if (config.apiData.length > 0) {
                values = config.apiData.map((ele) => {
                  return ele[element.value];
                });
              }
              config.echarts.series[0].data[index].value = values;
              config.echarts.series[0].data[index].name = legendData[index];
              config.echarts.legend.data[index] = legendData[index];
            }
          });
        }
      }
    }
    // 甘特图
    if (props.config.chartType == chartType.barStack) {
      let labelKey = config.labelKey ? config.labelKey : 'name';
      let valueKey = config.valueKey ? config.valueKey : 'value';
      let targetKey = config.targetKey ? config.targetKey : 'value';
      config.echarts.yAxis.data = config.apiData.map((ele) => {
        return ele[labelKey];
      });
      if (config.echarts && config.echarts.series) {
        let valueData = config.apiData.map((ele) => {
          return ele[valueKey];
        });
        let valueNameData = config.apiColumns.filter((ele) => {
          return ele.prop == valueKey;
        });
        config.echarts.series[0] = {
          name: valueNameData && valueNameData.length > 0 ? valueNameData[0].label : valueKey,
          type: 'bar',
          stack: 'total',
          label: {
            show: false,
          },
          color: '#ff7345',
          emphasis: {
            focus: 'series',
          },
          data: valueData,
        };
        let targetData = config.apiData.map((ele) => {
          return ele[targetKey];
        });
        let targetNameData = config.apiColumns.filter((ele) => {
          return ele.prop == targetKey;
        });
        config.echarts.series[1] = {
          name: targetNameData && targetNameData.length > 0 ? targetNameData[0].label : targetKey,
          type: 'bar',
          stack: 'total',
          label: {
            show: false,
          },
          color: '#6a6e88',
          emphasis: {
            focus: 'series',
          },
          data: targetData,
        };
      }
    }
  }
  /**
   * 初始化echart
   * @param clearCaching 是否清除缓存
   */
  const initChart = (clearCaching = false) => {
    myEcharts.value.showLoading({
      text: t('加载中'),
      color: '#5e95ff',
      textColor: 'rgba(255, 255, 255, 0.6)',
      maskColor: 'rgba(255, 255, 255, 0.2)',
      zlevel: 0,
    });
    setTimeout(() => {
      myEcharts.value.hideLoading();
      if (myEcharts.value && data.value.echarts)
        myEcharts.value.setOption(data.value.echarts, clearCaching);
    }, 100);
  };

  /**
   * 重置echart
   */
  const resizeChart = () => {
    if (data.value.echarts) {
      if (myEcharts.value) myEcharts.value.resize();
    }
  };
</script>
<style lang="less" scoped>
  .item {
    height: 100%;
    width: 100%;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    position: relative;
  }
</style>
