<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    title="保存表单模板"
    width="200"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" class="!pt-4" />
    <slot></slot>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: '模板名称',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入模板名称',
      },
      colProps: { span: 24 },
    },

    {
      field: 'code',
      label: '模板编码',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入模板编码',
      },
      colProps: { span: 24 },
    },
    {
      field: 'sortCode',
      label: t('排序'),
      component: 'InputNumber',
      required: true,
      componentProps: {
        placeholder: '排序',
      },
      colProps: { span: 24 },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      componentProps: {
        placeholder: t('请输入备注'),
      },
      colProps: { span: 24 },
    },
  ];

  const emit = defineEmits(['success', 'register']);
  const [registerForm, { resetFields, validate }] = useForm({
    layout: 'vertical',
    rowProps: { gutter: 32 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
    resetFields();
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
    });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      emit('success', values);
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }

  defineExpose({
    closeModal,
  });
</script>
