<template>
  <div class="chart-item" :id="elementId"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { initEcharts, disposeEchartsByKey, setOption } from './echartsOptions';
import emitter from '@/utils/eventBus';
import { useDark } from '@vueuse/core';

const props = defineProps(['chartsId', 'barType']);
const elementId = ref('chartId');
const colorList = ref([]);
const option = ref<any>({});

const initChart = () => {
  if (colorList.value.length) {
    option.value.color = colorList.value;
  }
  nextTick(() => {
    initEcharts(elementId.value, elementId.value, props.barType, option.value, useDark().value);
  });
};

defineExpose({
  elementId,
  colorList,
  option,
  initChart,
  setOption,
  disposeEchartsByKey,
});

onMounted(() => {
  elementId.value = props.chartsId;
});
// 监听主题颜色变化，动态更新图表颜色
emitter.on('THEME_CHANGE', (isDarkMode: any) => {
  initEcharts(elementId.value, elementId.value, props.barType, option.value, isDarkMode);
});
onBeforeUnmount(() => {
  emitter.off('THEME_CHANGE');
});
</script>

<style scoped lang="scss">
.chart-item {
  width: 100%;
  height: 100%;
  background-color: var(--el-bg-color);
}
</style>
