<template>
  <view>
    <navbar-back title="任务单预览"></navbar-back>
    <view></view>
    <!-- #ifdef H5 -->
    <web-view :src="pdfUrlH5"></web-view>
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { getBaseUrl } from '@/defaultBaseUrl'
import nx from '@/nx'

// 响应式数据
const taskId = ref('')
const localFilePath = ref('')
const reportKey = ref('')
const hideResultFlag = ref('')
const viewerUrl = '/hybrid/html/web/viewer.html?file='
const pdfUrlH5 = ref('')

let wv = null // 计划创建的 webview

// 方法：下载 PDF
const downloadPdf = (pdfUrl, retryCount = 0) => {
  const MAX_RETRY = 3 // 最多重试 3 次
  return new Promise(resolve => {
    if (retryCount >= MAX_RETRY) {
      console.error('PDF 下载失败：超过最大重试次数')
      return resolve(null)
    }

    uni.downloadFile({
      url: pdfUrl,
      success: res => {
        if (res.statusCode !== 200) {
          console.warn(`下载失败，状态码: ${res.statusCode}，重试第 ${retryCount + 1} 次`)
          return resolve(downloadPdf(pdfUrl, retryCount + 1))
        }

        const tempFilePath = res.tempFilePath
        uni.getFileInfo({
          filePath: tempFilePath,
          success: fileInfo => {
            if (fileInfo.size > 0) {
              resolve(tempFilePath)
            } else {
              console.warn('文件为空，重试中...')
              resolve(downloadPdf(pdfUrl, retryCount + 1))
            }
          },
          fail: () => {
            console.warn('获取文件信息失败，重试中...')
            resolve(downloadPdf(pdfUrl, retryCount + 1))
          }
        })
      },
      fail: () => {
        console.warn('网络请求失败，重试中...')
        resolve(downloadPdf(pdfUrl, retryCount + 1))
      }
    })
  })
}

// 方法：Android 加载 PDF
const loadPdfOnAndroid = async pdfUrl => {
  const tempFilePath = await downloadPdf(pdfUrl)
  if (!tempFilePath) return
  const localPath = plus.io.convertLocalFileSystemURL(tempFilePath)
  localFilePath.value = localPath
  const allUrl = viewerUrl + encodeURIComponent(localPath)
  // 创建并加载 webview
  wv = plus.webview.create('', 'custom-webview', {
    top: uni.getSystemInfoSync().statusBarHeight + 44,
    bottom: 0
  })
  wv.loadURL(allUrl)
  const currentWebview = getCurrentPages().pop().$getAppWebview()
  currentWebview.append(wv)
}

// 获取 PDF 预览 URL
const getPdf = async () => {
  const printBaseUrl = getBaseUrl()
  const baseUrl = getBaseUrl()
  let dataUrl = `${baseUrl}/qms/bus/qmsBusAssayTask/getAssayTaskDataWithDetailData?taskId=${taskId.value}`
  dataUrl += `&hideResultFlag=${hideResultFlag.value}`
  const token = nx.$store('user').token
  let url = `${printBaseUrl}/report/gridpp/report/previewDocs`
  url += `?token=${token}`
  url += `&type=PDF`
  url += `&reportKey=${reportKey.value}`
  url += `&dataUrl=${encodeURIComponent(dataUrl)}`

  // #ifdef H5
  pdfUrlH5.value = viewerUrl + encodeURIComponent(url)
  // #endif

  // #ifndef H5
  await loadPdfOnAndroid(url)
  // #endif
}

// 删除临时文件
const deleteTmpFile = () => {
  if (!localFilePath.value) return
  const dir = localFilePath.value.substring(0, localFilePath.value.lastIndexOf('/'))
  plus.io.resolveLocalFileSystemURL(
    dir,
    entry => {
      entry.removeRecursively(
        () => console.log('删除成功'),
        e => console.log('删除失败：' + e.message)
      )
    },
    e => console.log('目录不存在：' + e.message)
  )
}

// 生命周期
onLoad(param => {
  if (param.taskId) {
    taskId.value = param.taskId
    reportKey.value = param.reportKey
    hideResultFlag.value = param.hideResultFlag
  }
  getPdf()
})

onHide(() => {
  deleteTmpFile()
})

onUnload(() => {
  deleteTmpFile()
})
</script>

<style scoped></style>
