function getUrlParameter (name) {
	const url = window.location.href;
	const urlObj = new URL(url);
	const params = new URLSearchParams(urlObj.search);
	return params.get(name);
}

const url = window.$website.url + '/component'
function showLoader () {
	const loader = document.createElement('div');
	loader.id = 'loader';

	const message = document.createElement('div');
	message.className = 'loader-message';
	message.innerText = '加载中...';

	loader.appendChild(message);
	document.body.appendChild(loader);

	// 显示遮罩
	loader.style.display = 'flex';

}

function closeLoader () {
	const loader = document.getElementById('loader');
	if (loader) {
		loader.style.display = 'none';
		document.body.removeChild(loader);
	}
}
const getObj = (id) => axios({
	url: url + '/detail',
	method: 'get',
	params: {
		id
	}
});

const updateObj = (data) => axios({
	url: url + '/update',
	method: 'post',
	data: data
});

window.$AvueData = function (editor) {
	const id = getUrlParameter('id');
	editor.clear()
	function AvueData (id, editor) {
		this.editor = editor;
		this.id = id;
		this.save = (json) => {
			showLoader()
			updateObj({
				id: this.id,
				content: JSON.stringify(json)
			}).then(res => {
				closeLoader()
				alert('保存成功')
			})
		}
		this.load = () => {
			showLoader()
			getObj(this.id).then(res => {
				closeLoader()
				try {
					const json = JSON.parse(res.data.data.content);
					function onEditorCleared () {
						this.editor.fromJSON(json);
						this.editor.signals.editorCleared.remove(onEditorCleared);
					}
					this.editor.signals.editorCleared.add(onEditorCleared);
					this.editor.clear();
				} catch (e) {
					this.editor.clear()
					console.error(e);

				}
			})
			return this
		}
		return this;
	}
	return new AvueData(id, editor)
}