<template>
  <el-select
    :model-value="modelValue"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    filterable
    style="width: 100%"
    @update:model-value="onChange"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name + (item.staffNo ? ' (' + item.staffNo + ')' : '')"
      :value="item.id"
    />
  </el-select>
</template>

<script setup lang="ts" name="StaffSelect">
import { staffOptionselect } from '@/api/edu/staff';
import { StaffVO } from '@/api/edu/staff/types';

interface PropType {
  /** 选中的员工ID(staff.id) */
  modelValue?: number | string;
  /** 角色筛选 SALES/HOUSEKEEPER/TUTOR/... 不传则全部 */
  role?: string;
  placeholder?: string;
  disabled?: boolean;
  clearable?: boolean;
}

const prop = withDefaults(defineProps<PropType>(), {
  modelValue: undefined,
  role: undefined,
  placeholder: '请选择',
  disabled: false,
  clearable: true
});

const emit = defineEmits(['update:modelValue', 'change']);

const options = ref<StaffVO[]>([]);

/** 拉取候选员工(按 role 过滤) */
const loadOptions = async () => {
  const res = await staffOptionselect(prop.role);
  options.value = res.data || [];
};

const onChange = (val: number | string) => {
  emit('update:modelValue', val);
  const staff = options.value.find((o) => o.id === val);
  emit('change', val, staff);
};

/**
 * 传入 staff id 时若当前候选不含, 单条补查并补入候选, 保证回显正确
 */
const ensureEcho = async () => {
  if (prop.modelValue === undefined || prop.modelValue === null || prop.modelValue === '') return;
  const exists = options.value.some((o) => o.id === prop.modelValue);
  if (!exists) {
    // 角色已限定时, 该 id 可能不在候选内 → 放宽 role 重新拉一次全部再匹配
    const res = await staffOptionselect(undefined);
    const all = res.data || [];
    const found = all.find((o) => o.id === prop.modelValue);
    if (found && !options.value.some((o) => o.id === found.id)) {
      options.value.push(found);
    }
  }
};

watch(
  () => prop.role,
  () => {
    loadOptions();
  }
);

onMounted(async () => {
  await loadOptions();
  await ensureEcho();
});
</script>
