<template>
	<div style="height: 900px">
		<div v-if="!showPdf">渲染pdf失败</div>
		<div class="mb-4" v-if="showPdf">
			<a-button type="primary" @click="downPdf">下载讲义</a-button>
		</div>
		<vue-office-pdf
			:src="props.itemObj.url"
			style="width: 100%; height: 100%"
			@error="errorHandler"
			ref="scrollDiv"
			@scroll="handleScroll"
		/>
	</div>
</template>

<script setup>
	import classCentre from '@/api/student/classCentre'
	import { message } from 'ant-design-vue'
	import VueOfficePdf from '@vue-office/pdf'
	const scrollDiv = ref(null)
	const scrollPercent = ref(0)
	const showPdf = ref(true)
	const props = defineProps({
		itemObj: {
			type: Object,
			default: () => {}
		},
		hourId: {
			type: [String, Number],
			default: 0
		}
	})
	function errorHandler() {
		showPdf.value = false
	}
	const maxStr = ref(0)
	function handleScroll() {
		const el = scrollDiv.value.$el
		if (!el) return
		const scrollTop = el.scrollTop
		const scrollHeight = el.scrollHeight
		const clientHeight = el.clientHeight
		// 计算百分比
		scrollPercent.value = Math.round((scrollTop / (scrollHeight - clientHeight)) * 100)
		if (scrollPercent.value > maxStr.value) {
			maxStr.value = scrollPercent.value
		}
	}
	const downPdf = () => {
		const link = document.createElement('a')
		link.href = props.itemObj.url
		link.download = props.itemObj.name
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
		message.success('开始下载文件')
		addClassPlan()
	}
	const nowTimesStr = Date.now()
	const outNowTimesStr = ref()
	const addClassPlan = () => {
		classCentre
			.classPlanAdd({
				hourId: props.hourId,
				type: 2,
				funcType:2
			})
			.then((data) => {})
	}
	const addScrollPlan = () => {
		classCentre
			.classPlanAdd({
				progress: maxStr.value,
				hourId: props.hourId,
				stayTime: outNowTimesStr.value - nowTimesStr,
				type: 1,
				funcType:2
			})
			.then((data) => {})
	}
	onBeforeUnmount(() => {
		outNowTimesStr.value = Date.now()
		addScrollPlan()
	})
</script>
<style scoped lang="less">
	.flc {
		display: flex;
		align-items: center;
	}
	.fcbc {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
