<template>
  <a-select
    :value="modelValue || undefined"
    @change="onChange"
    :mode="multiple ? 'multiple' : undefined"
    :disabled="disabled"
    :placeholder="placeholder"
    allowClear
    :getPopupContainer="(node) => node.parentNode"
  >
    <a-select-option v-for="user in userList" :key="user.username" :value="user.username">
      {{ user.realname }}
    </a-select-option>
  </a-select>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { defHttp } from '/@/utils/http/axios';

const props = withDefaults(
  defineProps<{
    roleId: string;
    multiple?: boolean;
    disabled?: boolean;
    placeholder?: string;
  }>(),
  {
    multiple: false,
    disabled: false,
    placeholder: '请选择',
  },
);

const modelValue = defineModel<string>('value', { default: '' });

const userList = ref<Array<{ username: string; realname: string }>>([]);

async function fetchUserList() {
  if (!props.roleId) {
    userList.value = [];
    return;
  }
  try {
    const res = await defHttp.get({
      url: '/sys/user/userRoleList',
      params: {
        roleId: props.roleId,
        pageNo: 1,
        pageSize: 999,
      },
    });
    const records = res?.records || res?.result?.records || [];
    userList.value = records;
  } catch {
    userList.value = [];
  }
}

onMounted(fetchUserList);

watch(
  () => props.roleId,
  () => {
    modelValue.value = '';
    fetchUserList();
  },
);

function onChange(value: string | string[]) {
  if (props.multiple) {
    modelValue.value = Array.isArray(value) ? value.join(',') : '';
  } else {
    modelValue.value = (value as string) || '';
  }
}
</script>
