<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: [{
			type: 'gauge',
			radius: data.value.scalc || '95%',
			max: data.value.max || 1500,
			progress: {
		        show: true,
		        width: 6
			},
			axisLine: {
				lineStyle: {
					width: 6
				}
			},
			axisTick: {
				show: false
			},
			splitLine: {
				length: 5,
				distance: 1,
				lineStyle: {
					width: 1
				}
			},
			anchor: {
		        show: true,
		        showAbove: true,
		        size: 8,
		        itemStyle: {
					borderWidth: 3
		        }
			},
			pointer: {
			  	width: 2,
			  	length: "50%",
			},
			axisLabel: {
				distance: 8,
				color: "#000",
				fontSize: 8
			},
			title: {
		        show: false,
				fontSize: 10,
				offsetCenter: [0, '50%']
			},
			detail: {
				formatter: function (value) {
					return '{value|' + value + '}{unit|'+data.value.unit+'}';
				},
		        fontSize: 12,
		        offsetCenter: [0, '70%'],
				rich: {
					unit: {
						fontSize: 8,
						color: '#000',
						padding: [0, 0, 0, 3]
					}
				}
			},
			data: [{
				value: data.value.value,
				name: data.value.name
			}]
		}]
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    // option.value.yAxis.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>