<!--
  * 收货地址 下拉选择框
  *
  *
-->
<template>
  <a-select
      v-model:value="selectValue"
      :style="`width: ${width}`"
      :placeholder="props.placeholder"
      :showSearch="true"
      :allowClear="true"
      :size="size"
      @change="handleChange"
      :disabled="disabled"
      :mode="multiple ? 'multiple' : ''"
      optionFilterProp="label"
  >
    <a-select-option v-for="address in addressList" :key="address.addressId" :label="address.name">
      {{ address.name }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {addressApi} from "/@/api/business/base/address/address-api";

const props = defineProps({
  value: [Number, String, Object, Array],
  width: {
    type: String,
    default: '200px',
  },
  placeholder: {
    type: String,
    default: '请选择',
  },
  size: {
    type: String,
    default: 'default',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const addressList = ref([]);

async function queryData() {
  let res = await addressApi.queryAddress({});
  addressList.value = res.data;
}

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

const selectValue = ref(props.value);

// 箭头value变化
watch(
    () => props.value,
    (newValue) => {
      selectValue.value = newValue;
    }
);


function handleChange(value: any) {
  let selectedAddress: any[] | any;
  if (Array.isArray(value)) {
    // 多选情况
    selectedAddress = value.map((id) => addressList.value.find((item: any) => item.addressId === id)).filter(Boolean);
  } else {
    // 单选情况
    selectedAddress = addressList.value.find((item: any) => item.addressId === value);
  }
  emit('update:value', value);
  emit('change', selectedAddress);

}


onMounted(queryData);
</script>
