<template>
    <div v-loading="loading" element-loading-text="加载文件并初始渲染中..." class="h-full">
        <div :id="`pdf-view-${uuid}`" class="h-full" />
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import HcPdfSign from '~src/plugins/HcPdfSign'
import { getArrValue, getRandom } from 'js-fast-way'

//参数
const props = defineProps({
    sign: {
        type: [String, Number],
        default: '',
    },
    src: {
        type: [String, Number],
        default: '',
    },
    batch: {
        type: Boolean,
        default: false,
    },
    dom: {
        type: Array,
        default: () => ([]),
    },
    imgHeight:{
        type: [Number, String],
        default: '',
    },
    imgWidth:{
        type: [Number, String],
        default: '',
    },
})

//事件
const emit = defineEmits(['change'])
const pdf = ref(props.src)
const uuid = getRandom(6)
const signImg = ref(props.sign)
const loading = ref(false)
const imgWidth = ref(props.imgWidth)
const imgHeight = ref(props.imgHeight)


//监听
watch(() => [
props.imgWidth, props.imgHeight,
], ([width, height]) => {
    imgWidth.value = width
    imgHeight.value = height

    if (width && height) {
        getPdf()
    }
})
//监听PDFurl
watch(() => props.src, (src) => {
    if (src) {
        loading.value = true
        pdf.value = src
        getPdf()
    } else {
        noPdfUrl()
    }
})

//监听签章图片
watch(() => props.sign, (val) => {
    signImg.value = val
    getPdf()
})

//监听是否批量签章
watch(() => props.batch, (val) => {
    console.log(val)
    HcPdfSign.setBatchSign(val)
}, { immediate: true })

//渲染完成
onMounted(()=> {
    getPdf()
})

//设置PDF签章实例
const getPdf = () => {
    if (!pdf.value ) {
        noPdfUrl()
        return false
    }
    HcPdfSign.createPdf({
        ele: 'pdf-view-' + uuid, //挂载元素的id
        url: pdf.value, //pdf的url地址
        img: signImg.value, //签章图片的url地址
        width: imgWidth.value, //签章图片的宽度
        height: imgHeight.value, //签章图片的宽度
        //加载完成
        load: () => {
            //恢复签章记录
            setTimeout(()=> {
                HcPdfSign.setPdfSignImg(getArrValue(props.dom))
                loading.value = false
            }, 500)
        },
        //签章数据改变
        change: (data) => {
            emit('change', data)
        },
        isShowYinzhang:signImg.value.length > 0 ? true : false,
    })
}

const noPdfUrl = () => {
    pdf.value = ''
    loading.value = false
    document.getElementById('pdf-view-' + uuid).innerHTML = ''
}
</script>
