<template>
	<div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
	import * as echarts from "echarts";
	import resize from "./mixins";

	export default {
		name: "ChartItem",
		// 应对须要定制化调用echartApi的场景
		mixins: [resize],
		props: {
			className: {
				type: String,
				default: "chart",
			},
			id: {
				type: String,
				default: "chart",
			},
			width: {
				type: String,
				default: "100%",
			},
			height: {
				type: String,
				default: "100%",
			},
			options: {
				type: Object,
				default: () => {
					return {};
				},
			},
			echartApi: {
				type: Function,
				default: () => {},
			},
		},
		watch: {
			options(newV) {
				console.log(newV);
				this.chart.setOption(newV, true);
				this.useApi();
				deep: true;
			},
			watch: {
				$route(to, from) {
					this.chart.resize();
				},
			},
		},
		data() {
			return {
				chart: null,
			};
		},
		created() {},
		mounted() {
			// window.addEventListener("resize", () => {
			//   this.chart && this.chart.resize();
			// });

			this.initChart();
			this.useApi();
		},
		beforeDestroy() {
			if (!this.chart) {
				return;
			}
			this.chart.dispose();
			this.chart = null;
		},
		methods: {
			initChart() {
				this.chart = echarts.init(document.getElementById(this.id));
				const myChart = this.chart;
				myChart.clear();
				
				myChart.setOption(this.options);
			},
			useApi() {
				// 如果有需要默认加载的echartsAPI 在此处执行
				this.echartApi && this.echartApi(this.chart);
			},
		},
	};
</script>