<template>
	<a-layout>
		<a-layout-sider v-model:collapsed="collapsed" :trigger="null" collapsible collapsedWidth="0">
			<div class="classTitle">
				<div>{{ classDetail.courseName }}</div>
			</div>
			<a-menu
				v-model:openKeys="openKeys"
				v-model:selectedKeys="selectedKeys"
				theme="dark"
				mode="inline"
				@click="menuClick"
			>
				<a-sub-menu :key="String(idx + 1)" v-for="(item, idx) in classTimeList">
					<template #title>{{ item.name }}</template>
					<a-menu-item :key="itemc.id" v-for="(itemc, idxc) in item.classHours">
						<span class="mr-2">
							<CheckSquareOutlined v-if="selectedKeys.includes(itemc.id)" />
							<BorderOutlined v-else />
						</span>
						<span>{{ itemc.name }}</span>
					</a-menu-item>
				</a-sub-menu>
			</a-menu>
		</a-layout-sider>
		<a-layout>
			<a-layout-header style="padding: 0 20px">
				<div class="flex-between">
					<div>
						<menu-unfold-outlined
							v-if="collapsed"
							class="trigger"
							@click="() => (collapsed = !collapsed)"
							style="font-size: 30px; color: #fff"
						/>
						<menu-fold-outlined
							v-else
							class="trigger"
							@click="() => (collapsed = !collapsed)"
							style="font-size: 30px; color: #fff"
						/>
					</div>
					<div @click="isLike">
						<a-tooltip title="收藏" style="cursor: pointer" :getPopupContainer="(trigger) => trigger.parentElement">
							<heart-outlined :style="{ 'font-size': '20px', color: classDetail.isCollect ? '#ff4d4f' : '#fff' }" />
						</a-tooltip>
					</div>
				</div>
			</a-layout-header>
			<a-layout-content style="overflow-y: auto">
				<a-card :bordered="false">
					<video
						style="height: 900px; width: 100%; background-color: #000"
						ref="videoRef"
						controls
						Controlslist="nodownload noplaybackrate noremoteplayback disablePictureInPicture"
						@timeupdate="timeUpdate"
						:currentTime="currentTimenew"
					>
						<source :src="videoUrl" type="video/mp4" />
						<source :src="videoUrl" type="video/ogg" />
						您的浏览器不支持 HTML5 video 标签。
					</video>
					<rightMenu :idsObj="idsObj" :dataList="classTimeData" ref="rightNenuRef" @videoSpeed="videoSpeed"></rightMenu>
				</a-card>
				<div style="display: flex; justify-content: center">
					<a-card :bordered="false" class="mt-2" style="width: 1200px">
						<a-tabs v-model:activeKey="tabsActiveKey">
							<a-tab-pane key="1" tab="讲义">
								<handouts :itemObj="itemObj" :hourId="classHourData.id" v-if="classHourData"></handouts>
							</a-tab-pane>
							<a-tab-pane key="2" tab="字幕">
								<subtitleBox :url="danmuObj.url" @videoSpeed="videoSpeed"></subtitleBox>
							</a-tab-pane>
							<a-tab-pane key="3" tab="笔记">
								<note :idsObj="idsObj" ref="noteRef" @edit="noteEdit"></note>
							</a-tab-pane>
							<a-tab-pane key="4" tab="问答">
								<askDiv :idsObj="idsObj" ref="askDivRef" @edit="askEdit"></askDiv>
							</a-tab-pane>
						</a-tabs>
					</a-card>
				</div>
				<forumBtn :forumData="forumData" resourceType="0"></forumBtn>
			</a-layout-content>
		</a-layout>
	</a-layout>
</template>

<script setup name="classCentre">
	import classCentre from '@/api/student/classCentre'
	import rightMenu from './rightMenu.vue'
	import { useRoute, useRouter } from 'vue-router'
	import sysConfig from '@/config/index'
	import note from './note.vue'
	import askDiv from './ask.vue'
	import handouts from './handouts.vue'
	import subtitleBox from './subtitle.vue'

	const route = useRoute()
	const router = useRouter()
	const classDetail = ref({})
	const classTimeList = ref([])
	const classTimeData = ref([])
	const openKeys = ref(['1'])
	const selectedKeys = ref([])
	const collapsed = ref(false)
	const videoRef = ref()
	const currentTimenew = ref(0)
	const idsObj = computed(() => {
		let item = findNodeByKey(classTimeList.value, selectedKeys.value[0])
		return {
			courseId: route.query.id,
			chapterId: selectedKeys.value[0],
			hourId: classHourData.value?.id,
			...item
		}
	})
	function findNodeByKey(list, id) {
		for (const item of list) {
			if (item.id === id) {
				return item
			}
			if (item.classHours && Array.isArray(item.classHours)) {
				const found = findNodeByKey(item.classHours, id)
				if (found) return found
			}
		}
		return null
	}
	const getClassData = () => {
		classCentre.addViewCount({ courseId: route.query.id })
		classCentre.courseDetail({ courseId: route.query.id }).then((data) => {
			classDetail.value = data
			classCentre.coursechapterList({ courseId: data.courseId }).then((data) => {
				classTimeList.value = data
				selectedKeys.value = [data[0]?.classHours[0].id]
				if (selectedKeys.value[0]) {
					menuClick()
				}
			})
		})
	}
	const classHourData = ref()
	const menuClick = (e) => {
		classCentre.courseTimeDetail({ id: e?.key ? e.key : selectedKeys.value[0] }).then((data) => {
			classHourData.value = data
			classTimeData.value = data.courseRelates.map((r) => {
				return {
					...r,
					url: sysConfig.FILE_URL + r.url
				}
			})
			videoRef.value.src = classTimeData.value.filter((r) => r.funcType == 1)[0]?.url
			footprintClassAdd()
			getVideoTime()
		})
	}

	const tabsActiveKey = ref('1')
	const noteRef = ref()
	const askDivRef = ref()
	const itemObj = computed(() => {
		let item = classTimeData.value.length > 0 ? classTimeData.value.filter((r) => r.funcType == 2)[0] : { url: '' }
		return item
	})
	const danmuObj = computed(() => {
		let item = classTimeData.value.length > 0 ? classTimeData.value.filter((r) => r.funcType == 3)[0] : { url: '' }
		return item
	})
	const videoUrl = ref('')
	const newsschedule = ref(0)
	const currTime = ref(null)
	const maxTime = ref(0)
	const initialtime = ref(0)
	const videoContext = ref()
	const timeStamp1 = ref()
	const allTime = ref()
	const biNum = ref()
	const currentTime = ref()
	const videoStart = () => {
		videoContext.value = videoRef.value
		if (initialtime.value > 0) {
			videoContext.value.currentTime = initialtime.value
			timeStamp1.value = initialtime.value
		}
	}

	const timeUpdate = (e) => {
		//获取当前播放时间 durationinitialtime
		if (timeStamp1.value != parseInt(e.target.currentTime)) {
			allTime.value = parseInt(e.target.duration) //视频总时长（秒）
			//对播放的时间进行整
			timeStamp1.value = parseInt(e.target.currentTime) //播放进度 (秒)
			biNum.value = Math.floor((timeStamp1.value / allTime.value) * 10000) / 100 //暂时没用到
			currentTime.value = e.target.currentTime
			if (e.srcElement.currentTime - currTime.value > 3) {
				addClassPlan(3)
				console.log('快进了')
			}
			if (currTime.value - e.srcElement.currentTime > 3) {
				addClassPlan(3)
				console.log('快退了')
			}
			currTime.value = e.srcElement.currentTime
			// if (videoJumpTime.value) {
			// 	videoJumpTime.value = false
			// 	newsschedule.value = currentTime.value
			// } else {
			// 	if (newsschedule.value <= currentTime.value) {
			// 		//请求接口获取的参数就是判断当前观看的时长是否小于当前时间 小于当前时间就禁止拖动进度条

			// 		if (e.srcElement.currentTime - currTime.value > 3) {
			// 			//这里拖动进度条时间 - 当前观看的时长 > 3秒 这边判定它为拖动进度条
			// 			e.srcElement.currentTime = currTime.value > maxTime.value ? currTime.value : maxTime.value
			// 			let newsVal = initialtime.value
			// 			if (newsVal) {
			// 				videoContext.value.currentTime = newsVal
			// 			}
			// 			//当前用户记录观看时间 大于 实施播放时间
			// 			if (currTime.value > newsVal) {
			// 				videoContext.value.currentTime = currTime.value
			// 			}
			// 			console.log('快进了')
			// 		}
			// 		currTime.value = e.srcElement.currentTime
			// 		maxTime.value = currTime.value > maxTime.value ? currTime.value : maxTime.value
			// 	}
			// }
		}
	}

	const rightNenuRef = ref()
	const noteEdit = (e) => {
		rightNenuRef.value.selectBtn({ key: 6, type: 2 }, e)
	}
	const askEdit = (e) => {
		rightNenuRef.value.selectBtn({ key: 7, type: 4 }, e)
	}
	const videoJumpTime = ref(false)
	const videoSpeed = (e) => {
		videoJumpTime.value = true
		currentTimenew.value = e.startTime
	}

	const forumData = computed(() => {
		let item = findNodeByKey(classTimeList.value, selectedKeys.value[0]) ?? {}
		if (!item.src) {
			item.src = classTimeData.value.filter((r) => r.funcType == 1)[0]?.url
		}
		return {
			id: classHourData.value?.id,
			title: item?.name,
			videoUrl: btoa(encodeURIComponent(videoRef.value?.src ? videoRef.value.src : item.src)),
			courseId: route.query.id,
			chapterId: selectedKeys.value[0],
			courseName: classDetail.value?.courseName,
			chapterName: classHourData.value?.name
		}
	})
	const showPdf = ref(true)
	function errorHandler() {
		showPdf.value = false
	}
	const getVideoTime = () => {
		classCentre
			.theLastDetail({
				funcType: 1,
				type: 1,
				hourld: classHourData.value?.id
			})
			.then((data) => {
				if (data.endTime) {
					initialtime.value = parseFloat(data.endTime) / 1000
					currentTimenew.value = parseFloat(data.endTime) / 1000
				}
			})
	}

	// 毫秒转换时分秒
	function msToHMS(ms) {
		if (typeof ms !== 'number' || isNaN(ms)) return '00:00:00'
		let totalSeconds = Math.floor(ms / 1000)
		let hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
		let minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
		let seconds = String(totalSeconds % 60).padStart(2, '0')
		return `${hours}:${minutes}:${seconds}`
	}
	// 时分秒转换毫秒
	function hmsToMs(hms) {
		if (!hms) return 0
		const parts = hms.split(':').map((p) => parseFloat(p.replace(',', '.')))
		// 支持 hh:mm:ss 或 mm:ss
		let ms = 0
		if (parts.length === 3) {
			ms = (parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000
		} else if (parts.length === 2) {
			ms = (parts[0] * 60 + parts[1]) * 1000
		} else if (parts.length === 1) {
			ms = parts[0] * 1000
		}
		return ms
	}
	onBeforeUnmount(() => {
		addClassPlan(1)
	})
	const nowTimesStr = Date.now()
	const outNowTimesStr = ref()
	const addClassPlan = (type) => {
		outNowTimesStr.value = Date.now()
		let progress = parseFloat((videoRef.value?.currentTime / videoRef.value?.duration) * 100)
		if (
			(progress || progress == 0) &&
			(initialtime.value || initialtime.value == 0) &&
			(videoRef.value.currentTime || videoRef.value.currentTime == 0)
		) {
			classCentre
				.classPlanAdd({
					startTime: parseFloat(initialtime.value),
					endTime: Math.round(videoRef.value.currentTime * 1000),
					progress: Math.round(progress),
					hourId: classHourData.value?.id,
					stayTime: outNowTimesStr.value - nowTimesStr,
					type: type,
					funcType: type
				})
				.then((data) => {})
		}
	}
	const isLike = () => {
		classCentre
			.classCollectAdd(
				{
					courseId: route.query.id
				},
				classDetail.value.isCollect
			)
			.then(() => {
				classCentre.courseDetail({ courseId: route.query.id }).then((data) => {
					classDetail.value = data
				})
			})
	}
	//足迹
	const footprintClassAdd = () => {
		classCentre.footprintClassAdd({
			hourName: classHourData.value.name,
			chapterName: classHourData.value.name,
			courseName: classDetail.value.courseName,
			hourId: classHourData.value.id,
			chapterId: selectedKeys.value[0],
			courseId: classDetail.value.courseId,
			fileId: classHourData.value.courseRelates.filter((r) => r.funcType == 1)[0].relateId,
			fileName: classHourData.value.courseRelates.filter((r) => r.funcType == 1)[0].name,
			filePath: classHourData.value.courseRelates.filter((r) => r.funcType == 1)[0].url
		})
	}
	onMounted(() => {
		getClassData()
		getVideoTime()
		nextTick(() => {
			videoStart()
		})
	})
</script>
<style scoped lang="less">
	.classTitle {
		height: 64px;
		width: 200px;
		font-size: 18px;
		color: #ccc;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.flex-between {
		display: flex;
		justify-content: space-between;
	}
</style>
