<template>
	<div class="editor">
		<div class="editor" id="editor"></div>
	</div>
</template>

<script>
let editor;
let jsbOpts = {
	indent_size: 4
}
export default {
	name: "Editor",
	props: {
		info: Object
	},
	created() {
		this.createScript();
	},
	methods: {
		// 创建editor插件的script标签
		createScript() {
			const scriptList = Array.from(document.getElementsByTagName('script'));
			let list = [
				'https://cdn.bootcdn.net/ajax/libs/ace/test/ace.js',
				'https://cdn.bootcdn.net/ajax/libs/ace/test/ext-language_tools.min.js',
				`${process.env.BASE_URL}lib/js-beautify.js`
			];
			let count = 0;
			creater.bind(this)(list);

			function creater(param) {
				for (let item of param) {
					if (!scriptList.find(item => item.src === item)) {
						let srcipts = document.createElement('script');
						srcipts.src = item;
						srcipts.onload = checker.bind(this);
						document.body.appendChild(srcipts);
					} else {
						checker.bind(this);
					}
				}
			}

			function checker() {
				count++;
				if (count === list.length) {
					this.onScriptReady()
				}
			}
		},
		// editor插件加载完毕后执行
		onScriptReady() {
			editor = ace.edit("editor", {
				theme: "ace/theme/monokai",
				mode: "ace/mode/javascript",
				selectionStyle: "text",
				autoScrollEditorIntoView: true,
				enableBasicAutocompletion: true,
				enableSnippets: true,
				enableLiveAutocompletion: true,
				fontSize: 18
			});
			window.editor = editor;
			editor.insert(this.info.content);
			console.log(editor);
			const keyboardHandler = event => {
				const session = editor.getSession();
				if (event.ctrlKey && event.shiftKey && event.key === 'F') {
					session.setValue(beautifier.js(session.getValue(), jsbOpts));
				}
			};
			document.addEventListener('keydown', keyboardHandler);
			this.$once('hook:beforeDestroy', () => {
				document.removeEventListener('keydown', keyboardHandler);
			})
		},
	},
}
</script>

<style scoped lang="scss">
.editor {
	width: 1300px;
	height: 768px;
}
</style>
