<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: '实时数据',
			min: -40,
			max: 40,
			splitNumber:8,
			type: 'gauge',
			radius: '90%',
			center: ['50%', '55%'],
			data: [{
				value: data.value.value,
				name: data.value.name
			}],
			title: {
				show: false,
				fontSize: 8,
			},
			detail: {
				offsetCenter: [0, '40%'],
				fontSize: 12
			},
			axisTick: {
				distance:0,
				length: 4,
			},
			pointer: {
				width: 2,
				length: "50%",
			},
			splitLine: {
				length: 5,
				distance: 2,
				lineStyle: {
					width: 1
				}
			},
			axisLine: {
				lineStyle: {
					color: [
						[0.5, 'red'],
						[1, 'green']
					],
					width: 10
				}
			},
			axisLabel: {
				distance: 14,
				color: "#000",
				fontSize: 8
			}
		}]
	}
});

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 }
);
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>