<template>
	<div style="flex: 1; display: flex;">
		<el-input-number :disabled="!editable" :value="editValue" @change="onInput" controls-position="right"
		                 :placeholder="defaultValue">
		</el-input-number>
		<span @click="onClickPercent" v-if="config && config.percent"
		      style="position: absolute; right: 42px; cursor: pointer"
		      :class="{'percent-on': isPercent, 'percent-off': !isPercent}">%</span>
	</div>
</template>

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

	export default {
		name: "NumberInput",
		components: {LinkableInputWrapper, CmdInputWrapper},
		props: ['value', 'container', 'property', 'propertyName', 'editable', 'config'],
		data() {
			return {
				isPercent: false,
				editValue: null
			}
		},
		computed: {
			/*editValue() {
				let v = this.value;
				if (v === undefined) {
					this.isPercent = false;
					return this.property.default?this.property.default:undefined;
				} else {
					this.isPercent = typeof v === 'string';
					if(typeof v === 'string'){
						v = parseInt(v);
					}
					return v;
				}
			},*/
			defaultValue() {
				return getInputDefaultValue(this.property);
			},
		},
		mounted() {
			this.updateValue()
		},
		methods: {
			updateValue() {
				if (this.container.hasOwnProperty('_' + this.propertyName)) {
					if (this.container['_' + this.propertyName]) {
						this.editValue = this.container['_' + this.propertyName];

					} else {
						this.editValue = undefined;
					}
				} else if (this.propertyName.indexOf("_") != -1) {
					if (this.container[this.propertyName]) {
						this.editValue = this.container[this.propertyName]
					} else {
						this.editValue = undefined;
					}
				} else {
					let v = this.value;
					if (v === undefined) {
						this.isPercent = false;
						this.editValue = this.property.default ? this.property.default : undefined;
					} else {
						this.isPercent = typeof v === 'string';
						if (typeof v === 'string') {
							v = parseFloat(v);
						}
						this.editValue = v;
					}
					//this.editValue = this.value === undefined ? this.property.default : this.value;
				}
			},
			onInput(v) {
				//if (v !== this.value) {
					let value;
					if (this.isPercent) {
						if (!v && v !== 0) {
							value = undefined;
						} else {
							value = v + '%';
						}
					} else {
						value = parseFloat(v);
					}
					this.$emit('input', value, this.container, this.propertyName, this.value);
				//}
			},
			onClickPercent() {
				this.isPercent = !this.isPercent;
				this.onInput(this.value);
			},
		},
		watch: {
			value(v) {
				this.updateValue()
			}
		}
	}
</script>

<style scoped>

</style>
