<!--
  * 容器 下拉选择框
  *
  *
-->
<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="stock in stocks" :key="stock.stockId" :label="stock.stockCode">
      {{ stock.stockCode }}
      <div style="float: right">
        <template v-if="stock.stockType">
          <DictPreview :options="stockType.STOCK_TYPE" :value="stock.stockType"/>
        </template>
      </div>
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {stockApi} from "/@/api/business/base/stock/stock-api";
import {useDict} from "/@/utils/dict";
import DictPreview from "/@/components/dict-preview/index.vue";

//容器类型
const stockType = useDict('STOCK_TYPE');


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,
  },
  status: {
    type: String,
    default: null,
  },
  disabledFlag: {
    type: Boolean,
    default: null,
  },
});

const stocks = ref([]);

async function queryData() {
  let res = await stockApi.queryStock({
    status: props.status,
    disabledFlag: props.disabledFlag
  });
  stocks.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 selectedStocks: any[] | any;
  if (Array.isArray(value)) {
    // 多选情况
    selectedStocks = value.map((id) => stocks.value.find((item: any) => item.stockId === id)).filter(Boolean);
  } else {
    // 单选情况
    selectedStocks = stocks.value.find((item: any) => item.stockId === value);
  }
  emit('update:value', value);
  emit('change', selectedStocks);
}


onMounted(queryData);
</script>
