<template>
  <div class="">
    <vModal
      v-model:visible="visibleModal"
      :title="modalTitle"
      :ok-loading="loading"
      :width="600"
      :hide-cancel="true"
      :ok-text="loading ? '下载中' : '重新下载'"
      @modal-handle-ok="modelHandleOk"
    >
      <div style="padding: 5px 15px">
        <a-upload
          :default-file-list="downloadForm.files"
          draggable
          :limit="1"
          action="/"
          :auto-upload="false"
          :show-file-list="true"
        />
        <div>
          <a-progress size="large" :percent="currentProgress / 100" />
        </div>
      </div>
    </vModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h } from 'vue'
import { Message, FileItem } from '@arco-design/web-vue'
import vModal from '@/components/modal/index.vue'
import { getDownloadOutcomeUrl } from '@/api/project/outcome'
import { downloadFile } from '@/api/client'

const loading = ref<boolean>(true)
const visibleModal = ref(false) // 是否显示对话框
const modalTitle = ref('') // 对话框标题
const currentProgress = ref(0)

const downloadForm = reactive<{
  id?: string
  files?: FileItem[]
  objectId?: string
  filename?: string
  name?: string
}>({
  files: []
})

/**
 * 显示级别modal
 * @param type modal 类型
 * @param item
 */
const showDownloadModal = async (
  id: string,
  name: string,
  objectId: string,
  filename: string
) => {
  try {
    currentProgress.value = 0
    downloadForm.files = [
      {
        uid: objectId,
        name: `${filename}`
      }
    ]
    downloadForm.id = id
    downloadForm.name = name
    downloadForm.filename = filename
    downloadForm.objectId = objectId
    modalTitle.value = `下载${name}附件`
    visibleModal.value = true
    const { url } = await getDownloadOutcomeUrl({
      id
    })
    // const downloadUrl = url.replace(/https:\/\/pmr\.surkw\.com:29000\//, '')
    await downloadFile(filename!, url, getDownloadProgress)
    Message.success('下载成功')
    setTimeout(() => {
      visibleModal.value = false
    }, 1000)
  } catch (e) {
    currentProgress.value = 0
    Message.success('下载失败')
    loading.value = false
  }
}

// 获取上传进度信息
const getDownloadProgress = (e: ProgressEvent) => {
  currentProgress.value = Number(((e.loaded / e.total) * 100).toFixed(0))
}

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  const { id, filename, objectId, name } = downloadForm
  await showDownloadModal(id!, name!, objectId!, filename!)
  return cb(false)
}

defineExpose({ showDownloadModal }) // 暴露子组件的方法或者数据
</script>

<script lang="ts">
export default {
  name: 'DownloadOutcome'
}
</script>

<style lang="less" scoped>
:deep(.arco-upload-progress) {
  display: none;
}
:deep(.arco-upload-list-item-operation) {
  display: none;
}
</style>
