<template>
  <!-- #ifdef H5 -->
  <!-- H5 端：支持普通跳转 / PDF预览 / 文件下载 -->
  <a v-if="isDownload" class="pdf-link cursor-pointer" :href="url" :download="downloadName" target="_blank" :title="resolvedTitle" :data-tooltip="resolvedTitle" data-placement="top">
    <slot v-if="slots['default']"></slot>
    <view v-else>{{ t(props.title) || props.title }}</view>
  </a>
  <a v-else-if="isHtml" class="pdf-link cursor-pointer" :href="url" :target="target || '_blank'" :title="resolvedTitle"
    rel="noopener noreferrer" :data-tooltip="resolvedTitle" data-placement="top">
    <slot v-if="slots['default']"></slot>
    <view v-else>{{ t(props.title) || props.title }}</view>
  </a>
  <view v-else class="pdf-link cursor-pointer" @click="handleClick" :data-tooltip="t(props.title) || props.title" data-placement="top">
    <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 { computed, 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
})

const isDownload = props.type === 'download'
const isHtml = props.type === 'html'
const resolvedTitle = computed(() => {
  if (!props.title) return undefined
  return t(props.title)
})

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: t('mine.p27') })
          }
        })
      } else {
        uni.showToast({ icon: 'none', title: t('mine.p28') })
      }
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({ icon: 'none', title: t('mine.p28') })
    }
  })
}
</script>

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