<template>
	<view class="content">
		<view class="video">
			<video id="myVideo" :src="courseInfo.filePathOss" :poster="courseInfo.fileFirstImage" object-fit="contain"
				:title="courseInfo.fileTitle" style="width: 100vw;height: 312.5rpx;" :initial-time="viewTime"
				@timeupdate="timeupdate" @play="playVideo" @pause="pause"></video>
		</view>
		<scroll-view id="scrollView" scroll-y="true" :style="{height:scrollViewHeight+'px'}"
			@scrolltolower="scrolltolower">
			<view class="videoDetailBox">
				<view class="videoTitleBox">
					<view>
						{{courseInfo.fileTitle}}
					</view>
					<view :class="isShow?'iconTop':'iconBottom'" @click="isShow=!isShow">
						<text class="iconfont icon-youjiantou"></text>
					</view>
				</view>
				<view class="videoUser">
					<view class="videoUserImage">
						<image :src="lecturerInfo.lecturerUrl" style="height: 70rpx;border-radius: 200rpx;"
							mode="aspectFit"></image>
					</view>
					<view class="videoUserContent">
						<view class="videoUserName">
							{{lecturerInfo.lecturerName}}
						</view>
						<!-- <view class="videoUserRank">
							高级讲师
						</view> -->
					</view>
				</view>
				<view class="videoDetail" v-if="isShow">
					<view v-html="courseInfo.fileIntroduce"></view>
				</view>

			</view>
			<view style="border-top: 1rpx solid #eee;">

			</view>
			<view class="relatedVideoBox">
				<view class="tagBox">
					<view class="tagItem">
						相关视频
					</view>
				</view>
				<view class="relatedVideoList" v-if="relatedCourseList.length>0">
					<view class="relatedVideoItem" v-for="item in relatedCourseList" @click="play(item)">
						<view style="width: 46.5vw;">
							<image style="height: 46.5vw;border-radius: 16rpx;" :src="item.displayImage"
								mode="aspectFill"></image>
						</view>
						<view class="relatedVideoTitle">
							{{item.fileTitle}}
						</view>
					</view>
				</view>
				<view v-else
					style="text-align: center;font-weight: 600;font-size: 42rpx;margin-top:50rpx;color: #8c8c8c;">
					暂无相关视频
				</view>
				<!-- <uni-load-more iconType="circle" :status="moreStatus"></uni-load-more> -->
			</view>
		</scroll-view>


	</view>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import api from "@/api/api";
	import { cffpURL } from "@/environments/environment";
	import common from '../../common/common';
	import { onLoad, onReady, onUnload, onPageScroll } from "@dcloudio/uni-app";

	let windowHeight = ref(0);
	let scrollViewHeight = ref(0);
	//是否展示详细信息
	const isShow = ref(false);
	// more/loading/noMore
	let moreStatus = ref('more');

	let userId = ref('');
	let videoId = ref('');
	//课程
	let courseInfo = ref({
		filePathOss: '',
		fileFirstImage: '',
		fileTitle: '',
		fileIntroduce: '',
		packFileId: ''
	});
	//讲师
	let lecturerInfo = ref({
		lecturerUrl: '',
		lecturerName: '',
		lecturerIntroduce: ''
	});
	//相关视频
	let relatedCourseList = ref([]);


	//视频组件上下文
	const videoContext = ref(null);
	//播放起始时间
	const viewTime : any = ref(0);
	//视频时长
	const totalTime : any = ref(0);
	//视频是否暂停状态
	const isPauseFlag = ref(true);
	//新的视频信息
	const newCourseInfo = ref({
		fileId: '',
		packFileId: ''
	});

	//视频播放最新记录
	const videoPlaybackInfo = ref({
		id: '',
		viewTime: '',
		totalTime: ''
	});

	//保存记录后返回的Id
	const playbackId = ref(null);
	//定时器
	const timer = ref(null);
	const packFileId = ref(null);

	// 相关列表点击播放
	const play = async item => {

		if (videoId.value != item.fileId) {
			videoContext.value.pause();
			// 当点击的课程和当前播放的课程不一致时，执行此方法
			uni.showLoading({
				title: '加载中'
			});
			uni.setStorageSync('cffp_videoId', item.fileId);
			newCourseInfo.value = {
				fileId: item.fileId,
				packFileId: item.packFileId,
			}
			if (isPauseFlag) {
				pause();
			}
		} else {
			uni.showToast({
				title: '当前播放已是此视频',
				icon: 'none'
			})
		}
	}

	const saveVideoPlayback = () => {
		// 视频播放轨迹保存
		const param = {
			id: playbackId.value ? playbackId.value : null,
			systemType: 1,
			userId: userId.value,
			fileId: videoId.value,
			packFileId: courseInfo.value.packFileId,
			totalTime: Math.floor(totalTime.value),
			viewTime: Math.floor(viewTime.value),
			playbackStatus: viewTime.value >= totalTime.value ? '2' : '1'
		}
		return new Promise((resolve, reject) => {
			if (viewTime.value == 0) {
				resolve('success');
				return;
			}
			api.saveVideoPlayback(param).then(res => {
				if (res['success']) {
					playbackId.value = res['data']['id'];
					resolve('success');
				} else {
					reject('fail')
				}
			}).catch((err) => {
				reject('fail')
			})
		})

	}
	const findVideoPlayback = () => {
		// 查询视频播放最新记录
		const param = {
			systemType: 1,
			userId: userId.value,
			fileId: videoId.value,
			packFileId: courseInfo.value.packFileId,
		}
		api.findVideoPlayback(param).then(res => {
			if (res['success']) {
				videoPlaybackInfo.value = res['data'];
				viewTime.value = videoPlaybackInfo.value.viewTime ?? 0;
				totalTime.value = videoPlaybackInfo.value.totalTime ?? 0;
				packFileId.value = videoPlaybackInfo.value.id ?? null;
				// this.isRenderVideo = true;
				// 跳转到指定位置
				if(viewTime.value!=0){
					videoContext.value.seek(viewTime.value);
				}
				
				uni.hideLoading();
			} else {
				// this.isRenderVideo = true;
				totalTime.value = viewTime.value = 0;
				// 跳转到指定位置
				if(viewTime.value!=0){
					videoContext.value.seek(viewTime.value);
				}
				
				uni.hideLoading();
			}
		})
	};
	// 点击播放
	const playVideo = (e) => {
		isPauseFlag.value = false;

		if (viewTime.value >= totalTime.value) {
			viewTime.value = 0;
			videoContext.value.seek(viewTime);
		}
		// 开始/继续播放
		if (timer.value) {
			clearInterval(timer)
		}
		timer.value = setInterval(() => {
			saveVideoPlayback()
		}, 20 * 1000)
	}
	// 暂停播放
	const pause = async () => {
		isPauseFlag.value = true;
		if (timer.value) {
			clearInterval(timer.value)
		}
		const result = await saveVideoPlayback();
		if (result == 'success' && newCourseInfo.value.fileId) {
			videoId.value = newCourseInfo.value.fileId;
			courseInfo.value.packFileId = newCourseInfo.value.packFileId;
			playbackId.value = null;
			loadCourseDetail();
		}
	}
	//播放进度改变触发事件
	const timeupdate = (e) => {
		totalTime.value = e.detail.duration;
		// 播放进度变化
		viewTime.value = e.detail.currentTime > totalTime.value ? totalTime.value : e.detail.currentTime;
	}


	//滑动到底事件
	const scrolltolower = res => {
		if (moreStatus.value != 'loading') {
			moreStatus.value = 'loading';
		}
	}

	//增加访问记录
	const accessLogSave = () => {
		api.accessLogSave({

			"userId": userId.value, "sessionId": 'sessionId',
			"accessUrl": cffpURL + "/myPackageA/videoProject/videoDetail?videoId=" + videoId.value, "accessType": 'cffpVideo', businessId: videoId.value, remark: '视频播放'

		}).then(res => {
			if (res['success']) {

			}
		});
	}
	//查询课程详情
	const loadCourseDetail = () => {
		api.courseDetail({
			fileId: videoId.value,
			userId: userId.value,
			packFileId: courseInfo.value.packFileId
		}).then(res => {
			if (res['success']) {
				courseInfo.value = res['data']['data'];
				lecturerQuery(res['data']['data']['fileLecturerId']);
				loadRelatedCoursesList();
				findVideoPlayback();
			}
		})
	}
	// 讲师信息查询
	const lecturerQuery = (fileLecturerId) => {
		api.lecturerQuery({
			id: fileLecturerId
		}).then(res => {
			if (res['success']) {
				lecturerInfo.value = res['data']['lecturerInfos'][0];
			} else {
				uni.showToast({
					title: res['message'],
					duration: 2000,
					icon: 'none'
				})
			}
		})
	}
	// 加载相关视频
	const loadRelatedCoursesList = () => {
		api.relatedCoursesList({
			fileId: videoId.value,
			userId: userId.value,
			orderId: null,
			packFileId: courseInfo.value.packFileId,
		}).then(res => {
			if (res['success']) {
				relatedCourseList.value = res['data']['data']['relatedCourseList'];
			} else {
				uni.showToast({
					title: res['message'],
					duration: 2000,
					icon: 'none'
				})
			}
		})
	}
	onLoad(option => {
		//视频Id
		if (option.videoId && option.videoId!='null') {
			uni.setStorageSync('cffp_videoId', option.videoId);
			videoId.value = option.videoId;
		} else {
			videoId.value = uni.getStorageSync('cffp_videoId');
		}
		//用户Id
		userId.value = uni.getStorageSync('video_userId');
	})
	onReady(() => {
		videoContext.value = uni.createVideoContext('myVideo');
		//窗口高度
		windowHeight.value = uni.getSystemInfoSync().windowHeight;
		//元素距离顶部距离
		uni.createSelectorQuery().select('#scrollView').boundingClientRect(data => {
			scrollViewHeight.value = windowHeight.value - data['top'];
		}).exec();
		if (!userId.value || !videoId.value) {
			uni.showToast({
				title: '登录过期,请重新登录',
				icon: 'none'
			});
			uni.reLaunch({
				url: '/myPackageA/videoProject/login?videoId=' + videoId.value
			});
			return;
		}else{
			accessLogSave();
			loadCourseDetail();
		}
	})
	onUnload(() => {
		if (viewTime.value != 0) {
			videoContext.value.pause();
			saveVideoPlayback();
			if (timer.value) {
				clearInterval(timer.value)
			}
		}
	})
</script>

<style lang="scss">
	.content {
		color: #000;

		.videoDetailBox {
			padding: 15rpx 25rpx 0rpx 25rpx;
			position: relative;

			.videoTitleBox {
				font-weight: 600;
				font-size: 34rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.iconBottom {
					transform: rotate(90deg);
				}

				.iconTop {
					transform: rotate(-90deg);
				}
			}

			.videoUser {
				display: flex;
				align-items: center;
				margin: 20rpx 0 10rpx 0;

				.videoUserContent {
					// .videoUserRank{
					// 	background: #5359CD;
					// 	border-radius: 10rpx;
					// 	color: #fff;
					// 	padding: 4rpx 20rpx;

					// }
					.videoUserName {
						padding-bottom: 20rpx;
						font-size: 32rpx;
					}
				}

				.videoUserImage {
					width: 70rpx;
					margin-right: 15rpx;

				}
			}

			.videoDetail {
				color: #414141;
				font-size: 30rpx;
				padding-bottom: 20rpx;
				overflow: hidden;
			}
		}

		.relatedVideoBox {
			.tagBox {
				display: flex;
				justify-content: center;

				.tagItem {
					padding: 20rpx 0;
					font-size: 32rpx;
					color: #ff5e84;
					border-bottom: 6rpx solid #ff5e84;
				}
			}

			.relatedVideoList {
				display: flex;
				flex-wrap: wrap;
				gap: 3vw;
				padding: 2vw;

				.relatedVideoItem {
					width: 46.5vw;

					.relatedVideoTitle {
						font-size: 28rpx;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
						height: 79rpx;
					}
				}
			}
		}
	}
</style>