<template>
    <hc-pdf v-if="isPdfDom" :src="pdfUrl" :download="isDownload" :print="isPrint" />
</template>

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

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

defineOptions({
    name: 'HcPdfs',
})

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

//渲染完成
const isPdfDom = ref(false)
const isDownload = ref(false)
const isPrint = ref(false)
onMounted(() => {
    isDownload.value = btnAuth('measure-pdf-download')
    isPrint.value = btnAuth('measure-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>
