<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: {
		max: 3000,
		value: 0,
		name: "name",
		show: false,
		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: {
		tooltip: {
			formatter: '{a} <br/>{b} '+': {c}'+data.value.unit
		},
		series: [{
			name: '实时数据',
			type: 'gauge',
			radius: data.value.scalc || '95%',
			max: data.value.max || 1500,
			data: [{
				value: data.value.value,
				name: data.value.name
			}],
			title: {
				show:true,
				fontSize: 10,
				offsetCenter: [0, '20%'],
			},
			detail: {
				fontSize: 14,
				formatter: function (value) {
					return '{value|' + value.toFixed(0) + '}{unit|'+data.value.unit+'}';
				},
				offsetCenter: [0, '50%'],
				rich: {
					unit: {
						fontSize: 10,
						color: '#000',
						padding: [0,0,0,6]
					}
				}
			},
			axisTick: {
				distance: 2,
				length: 3,
			},
			pointer: {
				width: 2,
				length: "50%",
			},
			splitLine: {
				length: 5,
				distance: 2,
				lineStyle: {
					width: 1
				}
			},
			axisLine: {
				lineStyle: {
					width: 4
				}
			},
			axisLabel: {
				distance: 8,
				color: "#000",
				fontSize: 8
			}
		}]
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    option.value.series[0].data[0].value = newValue.value;
  },{ deep: true }
);
watch(option, (newValue) => {
    echartInstance.setOption(newValue, true);
  },{ deep: true }
);
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>