<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 { getCreateListFormSchema } from '../TaskList.data';
  import { addTaskList } from '../TaskList.api';
  import { getSecretText } from '../types';

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

  let pendingGroupId = '';
  let pendingUserSecurityLevel = 3;

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

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

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