<template>
  <div class="download-page flex items-center flex-col">
    <div class="retry text-sm text-center text-gray-700" v-if="!isRequest">
      下载出现问题了？<span class="cursor-pointer" @click="init"
        >点我重试!</span
      >
    </div>
    <template v-else>
      <div class="dot-elastic"></div>
      <div class="text-sm mt-6 text-center text-gray-700">
        {{ downloadTip }}
      </div>
    </template>
  </div>
</template>

<script>
import { decrypt } from '~/utils/crypto'
export default {
  data() {
    return {
      query: {},
      timer: null,
      time: 0,
      isRequest: false,
      success: false
    }
  },
  computed: {
    downloadTip() {
      return this.time > 10
        ? '当前文件过大，请勿退出，请耐心等待~~'
        : '正在下载，请稍等~~'
    },
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      try {
        // 获取参数
        const query = JSON.parse(decrypt(this.$route.query.state))
        this.query = query
        this.timer = setInterval(() => {
          this.time++
        }, 1000)
        this.isRequest = true
        const data = await fetch(query.downUrl, {
          headers: { 'X-Token': query.token },
        })
        // 链接是否重定向
        if (data.redirected) {
          const resultData = await data.json()
          // 登录过期
          if (resultData.code === -99) {
            return this.$toast('链接已失效~~')
          }
        }

        const res = await data.blob()
        const link = document.createElement('a')
        const url = URL.createObjectURL(res)
        link.href = url
        link.download = query.fileName
        link.click()
        URL.revokeObjectURL(url)
        clearInterval(this.timer)
        this.success = true
      } catch (error) {
        console.log(error)
        this.$toast('链接已失效~~')
        clearInterval(this.timer)
      } finally {
        this.isRequest = false
      }
    },
  },
}
</script>

<style scoped lang="scss">
.download-page {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  // background: #f1f8ee;
  box-sizing: border-box;
  padding-top: 16%;

  .retry {
    text-align: center;

    span {
      text-decoration: underline;
      transition: all 0.4s;
      &:hover {
        color: red;
      }
    }
  }
}
</style>
