<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: Array,
		default: [{
			name: '离线',
			value: [0,0, 0,0],
			itemStyle: {
				color: "#d80000"
			}
		}]
	},
	// 高度
	height: {
		type: [Number, String],
		default: "300px",
	},
	// 宽度
	width: {
		type: [Number, String],
		default: "100%",
	},
	name: {
		type: String,
		default: 'echart'
	}
});

const { data, name, height, width } = toRefs(props);
const option = ref({});
const formatterDate = function(tt) {
	return proxy.parseTime(new Date(tt),`{y}-{m}-{d} {h}:{i}:{s}`)
}

function renderItem(params, api){
	var categoryIndex = api.value(0);
	var start = api.coord([api.value(1),categoryIndex]);
	var end = api.coord([api.value(2),categoryIndex]);
	var height = api.size([0,1])[1]* 0.6;
	var rectShape = echarts.graphic.clipRectByRect({
		x: start[0],
		y: start[1] - height/2,
		width: end[0] - start[0],
		height: height,
	},{
		x: params.coordSys.x,
		y: params.coordSys.y,
		width: params.coordSys.width,
		height: params.coordSys.height,
	});
	return (
		rectShape && {
			type: 'rect',
			transition: ['shape'],
			shape: rectShape,
			style: api.style()
		}
	)
};
function getOption(){
	option.value = {
		tooltip:{
			formatter:function(params){
				return (params.marker +
						params.name +
						":"+
						formatterDate(params.value[1]*1000)+
						"至"+
						formatterDate(params.value[2]*1000)
					);
			},
		},
		grid: {
			top: '2%',
			left: '1%',
			right: '1%',
			bottom: '2%',
			containLabel: true
		},
		// dataZoom: [{
			// type: 'inside'
	    // },{
			// type: 'slider'
	    // }],
		xAxis: {
			min: data.value[0].value[1],
			max: (data.value[0].value[1]+60*60*24),
			type: "time",
			splitNumber: 0,
			scale: true,
			axisLabel:{
				formatter: function(val){
					return proxy.parseTime(new Date(val*1000),`{h}:{i}:{s}`);
				}
			}
		},	
		yAxis:{
			data: []
		},
		series:[{
			type:'custom',
			renderItem: renderItem,
			itemstyle: {
				opacity: 0.6
			},
			encode: {
				x: [1, 2],
				y: 0
			},
			data: data.value
		}]
	}
}

// 观察 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();
	})
});

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

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

useResize();
</script>