<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: "",
		radius: "90%"
	},
  },
  // 高度
  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} '+data.value.name+': {c}'+data.value.unit
		},
		series: [{
			name: '实时数据',
			min: 0,
			max: parseFloat(data.value.max||3000) ,
			splitNumber: 8,
			type: 'gauge',
			center: ['50%', '55%'],
			radius: data.value.radius,
			detail: {
				show: data.value.show,
				fontSize: 20,
				color: "#fbbd08",
				formatter: '{value}' + " "+data.value.unit,
				offsetCenter: [0, '86%']
			},
			data: [{
				value: data.value.value
			}],
			axisLine: {
				lineStyle: {
					color: [
						[0.09, 'lime'],
						[0.82, '#1e90ff'],
						[1, '#ff4500']
					],
					width: 5
				}
			},
			axisTick: {
				distance: 2,
				length: 5,
				lineStyle: {
					color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000"
				}
			},
			pointer: {
				width: 5,
				length: "50%",
			},
			splitLine: {
				distance: 2,
				length: 9,
				lineStyle: {
					width: 2,
					color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000"
				}
			},
			axisLabel: {
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000",
				fontSize: 10,
				distance: 6
			}
		}]
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch( data, (newValue) => {
    // option.value.yAxis.data = newValue;
     option.value.series[0].data[0].value = Number(newValue.value);
  }, { 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({
		series:[{
			axisLabel: {color: _ais},
			splitLine: { lineStyle: {color: _ais}},
			axisTick: { lineStyle: {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>