<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

import { getCountryAlls } from '#/api/legacy/system';

import { Select } from 'antdv-next';

const props = withDefaults(
  defineProps<{
    clearable?: boolean;
    disabled?: boolean;
    filterable?: boolean;
    multiple?: boolean;
    placeholder?: string;
    value?: any;
  }>(),
  {
    clearable: false,
    disabled: false,
    filterable: true,
    multiple: false,
    placeholder: '请选择国家',
    value: '',
  },
);

const emit = defineEmits<{
  change: [any, Record<string, any> | null];
  'update:value': [any];
}>();

const loading = ref(false);
const list = ref<Array<Record<string, any>>>([]);
const selectValue = ref<any>('');
const countryOptions = computed(() =>
  list.value.map((item) => ({
    label: String(item.aliasName || item.countryName || item.alphaTwo || item.id || '-'),
    value: item.id as any,
  })),
);

watch(
  () => props.value,
  (value) => {
    selectValue.value = value ?? '';
  },
  { immediate: true },
);

async function loadCountries() {
  loading.value = true;
  try {
    list.value = await getCountryAlls();
  } finally {
    loading.value = false;
  }
}

function handleChange(value: any) {
  selectValue.value = value;
  emit('update:value', value);
  const country =
    Array.isArray(value)
      ? null
      : list.value.find((item) => String(item.id) === String(value)) || null;
  emit('change', value, country);
}

onMounted(() => {
  void loadCountries();
});
</script>

<template>
  <Select
    :value="selectValue"
    :allow-clear="clearable"
    :disabled="disabled"
    :loading="loading"
    :mode="multiple ? 'multiple' : undefined"
    :options="countryOptions"
    :placeholder="placeholder"
    :show-search="filterable"
    option-label-prop="label"
    style="width: 100%"
    @change="handleChange"
  />
</template>
