<template>
	<div class="process-editor-dialog">
		<div class="editor-wrapper">
			<behavior-editor v-if="editorReady" ref="behaviorEditor" class="behavior-editor"></behavior-editor>
		</div>
		<div class="bottom-bar">
			<div>

			</div>
			<div class="gap-5">
				<el-button size="mini" type="danger" @click="onClose()">{{$t('Close')}}</el-button>
				<el-badge :hidden="!showBadge" is-dot>
					<el-button size="mini" type="primary" @click="onSave()">{{$t('Save')}}</el-button>
				</el-badge>
			</div>
		</div>
	</div>
</template>

<script>
	import {mapMutations, mapState, mapGetters} from 'vuex'
	import BehaviorEditor from "./Editor/behavior-editor/BehaviorEditor";
	import {clonePureObj} from "../utils";

	export default {
		name: "ProcessEditor",
		components: {BehaviorEditor},
		data() {
			return {
				editorReady: false,
			}
		},
		mounted() {
			window.reset = ({projectData, packageState}) => {
				console.log('reset');
				this.resetProjectData(projectData);
				this.resetPackageStore(packageState);
			};
			window.editable = () => {
				return !this.showBadge;
			};
			window.edit = (path, index) => {
				this.edit(path, index);
			};
			window.onbeforeunload = (e) => {
				return this.showBadge ? true : null;
			};
			this.updateProcessTree();
		},
		computed: {
			...mapState({
				showBadge: state => state.behavior.dirty,
			}),
			...mapGetters(['processesInEditor'])
		},
		methods: {
			edit(path, index) {
				this.path = path;
				this.index = index;
				this.editorReady = true;

				this.$nextTick(this.startEdit);
			},
			startEdit() {
				this.$refs.behaviorEditor.edit(this.path, this.index);
			},
			async onSave() {
				let opener;
				try {
					if (window.opener && window.opener.saveProcesses) {
						opener = window.opener;
					}
				} catch (e) {
				}
				if (opener) {
					let processes = clonePureObj(this.processesInEditor);
					window.opener.saveProcesses(processes);
					this.clearBehavior();
					/*this.$message({
						message: this.$t('Save behavior successfully'),
						type: 'success'
					});*/
				} else {
					this.$alert(this.$t('The main editor is closed and cannot be saved'));
				}
			},
			onClose() {
				if (this.showBadge) {
					this.$confirm(this.$t('Save this behavior before'), this.$t('Alert'), {
						closeOnClickModal: false,
						closeOnPressEscape: false,
						confirmButtonText: this.$t('Save And Close'),
						cancelButtonText: this.$t('Still Close'),
						distinguishCancelAndClose: true,
						type: 'warning'
					}).then(() => {
						this.onSave();
						this.close();
					}).catch((action) => {
						switch (action) {
							case 'close':
								break;
							case 'cancel':
								this.close();
								break;
						}
					});
				} else {
					this.close();
				}
			},
			close() {
				window.close();
			},
			...mapMutations(['clearBehavior',
				'resetProjectData', 'resetPackageStore', 'behavior_save', 'updateProcessTree'])
		}
	}
</script>

<style scoped>

</style>