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

<script setup name="SelectTypeUser">
import { onMounted, ref, useAttrs, watch, computed } from 'vue';
import { getRoleUserList } from '@/api/user';

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

const attrs = useAttrs();

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: { type: [Number, String, Array], default: '' },
  type: { type: String, default: '' },
});
const isMultiple = computed(() => {
  const multiple = attrs.multiple;
  return multiple === '' || multiple;
});

const search = async () => {
  if (!props.type) return;
  optionList.value = [];
  const res = await getRoleUserList(props.type).catch(() => {});
  if (!res) return;

  optionList.value = res;
};

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', isMultiple.value ? selectedData : selectedData[0]);
};

onMounted(async () => {
  await search();
  updateSelected(props.modelValue);
});

const updateSelected = (val) => {
  if (optionList.value.filter((item) => val === item.id).length !== 0) {
    selected.value = val;
  } else {
    selected.value = '';
  }
};

watch(
  () => props.modelValue,
  (val) => {
    updateSelected(val);
  }
);
watch(
  () => props.type,
  (val, oldval) => {
    if (val !== oldval) {
      search();
      emit('update:modelValue', null);
      emit('change', isMultiple.value ? [] : null);
    }
  }
);
</script>
