<template>
  <view class="document-viewer-page">
    <!-- 使用 web-view 全屏展示文档 -->
    <web-view v-if="documentUrl" :src="documentUrl"></web-view>
    
    <!-- 错误状态 -->
    <view v-else class="error-state">
      <text class="error-text">{{ errorMessage || '文档地址无效' }}</text>
      <button class="retry-btn" @click="handleBack">返回</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 文档信息
const documentName = ref('')
const documentUrl = ref('')
const ossId = ref('')
const errorMessage = ref('')

onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  
  documentName.value = decodeURIComponent(currentPage.options.name || '文档预览')
  documentUrl.value = decodeURIComponent(currentPage.options.url || '')
  ossId.value = currentPage.options.ossId || ''
  
  // 设置导航栏标题
  if (documentName.value) {
    uni.setNavigationBarTitle({
      title: documentName.value
    })
  }
  
  // 如果没有URL但有ossId，可以通过ossId构建URL
  if (!documentUrl.value && ossId.value) {
    // TODO: 根据ossId构建文档访问URL
    // documentUrl.value = `${BASE_URL}/file/preview/${ossId.value}`
  }
  
  // 验证URL
  if (!documentUrl.value) {
    errorMessage.value = '文档地址无效'
  }
})

// 返回
const handleBack = () => {
  uni.navigateBack({
    fail: () => {
      uni.reLaunch({
        url: '/pages/home/index'
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.document-viewer-page {
  width: 100%;
  height: 100vh;
  background-color: #ffffff;
  
  web-view {
    width: 100%;
    height: 100%;
  }
  
  // 错误状态
  .error-state {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 40rpx;
    padding: 60rpx;
    background-color: #f5f5f5;
    
    .error-text {
      font-size: 28rpx;
      color: #999999;
      text-align: center;
    }
    
    .retry-btn {
      width: 200rpx;
      height: 72rpx;
      line-height: 72rpx;
      background: #1ec9c9;
      color: #ffffff;
      border-radius: 36rpx;
      font-size: 28rpx;
      border: none;
      
      &:active {
        opacity: 0.8;
      }
      
      &::after {
        border: none;
      }
    }
  }
}
</style>
