<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="添加所属部门" width="400px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/src/components/Modal';
  import { BasicForm, useForm } from '/src/components/Form';

  const emit = defineEmits(['success', 'register']);
  const rowRecord = ref<any>(null);

  const [registerForm, { validate, resetFields, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        field: 'deptIds',
        label: '选择部门',
        component: 'Select',
        required: true,
        componentProps: {
          mode: 'multiple',
          options: [], // 初始为空，由父组件注入
        },
      },
    ],
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    rowRecord.value = data.record;
    // ✅ 关键：适配你说的“预加载后作为props传入”
    if (data.deptOptions) {
      updateSchema({
        field: 'deptIds',
        componentProps: { options: data.deptOptions },
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      console.log('当前选到的部门Id为', values.deptIds);
      console.log('接收到的来自table的record为', rowRecord.value);
      emit('success', {
        deptIds: values.deptIds,
        userId: rowRecord.value.userId,
        roleId: rowRecord.value.roleId,
      });
      // closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
