<!--
  * 库位 下拉选择框
  *
  *
-->
<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="location in locations" :key="location.locationId" :label="location.locationCode">
      {{ location.locationCode }}
      <div style="float: right">
        <template v-if="location.areaName"> {{ location.areaName }}</template>
      </div>
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {locationApi} from '/@/api/business/base/location/location-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,
  },
  areaNames: {
    type: Array as () => any[],
    default: () => []
  },
  status: {
    type: String,
    default: null,
  },
  disabledFlag: {
    type: Boolean,
    default: null,
  },
});

const locations = ref([]);

async function queryData() {
  let res = await locationApi.queryLocation({
    areaNames: props.areaNames,
    status: props.status,
    disabledFlag: props.disabledFlag
  });
  locations.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 selectedLocations: any[] | any;
  if (Array.isArray(value)) {
    // 多选情况
    selectedLocations = value.map((id) => locations.value.find((item: any) => item.locationId === id)).filter(Boolean);
  } else {
    // 单选情况
    selectedLocations = locations.value.find((item: any) => item.locationId === value);
  }
  emit('update:value', value);
  emit('change', JSON.parse(JSON.stringify(selectedLocations)));
}


onMounted(queryData);
</script>
