<template>
  <div ref="echart" :class="name" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from "echarts";
import useResize from "@/hooks/useResize"; // hook
const store = useStore();
const { proxy } = getCurrentInstance(); // 获取实例中的proxy

let echart;
let echartInstance;

const props = defineProps({
  // 数据
  data: {
    type: Object,
    default: {
		name: "",
		data:[]
	}
  },
  // 高度
  height: {
    type: [Number, String],
    default: "300px",
  },
  // 宽度
  width: {
    type: [Number, String],
    default: "100%",
  },
  name: {
		type: String,
		default: 'echart'
	}
});

const { data, name } = toRefs(props);
const data1 = reactive({
	option: {
		tooltip: {
			trigger: 'item'
		},
		legend: {
			bottom: '15%',
			right: '5%',
			orient: 'vertical',
			itemWidth: 8,
			itemHeight: 8,
			textStyle: {
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000",
				fontSize: 10
			}
		},
		series: [{
			name: data.value.name,
			type: 'pie',
			radius: ['45%', '70%'],
			center: ['40%', '50%'],
			avoidLabelOverlap: false,
			label: {
				show: false,
				position: 'center'
			},
			emphasis: {
				label: { show: false }
			},
			labelLine: { show: false },
			data: data.value.data
		}]
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    option.value.series = newValue;
},{ deep: true });
watch(option, (newValue) => {
    echartInstance.setOption(newValue, true);
},{ deep: true });
watch(() => store.state.settings.sideTheme, (newValue) => {
	let _ais = (newValue.indexOf("dark") != -1)?"#fff":"#000";
	echartInstance.setOption({
		legend:{ textStyle: {color: _ais}}
	});
});
onMounted(() => {
	// echart = proxy.$refs.echart;
	// echartInstance = echarts.init(echart, "macarons");
	// echartInstance.setOption(option.value, true);
	nextTick(()=>{
		echartInstance = echarts.init(document.getElementsByClassName(name.value)[0]);
		echartInstance.setOption(option.value, true);
	})
});

function resize() {
	echartInstance.resize();
}

// 暴露函数 （供hook调用）
defineExpose({
  resize,
});

useResize();
</script>