<template>
    <hc-pdf v-if="isPdfDom" :src="pdfUrl" :download="isDownload" :print="isPrint" :is-https="isHttps" :file-name="fileName" />
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { btnAuth, decode } from '~uti/btn-auth'
import { isNullES } from 'js-fast-way'
import website from '~src/config'

const props = defineProps({
    url: {
        type: String,
        default: '',
    },
    code: {
        type: String,
        default: '',
    },
     fileName: {
        type: String,
        default: '',
    },
})

defineOptions({
    name: 'HcPdfs',
})

//监听
const queryUrl = ref(props.url)
const queryCode = ref(props.code)
const fileName = ref(props.fileName)
watch(() => [props.url, props.code, props.fileName], ([url, code, name]) => {
 
    queryUrl.value = url
    queryCode.value = code
    fileName.value = name
    setPdfSrcData()
})

//渲染完成
const isPdfDom = ref(false)
const isDownload = ref(false)
const isPrint = ref(false)
const isHttps = ref(false)
onMounted(() => {
    isHttps.value = !website.localModel
    isDownload.value = btnAuth('client-pdf-download')
    isPrint.value = btnAuth('client-pdf-print')
    setPdfSrcData()
    nextTick(() => {
        isPdfDom.value = true
    })
})

//设置PDF地址
const pdfUrl = ref('')
const setPdfSrcData = () => {
    const url = queryUrl.value, code = queryCode.value
    //如果url和code都为空，不做处理
    if (isNullES(url) && isNullES(code)) {
        return
    }
    //如果url不为空，code为空，以url为准
    if (!isNullES(url) && isNullES(code)) {
        pdfUrl.value = url
        return
    }
    //如果url为空，code不为空，以code为准
    if (isNullES(url) && !isNullES(code)) {
        pdfUrl.value = decode(code ?? '')
        return
    }
    //两个都有的情况下，以code为准
    pdfUrl.value = decode(code ?? '')
}

//页面被卸载
onUnmounted(() => {
    isPdfDom.value = false
})
</script>
