<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: {
		xAxis: [],
		data:[]
	}
  },
  // 高度
  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: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
				crossStyle: {
					color: '#999'
				}
			}
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			axisLabel: {
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#909090",
				fontSize: 12
			},
			data: data.value.xAxis
		},
		grid: {
			top: '6%',
			left: '1%',
			right: '4%',
			bottom: '1%',
			containLabel: true
		},
		yAxis: {
			type: 'value',
			splitNumber: 3,
			axisLabel: {
				fontSize: 12,
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#909090",
				showMaxLabel: true
			},
			splitLine: {
				show: true,
				lineStyle: {
					// color: ['#5a5a5a']
				}
			}
		},
		series: data.value.data
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    option.value.series = newValue.data;
	option.value.xAxis.data = newValue.xAxis;
},{ deep: true });
watch(option, (newValue) => {
    echartInstance.setOption(newValue, true);
},{ deep: true });
watch(() => store.state.settings.sideTheme, (newValue) => {
	let _ais = (newValue.indexOf("dark") != -1)?"#fff":"#909090";
	echartInstance.setOption({
		xAxis:{ axisLabel: {color: _ais}},
		yAxis:{ axisLabel: {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>