<template>
	<el-select :class="styleClass" :placeholder="prompt" v-model="state.value" :loading="state.loading" @change="onChange" @focus="onFocus">
		<el-option v-for="item in state.data" :key="item.value" :label="item.label" :value="item.value" />
	</el-select>
</template>

<script setup>
import { reactive, watch, onMounted } from 'vue';
import { fetchItemList } from '/@/api/admin/dict';

const state = reactive({
	data: [],
	loading: false,
});
const emit = defineEmits(['change', 'update:value']);

const props = defineProps({
	value: {
		type: [String, Number, Array],
		default: '',
	},
	valueKey: {
		type: String,
		default: 'value',
	},
	trigger: {
		desc: '请求数据时机init:初始化/focus:聚焦',
		type: String,
		default: 'init',
	},
	dictType: {
		type: String,
		default: '',
	},
	isSelectAll: {
		desc: '是否需要全部选项',
		type: Boolean,
		default: false,
	},
	selectFirst: {
		desc: '是否选择第一个',
		type: Boolean,
		default: false,
	},
	prompt: {
		type: String,
		default: '请选择',
	},
	styleClass: {
		type: String,
		default: 'min-w-[160px]',
	},
});
watch(
	() => props.value,
	() => {
		state.value = props.value || null;
		if (!props.value && props.selectFirst && state.data[0]) {
			state.value = state.data[0].value;
			emit('update:value', state.value);
		}
	},
	{
		immediate: true,
	}
);
const onChange = (record, option) => {
	emit('change', record, option);
	emit('update:value', record);
};
//获取数据
const getData = async () => {
	state.data = [];
	state.loading = true;
	const { data = [], code } = await fetchItemList({ dictType: props.dictType });
		
	if (code === 0) {
		state.data = data.records.map((item) => {
			return {
				label: item.label,
				value: item[props.valueKey],
			};
		});
		if(props.isSelectAll){
			state.data.unshift({
				label: '全部',
				value: '',
			});
		}
		state.loading = false;
		if (props.selectFirst) {
			state.value = state.data[0].value;
			emit('update:value', state.value);
		}
	}
};
const onFocus = () => {
	props.trigger === 'focus' && getData();
};
onMounted(() => {	
	props.trigger === 'init' && getData();
});
</script>
<style lang="less" scoped></style>
