<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "Chat",
});
</script>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, markRaw } from "vue";
import * as echarts from "echarts";

const emits = defineEmits(["init"]);

interface PropsType {
  options: Record<string, any>;
}

const props = withDefaults(defineProps<PropsType>(), {
  options: () => ({}),
});

// 容器
let containerRef = ref();

// echat实例
let chartRef: echarts.ECharts | null = null;

// 重置尺寸
const resize = () => {
  chartRef?.resize();
};

// 添加监听
const addListen = () => {
  window.addEventListener("resize", resize);
};

// 移除监听
const removeListen = () => {
  window.removeEventListener("resize", resize);
};

// 初始化图标
const initChart = () => {
  chartRef?.clear();
  chartRef?.setOption(props.options);
};

// 初始化
const init = () => {
  chartRef = markRaw(echarts.init(containerRef.value));
  emits("init", chartRef);
  initChart();
  addListen();
};

watch(
  () => props.options,
  () => {
    initChart();
  },
);

onMounted(() => {
  init();
});

onUnmounted(() => {
  removeListen();
  chartRef?.dispose();
});

const prefix = "circle-chat";
</script>

<template>
  <div :class="prefix">
    <div ref="containerRef" style="width: 100%; height: 100%"></div>
  </div>
</template>

<style lang="scss" scoped>
$prefix: "circle-chat";
.#{$prefix} {
  width: 100%;
  height: 100%;
}
</style>
