<script setup lang="ts">
import { type UploadCustomRequestOptions, type UploadFileInfo } from 'naive-ui'
import { api } from '@/tools/web.js'
import type { UploadFileDto } from '@/types/user.js'
import { shallowRef, useTemplateRef } from 'vue'

defineProps<{
  afterLeave?: () => void
}>()

const showModal = defineModel('showModal', { required: true })

const upload = useTemplateRef('upload')

const fileList = shallowRef<UploadFileInfo[]>([])

async function handle_upload({ file, onFinish, onError, onProgress }: UploadCustomRequestOptions) {
  const formData = new FormData()
  console.log(file.file)
  formData.append('file', file.file!)
  console.log(formData)

  try {
    const data = await api
      .post('/file/upload/', formData, {
        headers: {
          'Content-Type': undefined, // 取消全局默认的 application/json 很重要！！！！！！！！
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.ceil((progressEvent.loaded / progressEvent.total!) * 100)
          onProgress({ percent }) // 更新进度条
        },
      })
      .then((res) => res.data as UploadFileDto)

    file.url = data.download_url
    onFinish()
  } catch (err) {
    console.error(`文件上传失败：${err}`)
    onError()
  }
}

function onUpload() {
  upload.value?.submit()
}
</script>

<template>
  <n-modal
    style="width: 600px"
    preset="card"
    v-model:show="showModal"
    title="上传文件"
    content-scrollable
    @after-leave="afterLeave"
  >
    <n-flex vertical>
      <n-upload
        multiple
        ref="upload"
        :default-upload="false"
        list-type="image"
        :custom-request="handle_upload"
        v-model:file-list="fileList"
      >
        <n-upload-dragger>
          <n-p>拖拽文件到此区域可以快速上传。</n-p>
        </n-upload-dragger>
      </n-upload>

      <n-flex>
        <n-button type="primary" secondary @click="onUpload">上传</n-button>
        <n-tag size="large" type="info">如有必要，请在上传前在您的本地对文件进行重命名~</n-tag>
      </n-flex>
    </n-flex>
  </n-modal>
</template>

<style scoped></style>
