<!--
  * 库区 下拉选择框
  *
  *
-->
<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="area in areas" :key="area.areaId" :label="area.areaName">
      {{ area.areaName }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {areaApi} from '/@/api/business/base/area/area-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,
  },
  // 类型 ENTERPRISE_TYPE_ENUM
  type: {
    type: Number,
  },
  areaNames: {
    type: Array as () => any[],
    default: () => []
  }
});

const areas = ref([]);

async function queryData() {
  let res = await areaApi.queryArea({areaNames: props.areaNames});
  areas.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) => areas.value.find((item: any) => item.areaId === id)).filter(Boolean);
  } else {
    // 单选情况
    selectedLocations = areas.value.find((item: any) => item.areaId === value);
  }
  emit('update:value', value);
  emit('change', JSON.parse(JSON.stringify(selectedLocations)));

}


onMounted(queryData);
</script>
