<template>
	<a-select v-model:value="selectValue" show-search label-in-value :placeholder="placeholder" style="width: 100%"
		:filter-option="false" :not-found-content="fetching ? undefined : null" :options="listOptions"
		@search="searchList" @change="searchChange" :disabled="selectDisabled" :mode="mode">
		<template v-if="fetching" #notFoundContent>
			<a-spin size="small" />
		</template>
	</a-select>
</template>
<script lang="ts" setup>
	import { ref, onMounted, defineProps, watch, defineEmits } from 'vue';
	import { getCompanyList } from '@/apis/models';
	import { debounce } from 'lodash-es';
	const emit = defineEmits();
	const props = defineProps(
	{
		list: Array,
		placeholder: String,
		select_value: Number,
		select_disabled: {
			type: Boolean,
			default: false
		},
		mode: {
			type: String,
			default: ''
		}
	});
	let listOptions = ref([]);
	let fetching = ref(false);
	let placeholder = ref<String>(props.placeholder);
	let selectValue = ref<String>('');
	let lastFetchId = 0;
	let selectDisabled = ref<Boolean>(false)
	let mode = ref<String>(props.mode)
	watch(() => [props.list,  props.select_value, props.select_disabled],
		(newVal, oldVal) => {
			listOptions.value = newVal[0]
			selectValue.value = newVal[1] ? newVal[1] : null;
			selectDisabled.value = newVal[2];
			mode.value = newVal[3]
		}, { immediate: true })

	
	const searchList = debounce(value => {
		lastFetchId += 1;
		const fetchId = lastFetchId;
		listOptions.value = [];
		fetching.value = true;
		emit('searchData', {keyword: value});
		if (fetchId !== lastFetchId) {
			return;
		}
		fetching.value = false;
	}, 300);
	
	const searchChange = (data) => {
		emit('getSelectValue', data);
	}
</script>