<template>
  <!-- #ifdef H5 -->
  <!-- H5 端：支持普通跳转 / PDF预览 / 文件下载 -->
  <a v-if="isDownload" class="pdf-link" :href="url" :download="downloadName" target="_blank">
    <slot v-if="slots['default']"></slot>
    <view v-else>{{ t(props.title) || props.title }}</view>
  </a>
  <view v-else class="pdf-link" @click="handleClick">
    <slot v-if="slots['default']"></slot>
    <view v-else>{{ t(props.title) || props.title }}</view>
  </view>
  <!-- #endif -->

  <!-- #ifdef APP-PLUS -->
  <!-- APP 端：统一点击处理 -->
  <view class="pdf-link" @click="handleClick">
    <slot v-if="slots['default']"></slot>
    <view v-else>{{ t(props.title) || props.title }}</view>
  </view>
  <!-- #endif -->
</template>

<script setup>
import { useSlots } from 'vue'
import { openLocalPdf } from '@/utils/pdf'
import { openExternalUrl } from '@/utils/openExternalUrl'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const slots = useSlots()

const props = defineProps({
  url: String,
  type: {
    type: String,
    default: 'pdf' // pdf / pdf1 / html / download
  },
  title: String,
  target: String,
  // 下载文件名（下载时必填）
  downloadName: String
})
    // console.log(props, 1111);
// 判断是否是下载类型
const isDownload = props.type === 'download'

const handleClick = () => {
  if (!props.url) return

  // 下载逻辑（APP端）
  if (props.type === 'download') {
    startDownload()
    return
  }

  // PDF 预览
  if (props.type == 'pdf' || props.type == 'pdf1') {


    openLocalPdf(props.url, props.title, props.type)
  }

  // 外链打开
  else if (props.type === 'html') {
    openExternalUrl(props.url)
  }
}

// APP 端下载方法
const startDownload = () => {
  uni.showLoading({ title: '下载中...', mask: true })

  uni.downloadFile({
    url: props.url,
    success: (res) => {
      uni.hideLoading()
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          fileName: props.downloadName,
          success: () => {
            uni.showToast({ icon: 'none', title: '下载完成' })
          }
        })
      } else {
        uni.showToast({ icon: 'none', title: '下载失败' })
      }
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({ icon: 'none', title: '下载链接异常' })
    }
  })
}
</script>

<style scoped>
.pdf-link {
  //width: 100%;
  display: inline-block;
  cursor: pointer;
}
</style>