<template>
	<el-select v-model="selected" :placeholder="placeholder" :filterable="canFilter">
		<el-option v-for="item in ops" :key="item.value" :label="item.name" :value="item.value">
		</el-option>
	</el-select>
</template>
<script>
export default {
	name: "sg-selector",
	props: ['default', 'type', 'placeholder', 'param', 'filterable', 'hasAll'],
	data() {
		let defaultV = "";
		if (this.default) {
			defaultV = this.default;
		}
		return {
			loaded: false,
			canFilter: this.filterable ? true : false,
			selected: defaultV,
			ops: []
		}
	},
	methods: {
		init() {
			let vm = this;
			vm.ops = [];
			if (vm.hasAll) {
				vm.ops.push({name: "全部", value: 'all'});
			}
			vm.postJson("/server/common/component/selector", { type: vm.type, param: vm.param }, (resp) => {
				if (vm.selected === '' && resp.selectedValue) {
					vm.selected = resp.selectedValue;
				}
				if(resp.options){
					resp.options.forEach((item)=>{
						vm.ops.push(item);
					});
				}
				if(vm.selected === '' && vm.ops[0]){
					vm.selected = vm.ops[0].value;
				}
			});
		}
	},
	created: function() {
		this.init();
		if (this.defautl === undefined) {
			return false;
		}
		this.$emit("changed", this.default);
	},
	watch: {
		selected: function(n, o) {
			if (!n || n === undefined) {
				return false;
			}
			if (n && o && n === o) {
				return false;
			}
			this.$emit("changed", n);
		},
		param: function(n, o) {
			if (n && o && n === o) {
				return false;
			}
			this.selected = "";
			this.init();
		}
	}
}

</script>
