<template>
  <div class="window-width window-height column flex-center items-center" style="background-color: #f1f2f4">
    <div class="rounded bg-white q-pa-xl light-shadow  column flex-center items-center" style="width: 650px;">
        <div style="width: 100%;">
            <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/pptTD.png" style="height: 27px;">
        </div>
        <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638533817842486720.png" style="width: 300px;" class="q-mt-xl">
        <template v-if="!isError && !isDownLoading && !isFinish">
          <div class="row items-center q-mt-xl ">
              <div style="width: 30px;height: 30px;" v-loading="true"></div>
              <div class="pingfangr q-ml-xl" style="font-size: 18px;">文件正在准备中...</div>
          </div>
          <div class="q-mt-lg text-info text-small text-center" style="font-size: 14px;">新的文件首次准备过程通常需要40秒左右，后续的下载会在3秒左右<br/>请您耐心等待。我们完成文件的渲染后将自动开启下载。</div>
         
        </template>
        <template v-if="isDownLoading">
          <div class="row items-center q-mt-xl ">
              <div class="pingfangr q-ml-xl" style="font-size: 18px;">文件正在下载中...</div>
          </div>
          <div class="full-width">
            <el-progress :percentage="progress" :format="formatProgress" class="q-mt-xl" />
          </div>
        </template>
        <template v-if="isFinish">
          <div class="row items-center q-mt-xl ">
            <div class="pingfangr q-ml-xl" style="font-size: 18px;">文件下载已完成</div>
            
          </div>
          <div class="q-mt-lg text-info text-small text-center" style="font-size: 14px;">本次下载令牌已失效，请关闭窗口，不要做多次刷新请求</div>
          <div class="q-mt-xl text-center" style="font-size: 14px;">
            <el-button type="info" size="large" class="ppt-button text-weight-bold" @click="closeWindow">关闭当前窗口</el-button>
          </div>
        </template>
        <template v-if="isError">
          <div class="row items-center q-mt-xl ">
            <div class="pingfangr q-ml-xl" style="font-size: 18px;">Access Denied，无法继续执行</div>
          </div>
          <div class="q-mt-lg text-info text-small text-center" style="font-size: 14px;">这通常是由于你没有足够的权限下载此文件，或者是由于你重复使用了令牌进行下载，你需要进入返回个人空间进行重新发起下载请求</div>
          <div class="q-mt-xl text-center" style="font-size: 14px;">
            <el-button type="info" size="large" class="ppt-button text-weight-bold" @click="closeWindow">关闭当前窗口</el-button>
          </div>
        </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ApiResult } from "@/configs/axios";
import ConfigService from "@/services/ConfigService";
import FileService from "@/services/FileService";
import { ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter()
const token = router.currentRoute.value.params.token
const isError = ref(false)
const isDownLoading = ref(false)
const isFinish = ref(false)
const progress = ref(0)

if(!token) router.push({path:'/notfound'})

const checkDownloadRequestAsync = async()=>{
  const response = await FileService.checkDownloadRequestAsync(token.toString())//2f5aa48a56835d0518eea926253214f739b4b77c07b8852aa7fa5df93b2380d2
  if(response && !response.isError){
    if(response.status==0){
      setTimeout(() => {
        checkDownloadRequestAsync()
      }, 1000);
    }else {
      handlePreview()
    }
  } else {
    isError.value=true
  }
}

const handlePreview = ()=> {
  isDownLoading.value=true
  isFinish.value=false
  const url = `${process.env.VUE_APP_PDF_URL}/api/download/${token}/d`
  const xhr = new XMLHttpRequest()
  xhr.open('GET', url, true)
  xhr.responseType = 'blob'
  xhr.onprogress = (e:any)=>{
      progress.value = parseInt(((e.loaded / e.total) * 100).toString())
      console.log(e)
  }
  xhr.onload = ()=>{
    isDownLoading.value=false
    isFinish.value=true
    var blob = xhr.response;
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = xhr.getResponseHeader('X-File-Name')?.toString()??"";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
  xhr.send()
}
const formatProgress = (percentage:any) => (percentage === 100 ? '完成' : `${percentage}%`)
const closeWindow = ()=> window.close()
checkDownloadRequestAsync()
</script>

<style>

</style>