<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

let echart;
let echartInstance;

const props = defineProps({
  // 数据
  data: {
    type: Object,
    default: {
		xAxis: [],
		data:[],
		yname: "",
		xname: ""
	}
  },
  // 高度
  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'
		},
		legend: {
			show: data.value.data.length>1?true:false,
			textStyle: {
				color: "#000"
			}
		},
		grid: {
			top: data.value.yname.length?30:'4%',
			left: data.value.yname.length?'8%':'2%',
			right: data.value.xname.length?'12%':'2%',
			bottom: '4%',
			containLabel: true
		},
		xAxis: {
			name: data.value.xname,
			type: 'category',
			boundaryGap: true,
			splitLine: {
				show: false,
				lineStyle: {
					color: '#c6c6c6'
				}
			},
			axisLabel: {
				show: false,
				fontSize: 12,
				color:"#323232",
				showMaxLabel: true
			},
			data: data.value.xAxis
		},
		yAxis: {
			name: data.value.yname,
			type: 'value',
			axisLabel: {
				show: false,
				fontSize: 12,
				color:"#323232",
				showMaxLabel: true
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: ['#323232']
				}
			},
			splitLine: {
				show: false,
				lineStyle: {
					color: ['#c6c6c6']
				}
			}
		},
		series: data.value.data
	}
});

const { option } = toRefs(data1);

// 观察 data ，重新绘制
watch(data, (newValue) => {
    option.value.series = newValue.data;
},{ deep: true });
watch(option, (newValue) => {
    echartInstance.setOption(newValue, true);
},{ deep: true });
onMounted(() => {
	nextTick(()=>{
		echartInstance = echarts.init(document.getElementsByClassName(name.value)[0]);
		echartInstance.setOption(option.value, true);
	})
});

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

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

useResize();
</script>