<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: "",
		value: 0,
		unit: ""
	}
  },
  // 高度
  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: {
		graphic: [{
			type: 'text',
			left: 'center',
			top: 'center',
			z: 10,
			style: {
				fill: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000",
				text: data.value.data[0].name,
				font: '14px Microsoft YaHei'
			}
		}],
		series: [{
			name: '实时数据',
			type: 'pie',
			center:["50%", "50%"],
			radius: ['60%', '80%'], 
			avoidLabelOverlap: false,
			hoverAnimation: false, 
			label: {
				normal: {
					show: false,
				}
			},
			data: data.value.data
		}],
		color: ['#FFF076','#52989F']
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    option.value.series[0].data = newValue.data;
},{ 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({
		graphic: [{
			style: { fill: _ais }
		}]
	});
});
onMounted(() => {
	nextTick(()=>{
		echartInstance = echarts.init(document.getElementsByClassName(name.value)[0]);
		echartInstance.setOption(option.value, true);
	})
});

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

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

useResize();
</script>