<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroy-on-close title="创建清单" :width="500" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { createListFormSchema } from '../TaskList.data';
  import { addTaskList } from '../TaskList.api';

  const emit = defineEmits(['register', 'success']);

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: createListFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  let pendingGroupId = '';

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    pendingGroupId = data?.groupId || '';
  });

  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      const values = await validate();
      await addTaskList({
        tasklistName: values.tasklistName || values.name,
        pid: pendingGroupId || undefined,
      });
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
