<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'
				}
			}
		},
		grid: {
			top: '6%',
			left: '2%',
			right: '2%',
			bottom: '1%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			axisLabel: {
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000",
				fontSize: 12
			},
			data: data.value.xAxis
		},
		yAxis: {
			type: 'value',
			axisLabel: {
				fontSize: 12,
				color: (store.state.settings.sideTheme.indexOf("dark") != -1)?"#fff":"#000",
				showMaxLabel: true
			},
			splitLine: {
				show: true,
				lineStyle: {
					color: ['#5a5a5a']
				}
			}
		},
		series: [{
			data: data.value.data,
			type: 'bar',
			itemStyle: {
				color: new echarts.graphic.LinearGradient(
					0, 0, 1, 0, [{
							offset: 0,
							color: '#5940ff'
						},
						{
							offset: 1,
							color: '#a38cff'
						}
					]
				),
			}
		}]
	}
});

const { option } = toRefs(data1);

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