<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 option = ref({});
// const data1 = reactive({});
// const {  } = toRefs(data1);
const getOption = function(){
	let _unit = data.value.unit;
	option.value = {
		tooltip: {
			trigger: 'axis',
			formatter: function (params) {
				return params[0].name + '<br/>'+ params[0].seriesName+ "："+params[0].data + _unit
			}
		},
		legend: {
			show: data.value.data.length>1?true:false,
			textStyle: {
				color: "#000"
			}
		},
		grid: {
			top: (data.value.name&&(data.value.name.length||data.value.data.length>1))?'14%':'4%',
			left: '1%',
			right: '2%',
			bottom: '2%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			splitLine: {
				show: true,
				lineStyle: {
					color: '#c6c6c6'
				}
			},
			axisLabel: {
				fontSize: 12,
				color:"#323232",
				showMaxLabel: true
			},
			data: data.value.xAxis
		},
		yAxis: {
			name: data.value.name,
			type: 'value',
			axisLabel: {
				fontSize: 12,
				color:"#323232",
				showMaxLabel: true
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: ['#323232']
				}
			},
			splitLine: {
				show: true,
				lineStyle: {
					color: ['#c6c6c6']
				}
			}
		},
		series: data.value.data
	}
}
// 观察 data ，重新绘制
watch(data, (newValue) => {
    getOption();
},{ deep: true });
watch(option, (newValue) => {
    echartInstance.setOption(newValue, true);
},{ deep: true });
onMounted(() => {
	nextTick(()=>{
		echartInstance = echarts.init(document.getElementsByClassName(name.value)[0]);
		getOption();
		// echartInstance.setOption(option.value, true);
	})
});

function resize() {
	echartInstance.resize();
}

// 暴露函数 （供hook调用）
defineExpose({
  resize,
});

useResize();
</script>