<!--
  * 物料 下拉选择框
  *
  *
-->
<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="item in items" :key="item.itemId" :label="item.itemCode">
      {{ item.itemCode }}
      <div style="float: right">
        <template v-if="item.itemName"> {{ item.itemName }}</template>
      </div>
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {itemApi} from '/@/api/business/base/item/item-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 items = ref([]);

async function queryData() {
  let res = await itemApi.queryItem({
    disabledFlag: props.disabledFlag
  });
  items.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) => items.value.find((item: any) => item.itemId === id)).filter(Boolean);
  } else {
    // 单选情况
    selectedLocations = items.value.find((item: any) => item.itemId === value);
  }
  emit('update:value', value);
  emit('change', selectedLocations);

}


onMounted(queryData);
</script>
