<template>
  <PickerField 
    :columns="[ loader.data.value || [] ]"
    v-bind="$attrs"
    :singleValue="true"
    :modelValue="!(modelValue instanceof Array) ? [modelValue || ''] : modelValue"
    @update:modelValue="handleUpdateModelValue"
  />
</template>

<script setup lang="ts">
import PickerField from '@/components/form/PickerField.vue';
import { useDataLoader } from '@/components/composeabe/DataLoader';
import type { PickerIdFieldProps, PickerIdFieldOption } from './PickerIdField';

const props = defineProps<PickerIdFieldProps>();
const emit = defineEmits(['update:modelValue']);
const loader = useDataLoader<PickerIdFieldOption[]>(async () => {
  const res = await props.loadData();
  if (res.length === 0)
    return [];
  return ([{
    text: props.readonly ? '未选择' : '请选择',
    value: '',
  }] as PickerIdFieldOption[]).concat(res);
}, {
  immediate: true,
});

function handleUpdateModelValue(value: (string|number)[]) {
  if (value.length === 1) {
    emit('update:modelValue', value[0]);
    return;
  }
  emit('update:modelValue', value);
}

defineExpose({
  reload() {
    loader.load();
  }
})
</script>