<template>
	<div ref="el" :id="id" class="Echarts" :style="{width,height}" v-if="id"></div>
</template>
<script setup>
import { nextTick, onMounted, ref, useAttrs, watch } from "vue";

import * as echarts from "echarts";

const emits = defineEmits(['load']);
const props = defineProps({
	id:{type:String,required:true},
	width:{type:String,default:'100%'},
	height:{type:String,default:'100%'},
	options:{type:Object,required:true},
});
const attrs = useAttrs();
const el = ref(null);
let Ecs = undefined;

onMounted(()=>{
	// ready();
	let resizeFn = debounce(resize);
	window.addEventListener('resize',resizeFn,false);
	init();
	emits('load',Ecs);
	bindEvent(attrs);
});


// function ready(){
// 	loadScript('https://cdn.jsdelivr.net/npm/echarts@5.3.0/dist/echarts.min.js','loadScript_echarts').then(reg=>{
// 		let resizeFn = debounce(resize);
// 		window.addEventListener('resize',resizeFn,false);
// 		init();
// 		emits('load',Ecs);
// 		bindEvent(attrs);
// 	}).catch(err=>{})
// }

function init(){
	try{
		Ecs = echarts.init(el.value);
		Ecs.setOption(props.options,true);
	}catch(err){
		console.log(echarts,props.id);
	}
}
function bindEvent(attrs){
	Object.keys(attrs).filter(v=>v.indexOf('ecs-') === 0).forEach(item=>{
		Ecs.on(item.slice(4),attrs[item])
	})
}

function resize(){
	Ecs && Ecs.resize();
}
function debounce(fn,time=200,type=1){
	let timeout;
	return function(){
		let context = this;
		let args = arguments;
		if(timeout){ clearTimeout(timeout); }
		if(type === 1){
			let callNow = !timeout;
			timeout = setTimeout(()=>{ timeout = null; },time);
			if(callNow){ fn.apply(context,args); }
		} else if(type === 2) {
			timeout = setTimeout(function(){ fn.apply(context,args); },time)
		}
	}
}

function loadScript(url,id){
	let head = document.getElementsByTagName('head')[0];
	let js = document.getElementById(id);
	if(id && js && js.getAttribute('ready')){ return Promise.resolve(false); }
	js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', url);

	id && js.setAttribute('id', id);

	return new Promise((resolve, reject) => {
		function onLoad() {
			js.setAttribute('ready', 'true');
			resolve(true);	
			js.removeEventListener('load', onLoad);
		}
		function onError(e) {
			reject(e);
			js.removeEventListener('error', onError);
		}
		js.addEventListener('load', onLoad);
		js.addEventListener('error', onError);
		head.appendChild(js);
	});
}

</script>