<template>
	<div style="display: flex;flex: 1;">
		<el-popover
			placement="top"
			popper-class="input-area-popover"
			class="string-input-container"
			trigger="manual"
			width="400"
			v-model="popoverVisible"
			:disabled="!editable"
		>
			<div>
				<el-input
					type="textarea"
					v-model="popoverEditValue"
					:placeholder="defaultValue"
					:rows="6"
				>
				</el-input>
				<div class="bottom-bar">
					<el-button @click="onClean" type="danger" plain>Clean</el-button>
					<el-button-group>
						<el-button @click="onCancel" plain>Cancel</el-button>
						<el-button @click="onConfirm" type="primary" plain>Confirm</el-button>
					</el-button-group>
				</div>
			</div>
			<el-input clearable slot="reference" :value="editValue" @input="onInput" @change="onChange" :readonly="!editable"
			          :placeholder="defaultValue"/>
		</el-popover>
		<el-button-group>
			<el-button :icon="editButtonIcon" @click="onClickEdit" :disabled="!editable"></el-button>
			<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";

	export default {
		name: "StringInput",
		components: {LinkableInputWrapper, CmdInputWrapper},
		props: ['value', 'container', 'property', 'propertyName', 'editable'],
		data() {
			return {
				editValueOrigin: this.value,
				popoverEditValue: this.value,
				popoverVisible: false,
			}
		},
		computed: {
			editValue() {
				return this.editable ? this.editValueOrigin : '';
			},
			editButtonIcon() {
				return this.popoverVisible ? 'el-icon-check' : 'el-icon-edit';
			},
			defaultValue() {
				return getInputDefaultValue(this.property);
			},
		},
		watch: {
			value(v) {
				this.editValueOrigin = v;
			},
			popoverVisible(v) {
				if (v) {
					this.popoverEditValue = this.editValue;
				}
			}
		},
		methods: {
			onClickEdit() {
				this.popoverVisible = !this.popoverVisible;
			},
			onClickClean() {
				this.$emit('input', undefined, this.container, this.propertyName, this.value);
			},
			onInput(v) {
				this.editValueOrigin = v;
			},
			onChange() {
				this.$emit('input', this.editValue, this.container, this.propertyName, this.value);
			},
			onConfirm() {
				this.editValueOrigin = this.popoverEditValue;
				this.onChange();
				this.popoverVisible = false;
			},
			onCancel() {
				this.$emit('cancel');
				this.popoverVisible = false;
			},
			onClean() {
				this.popoverEditValue = '';
			},
		},
	}
</script>

<style scoped>
	.bottom-bar {
		margin-top: 5px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
</style>
