<!--
  * 库区 下拉选择框
  *
  *
-->
<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="customer in customers" :key="customer.customerId" :label="customer.customerName">
      {{ customer.customerName }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {customerApi} from "/@/api/business/base/customer/customer-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,
  },
  disabledFlag: {
    type: Boolean,
    default: null,
  }
});

const customers = ref([]);

async function queryData() {

  let res = await customerApi.queryCustomer({
    disabledFlag: props.disabledFlag
  });
  customers.value = res.data;
  //默认显示第一个元素
/*  if (customers.value.length > 0 &&!props.value) {
    selectValue.value = customers.value[0].customerId;
    handleChange(selectValue.value);
  }*/
}

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

const selectValue = ref(props.value);

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


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

}


onMounted(queryData);
</script>
