<template>
	<div class="tool-bar">
		<sample-menu :data="menu" @click-menu="clickMenu"/>
		<div class="right-part">
			<span>
				[{{project.name}}]
				<el-button size="mini" class="micro" circle icon="el-icon-edit" @click="editProjectName"/>
				<el-button size="mini" class="micro" circle icon="el-icon-notebook-2" @click="editRemark"/>
			</span>
		</div>
		<project-remark-dialog ref="projectRemarkDialog"/>
	</div>
</template>

<script>
	import {mapState, mapActions, mapMutations} from 'vuex'
	import SampleMenu from "../../components/SampleMenu";
	import ProjectRemarkDialog from "./dialogs/ProjectRemarkDialog";

	export default {
		name: "ToolBar",
		components: {ProjectRemarkDialog, SampleMenu},
		data() {
			return {}
		},
		computed: {
			...mapState([
				'project'
			]),
			menu: function () {
				const menuConfig = this.$t('menu');
				let menu = {};
				for (let key of Object.keys(menuConfig)) {
					let {label, icon, sub} = menuConfig[key];
					menu[key] = {label, icon, sub, disabled: false}
				}
				if (menu['undo']) {
					menu['undo']['disabled'] = !this.project.operateStack.length || this.project.operateStack.length === this.project.stackIndex + 1
				}
				if (menu['redo']) {
					menu['redo']['disabled'] = this.project.stackIndex === 0;
				}
				return menu;
			}
		},

		async mounted() {
			//监听键盘事件
			//document.addEventListener('keydown', this.onKeyPress);
		},
		methods: {
			clickMenu(menuItem) {
				this.$emit('click-menu', menuItem);
			},
			editProjectName() {
				this.$prompt(this.$t('Input project name'), this.$t('Rename project'), {
					inputValue: this.project.name,
					confirmButtonText: this.$t('Confirm'),
					cancelButtonText: this.$t('Cancel'),
					closeOnClickModal: false,
					inputPattern: /^.{1,64}$/,
					inputErrorMessage: this.$t('Invalid project name'),
				}).then(({value}) => {
					this.$set(this.project, 'name', value);
					this.modifyProject();
				}).catch(() => {
				});
			},
			editRemark() {
				this.$refs.projectRemarkDialog.show();
			},
			onKeyPress(e) {
				if (e.key === 'z' && (e.ctrlKey || e.metaKey) && (!e.shiftKey)) {
					//快捷键ctrl+z执行撤销
					e.preventDefault();
					//是否可执行撤销
					if (!(!this.project.operateStack.length || this.project.operateStack.length === this.project.stackIndex + 1)) {
						this.clickMenu("undo");
					}
					return false;
				} else if (e.key === 'z' && (e.ctrlKey || e.metaKey) && (e.shiftKey)) {
					//快捷键ctrl+shift+z执行重做
					e.preventDefault();
					//是否可以执行重做
					if (!(this.project.stackIndex === 0)) {
						this.clickMenu("redo");
					}
					return false;
				}
			},
			...mapMutations([
				'modifyProject'
			]),
		}
	}
</script>

<style scoped>

</style>