<script setup lang="ts">
import type { UploadChangeParam } from 'ant-design-vue';

import { shallowRef, triggerRef } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { FilePlus } from '@vben/icons';
import { $t } from '@vben/locales';

import { message, UploadDragger } from 'ant-design-vue';

export interface ImportDatabaseProps<U = { count: number; message: string }> {
  accept?: string;
  upload?: (file: File) => Promise<U>;
}

defineOptions({
  name: 'ImportDatabaseModal',
});

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

const props = shallowRef<ImportDatabaseProps>({
  accept: '*/*',
});

const [Modal, modalApi] = useVbenModal({
  showConfirmButton: false,
  async onConfirm() {},
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<ImportDatabaseProps>();
      Object.assign(props.value, data);
      triggerRef(props);
    }
  },
});

const onAcceptError = (_files: File[]) => {
  message.warn(`请上传正确格式的文件`);
};

async function onChangeHandle(info: UploadChangeParam<File>) {
  const accept = props.value.accept ?? '*/*';
  if (info.file.type && accept !== '*/*' && !accept.includes(info.file.type))
    return onAcceptError(info.fileList);

  modalApi.lock();
  try {
    const data = await props.value.upload?.(info.file);
    if (data?.count) {
      message.success(data.message);
      await modalApi.close();
      emit('success');
    }
  } catch (error: any) {
    message.error(error.message);
  } finally {
    modalApi.lock(false);
  }
}
</script>

<template>
  <Modal
    class="import-database-modal-wrapper"
    :draggable="true"
    :fullscreen-button="false"
    :confirm-text="$t('ui.actionTitle.import')"
  >
    <UploadDragger
      class="size-full"
      name="file"
      :show-upload-list="false"
      :accept="props.accept"
      :before-upload="() => false"
      @change="onChangeHandle"
      @reject="onAcceptError"
    >
      <p class="ant-upload-drag-icon text-center">
        <FilePlus class="text-primary inline size-24" />
      </p>
      <span class="ant-upload-text">单击或将文件拖到此区域进行上传</span>
    </UploadDragger>
    <template v-if="$slots['prepend-footer']" #prepend-footer>
      <slot name="prepend-footer"></slot>
    </template>
  </Modal>
</template>

<style scoped lang="scss">
:deep(.ant-upload-btn) {
  display: flex !important;
  flex-direction: column;
  justify-content: center;
  padding: 0 !important;
}

:global(.import-database-modal-wrapper) {
  height: 520px;
}
</style>
