<template>
	<div class="zero-inspector-behavior" v-if="activeComponent.uuid">
		<el-dropdown trigger="click" size="mini" @command="addTrigger" class="add-trigger">
			<el-link icon="el-icon-plus">添加触发</el-link>
			<el-dropdown-menu slot="dropdown">
				<el-dropdown-item :disabled="!!activeComponent.events[key]" v-for="(item, key) in builtinEvents" :command="key"
				                  :key="key">{{item}}
				</el-dropdown-item>
				<el-dropdown-item divided command="custom-global">{{$t('Custom global event')}}</el-dropdown-item>
				<el-dropdown-item command="custom-private">{{$t('Custom private event')}}</el-dropdown-item>
			</el-dropdown-menu>
		</el-dropdown>
		<el-scrollbar class="scrollbar" wrap-class="wrap-x-hidden" view-class="trigger-list">
			<div class="trigger-item" v-for="(trigger, name, index) in activeComponent.events" :key="index">
				<div class="top-bar">
					<span class="el-icon-caret-right el-tree-node__expand-icon expanded-arrow"
					      :class="{expanded: !trigger.collapse}"></span>
					<el-icon v-if="trigger.custom" :name="trigger.private ? 's-opportunity' : 's-home'"></el-icon>
					<span class="name" @click="toggleCollapse(trigger)">
						{{$t('events')[name] || name}}({{trigger.behaviors.length}})
					</span>
					<el-dropdown trigger="click" size="mini" @command="command=>clickTriggerMore(command, trigger, name, index)">
						<el-link icon="el-icon-more" :underline="false"></el-link>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item icon="el-icon-plus" command="addBehavior">{{$t('Add behavior')}}</el-dropdown-item>
							<el-dropdown-item icon="el-icon-edit" command="editTrigger" :disabled="!trigger.custom" divided>{{$t('Edit trigger')}}
							</el-dropdown-item>
							<el-dropdown-item icon="el-icon-minus" command="deleteTrigger" :disabled="trigger.behaviors.length > 0">
								{{$t('Delete trigger')}}
							</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</div>
				<el-collapse-transition>
					<div class="behavior-list" v-show="!trigger.collapse">
						<div v-for="(behavior, index) in trigger.behaviors" class="behavior-item">
							<enabled-setter :target="behavior"/>
							<span v-if="!getBehavior(behavior)" class="name-field missing-behavior">{{$t('Missing behavior')}}</span>
							<input v-else class="name-field name-input" type="text" v-model="getBehavior(behavior).name"
							       @change="onBehaviorNameChange"></input>

							<el-popconfirm class="delete-button" @onConfirm="deleteBehavior(index, trigger.behaviors)"
							               :title="$t('Are you sure to delete this behavior?')">
								<el-button slot="reference" icon="el-icon-minus" type="danger" plain circle size="mini"/>
							</el-popconfirm>
							<el-button icon="el-icon-edit" class="edit-button" type="primary" plain circle size="mini"
							           @click="editBehavior(behavior, trigger.behaviors)"/>
						</div>
					</div>
				</el-collapse-transition>
			</div>
		</el-scrollbar>
	</div>
</template>

<script>
	import {mapGetters, mapActions, mapMutations} from 'vuex';
	import events from "@/global-events.js"
	import EnabledSetter from "../components/EnabledSetter";

	export default {
		name: "BehaviorTab",
		components: {EnabledSetter},
		data() {
			const builtinEvents = this.$t('events');
			return {
				builtinEvents,
			}
		},
		watch: {
			'activeComponent.uuid': function () {
				this.updateEvents();
			}
		},
		computed: {
			...mapGetters(['activeComponent', 'componentList', 'behaviorEditable'])
		},
		methods: {
			getBehavior(behavior) {
				let process = this.$store.getters.getProcess(behavior);
				if (!process) {
					console.warn('missing process:', behavior.meta);
				}
				return process;
			},
			updateEvents() {
				if (!this.activeComponent.events) {
					this.$set(this.activeComponent, 'events', {});
				}
			},
			addTrigger(command) {
				if(this.behaviorEditable()){
					let trigger = {behaviors: []};
					switch (command) {
						case 'custom-global':
						case 'custom-private':
							trigger.custom = true;
							break;
					}

					if (command === 'custom-private') {
						trigger.private = true;
					}

					this.addBehavior(command, trigger.behaviors);
					this.$set(this.activeComponent.events, command, trigger);
				}else{
					this.$message('独立过程编辑器正在使用中，不可编辑')
				}
			},
			toggleCollapse(trigger) {
				this.$set(trigger, 'collapse', !trigger.collapse);
			},
			clickTriggerMore(command, trigger, name, index) {
				switch (command) {
					case 'addBehavior':
						this.addBehavior(name, trigger.behaviors);
						this.$set(trigger, 'collapse', false);
						break;
					case 'editTrigger':
						this.editTriggerName(name);
						break;
					case 'deleteTrigger':
						this.deleteTrigger(name);
						break;
				}
			},
			addBehavior(eventName, behaviors) {
				if(this.behaviorEditable()){
					const alias = `${this.activeComponent.name}_${eventName}` + (behaviors.length > 0 ? '_' + (behaviors.length + 1) : '');

					this.addBehaviorDirect({
						alias, behaviors,
					});

					this.makeProjectDirty();
				}else{
					this.$message('独立过程编辑器正在使用中，不可编辑')
				}
			},
			editTriggerName(name) {
				this.$prompt(this.$t('Input event name'), this.$t('Rename event'), {
					inputValue: name,
					confirmButtonText: this.$t('Confirm'),
					cancelButtonText: this.$t('Cancel'),
					closeOnClickModal: false,
					inputPattern: /^.{1,256}$/,
					inputErrorMessage: this.$t('Invalid event name'),
				}).then(({value}) => {
					if (name !== value) {
						const events = this.activeComponent.events;
						if (events.hasOwnProperty(value)) {
							this.$alert(this.$t('Event name exists'))
						} else if (this.builtinEvents.hasOwnProperty(value)) {
							this.$alert(this.$t('Builtin event should add directly'))
						} else {
							this.$set(events, value, events[name]);
							this.$delete(events, name);

							this.makeProjectDirty();
						}
					}
				}).catch(() => {
				});
			},
			deleteTrigger(name) {
				this.$delete(this.activeComponent.events, name);

				this.makeProjectDirty();
			},
			editBehavior(behavior, behaviors) {
				events.$emit('edit-behavior', [{process: behavior}]);
			},
			onBehaviorNameChange() {
				this.makeProjectDirty();
			},
			async deleteBehavior(index, behaviors) {
				if(this.behaviorEditable()){
					let deleteMeta = false;
					await this.$confirm(this.$t('Are you sure to delete it\'s process?'), this.$t('Alert'), {
						confirmButtonText: this.$t('Delete'),
						cancelButtonText: this.$t('Not delete'),
						distinguishCancelAndClose: true,
						type: 'warning'
					}).then(() => {
						deleteMeta = true;
						this.makeProjectDirty();
					}).catch(action => {

					});

					this.deleteBehaviorDirect({
						behaviors,
						index,
						deleteMeta,
					})
				}else{
					this.$message('独立过程编辑器正在使用中，不可编辑')
				}

			},
			...mapActions([
				'modifyActiveView',
				'getProcess',
				'addBehaviorDirect',
				'deleteBehaviorDirect',
			]),
			...mapMutations([
				'makeProjectDirty',
			]),
		}
	}
</script>

<style scoped lang="scss">
</style>