<template>
  <component
    :is="renderChartByType"
    :id="chartId"
    :chartData="chartData"
  ></component>
</template>
<script>
import { defineComponent, computed, ref, watch } from "@vue/composition-api";
import {
  CUSTOM_COM,
  ECHARTS_COM,
  WEB,
} from "@bdlite/chart-config/lib/chartTypes";
import { nanoid } from "nanoid";
import ChartComp from "./ChartComp";
import CustomComp from "./customComps/";
import EchartsConfig from "@/constants/config/echartConfig.js";
import { deepAssign } from "@/utils";
export default defineComponent({
  name: "ChartContainer",
  components: {
    ChartComp,
    CustomComp,
  },
  props: {
    id: {
      type: Number | String,
    },
    chartConfig: {
      type: String,
      default: "",
    },
    dataResult: {
      type: String,
      default: "{}",
    },
  },
  setup(props) {
    const chartId = props.id || nanoid();
    const chartData = ref({});
    const initChartData = () => {
      const parseChartConfig = JSON.parse(props.chartConfig);
      const parseDataResult = JSON.parse(props.dataResult);
      chartData.value = {
        chartType: parseChartConfig.chartType,
        iconConfig: deepAssign(
          {},
          EchartsConfig[parseChartConfig.chartType],
          parseChartConfig.iconConfig || {}
        ),
        dataConfig: {},
        dataResult: parseDataResult,
      };
    };
    watch(
      [() => props.dataResult, () => props.chartConfig],
      () => {
        initChartData();
      },
      {
        immediate: true,
      }
    );
    const renderChartByType = computed(() => {
      if (ECHARTS_COM.includes(chartData.value.chartType)) {
        return "ChartComp";
      } else if (
        CUSTOM_COM.includes(chartData.value.chartType) ||
        WEB === chartData.value.chartType
      ) {
        return "CustomComp";
      }
      return "";
    });
    return {
      chartId,
      chartData,
      renderChartByType,
    };
  },
});
</script>
<style></style>
