<template>
	<el-select ref="selectRef" v-model="defaultValue" :size="size" :clearable="clearable" :multiple="multiple"
			   :collapse-tags="collapseTags" :collapse-tags-tooltip="collapseTagsTooltip" :filterable="filterable"
			   :placeholder="placeholder" :disabled="disabled">
		<el-option v-for="(item, index) in tableData" :key="index" :label="item[defaultProps.label]"
				   :value="item[defaultProps.value]"></el-option>
	</el-select>
</template>

<script setup>
import config from '@/config/select'
import {ref, watch, onMounted} from 'vue'

const emit = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
	modelValue: null,
	apiObj: {
		type: Function, default: () => {
		}
	},
	params: {
		type: Object, default: () => {
		}
	},
	placeholder: {type: String, default: "请选择"},
	size: {type: String, default: "default"},
	clearable: {type: Boolean, default: false},
	multiple: {type: Boolean, default: false},
	filterable: {type: Boolean, default: false},
	collapseTags: {type: Boolean, default: false},
	collapseTagsTooltip: {type: Boolean, default: false},
	disabled: {type: Boolean, default: false},
	props: {
		type: Object, default: () => {
		}
	}
})

const selectRef = ref(null)
let loading = ref(false)
let defaultValue = ref([])
let defaultProps = ref({
	label: config.props.label,
	value: config.props.value
})
let tableData = ref([])

watch(() => props.modelValue, (val) => {
	defaultValue.value = val
}, {deep: true, immediate: true})

watch(defaultValue, () => {
	emit('update:modelValue', defaultValue.value)
	emit('change', defaultValue.value)
})

onMounted(() => {
	getData()
	defaultProps.value = Object.assign(defaultProps.value, props.props);
	defaultValue.value = props.modelValue
})

async function getData() {
	loading.value = true;
	const res = await props.apiObj(props.params);
	tableData.value = res.data;
	loading.value = false;
}
</script>

<style scoped>

</style>
