<template>
  <cwg-page-wrapper class="webview-page" :pageTitle="pageTitle" type="webview">
    <view class="page-container">
      <!-- WebView 内容区（自动占满剩余空间，不遮挡导航栏） -->
      <view class="web-view-container">
        <web-view :src="fileUrl" class="web-view" :webview-styles="webviewStyles" />
      </view>
    </view>
  </cwg-page-wrapper>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import Config from '@/config/index'
const { Host80 } = Config
import getWebBase from '@/utils/webBase'
const webBase = getWebBase()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const fileUrl = ref('')
const title = ref('')
const pageTitle = computed(() => t(title.value || ''))
const fileType = ref('')

import useGlobalStore from '@/stores/use-global-store'
const globalStore = useGlobalStore()
const statusBarHeight = computed(() => globalStore.statusBarHeight || 0)

// webview 样式（修复顶部安全区）
const webviewStyles = computed(() => ({
  progress: {
    color: '#ea002a'
  },
  top: statusBarHeight.value + 56 + 'px',
  bounce: 'none',
  scrollIndicator: 'none'
}))

// 获取文件后缀
const getFileExt = (name) => {
  if (!name) return ''
  return name.split('.').pop()?.toUpperCase()
}

onLoad((options) => {
  console.log('webview 接收参数：', options)

  title.value = options.title || '文件预览'
  const realUrl = options.url || ''
  fileType.value = getFileExt(realUrl)

  // ✅ 核心修复：PDF 只编码一次，不再二次编码
  if (fileType.value === 'PDF') {
    fileUrl.value = `${Host80}${webBase}/iframe/pdf.html?pdf=${realUrl}&title=${title.value}`
  } else {
    fileUrl.value = realUrl
  }

  console.log('最终加载地址：', fileUrl.value)
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";
</style>