<template>
  <div style="width: 100%; height: 100%;">
    <!-- 图片：直接使用原始地址展示（保持原有行为） -->
    <viewer :images="[authSrc]" v-if="!showIframe">
      <img
        v-if="!showIframe"
        ref="imgRef"
        :width="imgWidth ? imgWidth : '100%;'"
        :height="imgHeight ? imgHeight : '100%;'"
        :src="authSrc"
      />
    </viewer>

    <!-- PDF：通过 iframe + 带 token 的请求展示 -->
    <iframe
      v-if="showIframe"
      ref="authIframeRef"
      style="width: 100%; height: 100%;"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { Session } from '/@/utils/storage'

const props = defineProps<{
  authSrc: string
  imgWidth?: string
  imgHeight?: string
}>()

const showIframe = ref(false)
const authIframeRef = ref<HTMLIFrameElement | null>(null)
const imgRef = ref<HTMLImageElement | null>(null)

// 携带 token 请求 img/pdf 的 src
const getImgSrcByToken = (src?: string) => {
  const targetSrc = src || props.authSrc

  if (targetSrc.indexOf('.pdf') >= 0) {
    // PDF：通过 iframe 展示
    showIframe.value = true
    nextTick(() => {
      const tenantId = Session.getTenant()
      const iframe = authIframeRef.value
      if (!iframe) return

      const request = new XMLHttpRequest()
      request.responseType = 'blob'
      request.open('get', targetSrc, true)
      request.setRequestHeader('Authorization', 'Bearer ' + Session.getToken())
      request.setRequestHeader('TENANT-ID', tenantId)
      request.onreadystatechange = () => {
        if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
          const binaryData: BlobPart[] = []
          binaryData.push(request.response)
          iframe.src = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
          iframe.onload = () => {
            URL.revokeObjectURL(iframe.src)
          }
        }
      }
      request.send(null)
    })
  } else {
    // 图片：保持原有行为（直接使用 authSrc，不做 token 转发）
    showIframe.value = false
    // 如需带 token 加载图片，可参考被注释的旧逻辑在此扩展
  }
}

const refreshImg = (src?: string) => {
  getImgSrcByToken(src)
}

onMounted(() => {
  getImgSrcByToken()
})

defineExpose({
  refreshImg,
})
</script>

