<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="重命名" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { renameSchema } from '../modal.data';
  import { UpdatePicName } from '@/api/demo/mediaLibrary';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  const emits = defineEmits(['handleSuccess']);

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

  // 上级文件夹的id
  const id = ref();
  const recordData: any = ref({});
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    recordData.value = data.record;
    id.value = data.record?.id;
    let editName: any = recordData.value.name.split('.').slice(0, -1).join('.');
    setFieldsValue({
      name: editName,
    });
  });

  // 提交
  async function handleSubmit() {
    try {
      const values = await validate();
      let newName = '';
      if (recordData.value.name.split('.').length <= 1) {
        newName = values.name;
      } else {
        newName = values.name + '.' + recordData.value.name.split('.').pop();
      }
      let query = {
        id: id.value,
        name: newName,
      };
      UpdatePicName(query).then((res) => {
        emits('handleSuccess');
        setModalProps({ confirmLoading: true });
        createMessage.success(res);
        closeModal();
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
