<template>
	<el-select class="w100p" :model-value="valueSync" :multiple="multiple" :placeholder="placeholder"
	           @change="_onChange" :clearable="clearable" :disabled="disabled" :filterable="filterable">

		<el-option v-for="(item,index) in list" :key="index" :value="item[valueKey]" :label="item[labelKey]"></el-option>

	</el-select>
</template>

<script>
	export default {
		name: "st-select",
		emits: ["change", "update:modelValue"],
		props: {
			modelValue: [String, Number, Array, Boolean],
			defaultValue: {
				type: [String, Number, Array, Boolean],
				default: ""
			},
			defaultIndex: {
				type: Number,
				default: -1
			},
			multiple: Boolean,
			clearable: {
				type: Boolean,
				default: true
			},
			placeholder: String,
			list: {
				type: Array,
				default() {
					return []
				}
			},
			labelKey: {
				type: String,
				default() {
					return "label";
				}
			},
			valueKey: {
				type: String,
				default() {
					return "value";
				}
			},
			disabled : Boolean,
			filterable : {
				type : Boolean,
				default : true
			}
		},
		data() {
			return {
				valueSync: this._getValue()
			}
		},
		watch: {
			modelValue() {
				this.valueSync = this._getValue();
			}
		},
		methods: {
			_getValue() {
				if (this.modelValue !== undefined) return this.modelValue;
				if (this.defaultIndex > -1 && this.list.length > 0 && this.modelValue === undefined) {
					let index = this.defaultIndex > this.list.length - 1 ? 0 : this.defaultIndex ;
					let firstValue = this.list[index][this.valueKey];
					let value = this.multiple ? [firstValue] : firstValue;
					this.$emit("update:modelValue", value);
					return value ;
				}
				return this.defaultValue;
			},
			_onChange(value) {
				this.valueSync = value;
				this.$emit("update:modelValue", value);
				this.$emit("change", value);
			}
		}
	}
</script>