<template>
	<div style="display: flex;flex: 1;">
		<el-popover
			popper-class="input-area-popover"
			class="string-input-container"
			trigger="manual"
			v-model="popoverVisible"
			:disabled="!editable"
			:width="400"
		>
			<div v-if="editValue" class="mapping-list">
				<el-button class="add-button" icon="el-icon-plus" size="mini" circle @click="addMapItem"/>
				<div class="list">
					<div class="item" v-for="(item, index) in editValue" :key="index">
						<el-input v-model="item.key" style="width: unset"/>
						:
						<dynamic-selector style="flex: 1;" v-model="item.value"
						                  :editable="editable"/>
						<el-button class="delete-button" icon="el-icon-minus" size="mini" plain circle type="danger"
						           @click="deleteMapItem(index)"/>
					</div>
				</div>
				<div class="bottom-bar">
					<el-button size="mini" type="primary" @click="close">{{$t('Close')}}</el-button>
					<el-button size="mini" type="primary" @click="save">{{$t('Save')}}</el-button>
				</div>
			</div>
			<el-button slot="reference" @click="onClickEdit" :disabled="!editable">{{$t('Edit')}}</el-button>
		</el-popover>
		<el-button-group>
			<el-button icon="el-icon-delete" @click="onClickClean" :disabled="!editable"></el-button>
		</el-button-group>
	</div>
</template>

<script>
	import LinkableInputWrapper from "./LinkableInputWrapper";
	import CmdInputWrapper from "./CmdInputWrapper";
	import {getInputDefaultValue} from "../../utils";
	import DynamicSelector from "./DynamicSelector";

	export default {
		name: "MapInput",
		components: {DynamicSelector, LinkableInputWrapper, CmdInputWrapper},
		props: ['value', 'container', 'property', 'propertyName', 'editable'],
		data() {
			let dataTypes = this.$t('dataTypes');
			return {
				editValue: null,
				popoverEditValue: this.value,
				popoverVisible: false,
				dataTypes,
			}
		},
		computed: {
			defaultValue() {
				return getInputDefaultValue(this.property);
			},
		},
		watch: {
			value(v) {

			},
		},
		methods: {
			transEditValue() {
				let arr = [];
				if (this.value && this.value.value) {
					let v = this.value.value;
					for (let key in v) {
						arr.push({key, value: v[key]});
					}
				}
				return arr;
			},
			onClickEdit() {
				this.editValue = this.transEditValue();
				this.popoverVisible = !this.popoverVisible;
			},
			onClickClean() {
				this.$emit('input', undefined, this.container, this.propertyName, this.value);
			},
			addMapItem() {
				this.editValue.push({});
			},
			deleteMapItem(index) {
				this.editValue.splice(index, 1);
			},
			save() {
				let v = {type: 'map', value: {}};
				for (let item of this.editValue) {
					v.value[item.key] = item.value;
				}
				this.$emit('input', v, this.container, this.propertyName, this.value);
				this.popoverVisible = false;
			},
			close() {
				this.popoverVisible = false;
			}
		},
	}
</script>

<style scoped>

</style>
