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

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

  const rowId = ref('');
  const suffix = ref('');

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

  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    schemas: renameFormSchema,
    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;
    const fileNameArr = data.fileName.split('.');
    if (fileNameArr.length > 1) {
      suffix.value = fileNameArr.pop();
      data.fileName = fileNameArr.toString();
      const addonAfter = '.' + suffix.value;
      updateSchema([
        {
          field: 'currentFileName',
          componentProps: {
            addonAfter,
          },
        },
        {
          field: 'fileName',
          componentProps: {
            addonAfter,
          },
        },
      ]);
    }
    setFieldsValue({ currentFileName: data.fileName });
  });

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