<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="30%">
    <BasicForm @register="registerForm" class="pt-3"> </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { FormSchema } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { typeAdd, typeEdit } from '../api';

  const title = ref('新增文档分类');
  const FormSchema: FormSchema[] = [
    {
      label: 'pid',
      field: 'pid',
      component: 'Input',
      show: false,
    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: '分类名称',
      field: 'name',
      component: 'Input',
      required: true,
    },
    {
      label: '分类排序',
      field: 'sort',
      component: 'InputNumber',
    },
  ];
  // Emits声明
  const emit = defineEmits(['register', 'success']);

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: FormSchema,
    // autoAdvancedCol: 2,
    // baseColProps: { span: 24 },
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: any) => {
    title.value = data.title;
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter, centered: true });
    //表单赋值
    if (data.isEdit) {
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      if (title.value == '新增文档分类' || title.value == '添加下级') await typeAdd(values);
      else {
        delete values.pid;
        await typeEdit(values);
      }
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
