<template>
  <BasicModalExcel v-bind="$attrs" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="!pt-4" />
  </BasicModalExcel>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue';
  import { BasicModalExcel, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';

  const nameFormSchema: FormSchema[] = [
    {
      field: 'fileName',
      label: '文件名称',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请填写文件名称',
      },
      colProps: { span: 24 },
    },
  ];

  const renameFormSchema: FormSchema[] = [
    {
      field: 'currentFileName',
      label: '当前名称',
      component: 'Input',
      componentProps: {
        readonly: true,
      },
      colProps: { span: 24 },
    },
    {
      field: 'fileName',
      label: '修改名称',
      component: 'Input',
      componentProps: {
        placeholder: '请填写修改后名称',
      },
      colProps: { span: 24 },
    },
  ];

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

  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate, setProps }] = useForm({
    schemas: nameFormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: {
      gutter: 32,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      width: 500,
      title: data.title,
    });
    rowId.value = data.id;
    if (!!data.isRename) {
      await setProps({
        schemas: renameFormSchema,
      });
      setFieldsValue({ currentFileName: data.fileName });
    } else {
      await setProps({
        schemas: nameFormSchema,
      });
      if (data.isUpdate) setFieldsValue({ fileName: data.fileName });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      emit('success', {
        fileName: values.fileName,
        id: rowId.value,
      });
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
