<template>
  <t-select
    v-model="selected"
    clearable
    filterable
    :loading="loading"
    @search="search"
    @change="onChange"
  >
    <t-option
      v-for="item in optionList"
      :key="item.id"
      :value="item.id"
      :label="item.realName"
    />
  </t-select>
</template>

<script setup name="SelectFilterUser">
import { ref, watch, computed, useAttrs } from 'vue';
import { getUserList } from '@/api/user';
const attrs = useAttrs();
const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: { type: [Number, String, Array], default: '' },
  defaultList: {
    type: Array,
    default() {
      return [];
    },
  },
});
const isMultiple = computed(() => {
  const multiple = attrs.multiple;
  return multiple === '' || multiple;
});

let optionList = ref([]);
let selected = ref('');
let loading = ref(false);

async function search(userInfo) {
  if (!userInfo) {
    optionList.value = props.defaultList;
    return;
  }

  optionList.value = [];

  if (loading.value) return;
  loading.value = true;
  const res = await getUserList({
    userInfo,
    enable: true,
    pageNumber: 1,
    pageSize: 10,
  }).catch(() => {});
  loading.value = false;
  if (!res) return;

  optionList.value = res.records;
}

const onChange = () => {
  const selectedData = isMultiple.value
    ? optionList.value.filter(
        (item) => selected.value && selected.value.includes(item.id)
      )
    : optionList.value.filter((item) => selected.value === item.id);
  emit('update:modelValue', selected.value);
  emit('change', selectedData);
};

watch(
  () => props.modelValue,
  (val) => {
    selected.value = val;
  },
  {
    immediate: true,
  }
);
</script>
