<template>
	<view class="container">
		<web-view ref="webviewRef" :src="pageUrl" v-if="pageUrl" update-title allow="fullscreen" @message="handleMessage"></web-view>
		<image src="@/static/images/course_expiration_img.png" mode="aspectFill"></image>
		<view>{{msg}}</view>
	</view>
</template>

<script>
	import {getRealLink,updateSopAppLink} from "@/api/courseAnswer.js"
	//import {getUserLiveInfo} from '@/api/living.js'
	export default {
		data() {
			return {
				pageUrl:"",
				msg: '加载中...',
				userInfo: {},
				currentLiveId: null,
				currentCompanyId: null,
				currentCompanyUserId: null
			}
		},
		onLoad(option) {
			this.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : {};
			//console.log('this.liveUserId',this.liveUserId)
			//this.getUserLiveInfo()
			// const userId = this.userInfo.userId || ''
			const liveId = option.liveId
			const companyId = option.companyId
			const companyUserId = option.companyUserId
			
			this.currentLiveId = liveId;
			this.currentCompanyId = companyId;
			this.currentCompanyUserId = companyUserId;
			
			if (liveId) {
			    const baseUrl ="https://h5vips.cdwjyyh.com/appweb/pages_live/living?liveId="+liveId+"&source=app"
				//const baseUrl ="https://yjf.natappvip.cc/appweb/pages_live/living?liveId="+liveId+"&source=app"
				//const baseUrl = "http://localhost:80/appweb/pages_live/living?liveId="+liveId+"&source=app"
				// 用一个集合传参到 living（web-view 内 H5 与原生 storage 隔离）。断点续播规则由 H5 liveVideo 实现：首轮结束后有存储进度即续播，不要求先看完第一遍；本页只传 videoCurrentTime/firstPassWatched 供 H5 恢复
				const rawUserInfo = uni.getStorageSync('userInfo')
				const rawUserData = uni.getStorageSync('userData');
				const payload = {
					companyId:companyId,
					companyUserId:companyUserId,
					appToken: uni.getStorageSync('AppToken') || '',
					liveToken: uni.getStorageSync('liveToken') || '',
					videoCurrentTime:uni.getStorageSync('videoProgress_'+liveId),
					firstPassWatched:uni.getStorageSync('firstPassWatched_'+liveId),
					startTime:uni.getStorageSync('videoProgressSeek_startTime_'+liveId),
					duration:uni.getStorageSync('videoProgressSeek_duration_'+liveId),
					// 首次进入 H5 时 web-view 与原生 storage 隔离，需通过 payload 传入用户信息，否则无法初始化 WebSocket
					// userInfo: rawUserInfo,
					// userData: rawUserData
				}
				console.log("event===videoCurrentTime===",uni.getStorageSync('videoProgress_'+liveId))
				console.log("event===videoProgressSeek_startTime_===",uni.getStorageSync('videoProgressSeek_startTime_'+liveId))
				// 使用双重 encodeURIComponent 避免 web-view 内部自动解码导致含有空格等特殊字符时被截断
				this.pageUrl = baseUrl + '&payload=' + encodeURIComponent(encodeURIComponent(JSON.stringify(payload))) + '&t=' + Date.now();
				console.log("qxj pageUrl",this.pageUrl);
				//this.getLink(link)
				//this.getCourseRead(link)
			} else {
				this.msg="缺少直播Id"
				uni.showToast({
					title: "缺少直播Id",
					icon: 'error'
				})
			}
		},
		onUnload() {
			// #ifdef APP-PLUS
			// plus.navigator.setFullscreen(false);
			// plus.screen.lockOrientation('portrait-primary');
			// #endif
		},
		onBackPress() {
			// #ifdef APP-PLUS
			// 返回时退出全屏
			// plus.navigator.setFullscreen(false);
			// plus.screen.lockOrientation('portrait-primary');
			// #endif
		},
		methods: {
			getUserLiveInfo(){
				getUserLiveInfo().then((res) => {
											if (res.code == 200) {
												const liveUserId=res.user.userId
												uni.setStorageSync('liveUserId', liveUserId)
												//console.log('liveUser', res.user)
											} else {
												uni.showToast({
													icon: 'none',
													title: '请求失败'
												})
											}
										},
										(rej) => {}
								)
							},
			getCourseRead(id) {
				updateSopAppLink(id).then(res=>{
					if(res.code == 200) {
						this.$updateMsgDot()
					}
				})
			},
			handleMessage(event) {
				//console.log('点击事件',event)
				const info = event.detail.data[0]
				
				// 响应 H5 页面发起的 payload 请求
				if (info && info.action === 'requestPayload') {
					console.log('收到 H5 的 payload 请求');
					const liveId = this.currentLiveId;
					const payload = {
						companyId: this.currentCompanyId,
						companyUserId: this.currentCompanyUserId,
						appToken: uni.getStorageSync('AppToken') || '',
						liveToken: uni.getStorageSync('liveToken') || '',
						videoCurrentTime: uni.getStorageSync('videoProgress_'+liveId),
						firstPassWatched: uni.getStorageSync('firstPassWatched_'+liveId),
						startTime: uni.getStorageSync('videoProgressSeek_startTime_'+liveId),
						duration: uni.getStorageSync('videoProgressSeek_duration_'+liveId),
						userInfo: uni.getStorageSync('userInfo'),
						userData: uni.getStorageSync('userData')
					};
					// #ifdef APP-PLUS
					const currentWebview = this.$mp.page.$getAppWebview();
					const wv = currentWebview.children()[0];
					if (wv) {
						// 使用 evalJS 将数据直接注入到 H5 的 window 对象中
						wv.evalJS(`if(window.receivePayloadFromApp) { window.receivePayloadFromApp(${JSON.stringify(payload)}); }`);
					}
					// #endif
					return;
				}
				
				// #ifdef APP-PLUS
				// if(info.login != 1) {
				// 	// 退出登录
				// 	let IMUserID = uni.getStorageSync('IMUserID');
				// 	//Igexin.unbindAlias(IMUserID);
				// 	uni.removeStorage({key: "IMUserID"});
				// 	uni.setStorageSync("AppToken",null);
				// 	uni.setStorageSync("liveToken",null);		
				// 	uni.removeStorage({ key: 'IMToken' });
				// 	uni.removeStorageSync("onLaunch",null)
				// 	uni.removeStorageSync("imUnread",null);
				// 	uni.removeStorageSync("companyUser");
				// 	uni.removeStorageSync("CompanyUserToken");
					
				// 	uni.$emit("refreshUserInfo");
				// 	let pages = getCurrentPages();
					
				// 	let url = pages[ pages.length - 1]; //当前页页面实例
				// 	//如果登录界面已打开,自动关闭
				// 	if(url!=undefined&&url.route=="pages/auth/loginIndex"){
				// 		return;
				// 	}
				// 	uni.navigateTo({
				// 		url: '/pages/auth/loginIndex'
				// 	});
				// 	return
				// }
				// if (info&&info.isFullscreen) {
				// 	plus.screen.lockOrientation('landscape-primary');
				// } else {
				// 	plus.screen.lockOrientation('portrait-primary');
				// }
				//立即购买
				if(info&&info.pagesUrl) {
					if(info.isBack){
						uni.navigateBack()
					}else{
						console.log('+++++++++++++++++++++++++++++')
						uni.navigateTo({
							url: info.pagesUrl
						})
					}
					
				}
				if(info&&info.liveId) {
					// 断点续播：H5 传来进度就持久化（播放中每 10 秒、退出时 sync、设置节点时 seek）。续播规则在 H5：首轮结束后有进度即续播，不要求先看完第一遍
					if (info.videoProgress !== undefined && info.videoProgress !== null && info.videoProgress !== '') {
						uni.setStorageSync('videoProgress_'+info.liveId, info.videoProgress)
					}
					if(info.firstPassWatched){
						uni.setStorageSync('firstPassWatched_'+info.liveId, true)
					}
					// 录播设置播放节点时的附加信息（可选，供原生展示或下次传参）
					if (info.videoProgressSeek) {
						if (info.isLiveSync === true && info.startTime != null) {
							console.log('videoProgressSeek_startTime_'+info.liveId, info.startTime)
							uni.setStorageSync('videoProgressSeek_startTime_'+info.liveId, info.startTime)
						}
						if (info.duration != null) {
							uni.setStorageSync('videoProgressSeek_duration_'+info.liveId, info.duration)
						}
					}
				}
				// //
				// if(info&&info.productId) {
				// 	uni.navigateTo({
				// 		url: info.pagesUrl
				// 	})
				// }
				// console.log("event===info===",info)
				// if(info&&info.pagesUrl) {
				// 	uni.navigateTo({
				// 		url: info.pagesUrl
				// 	})
				// }
				// #endif
			},
			getLink(sortLink) {
				this.msg = '加载中...'
				const userId = this.userInfo.userId || ''
				getRealLink({sortLink: sortLink}).then(res => {
					if (res.code == 200) {
						// 如果响应中包含真实链接，则跳转到真实链接
					    let pageUrl= res.realLink + "&userId="+userId+"&source=app&time=" + new Date().getTime();
						this.pageUrl = pageUrl;
					} else {
						this.msg = '课程已过期或链接无效'
						uni.showModal({
							title: '提示',
							content: '课程已过期或链接无效',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				}).catch(err => {
					this.msg = '发生错误，请稍后再试'
					uni.showToast({
						title: '发生错误，请稍后再试',
						icon: 'none'
					});
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 88rpx;
		justify-content: center;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 32rpx;
		color: #757575;
		line-height: 48rpx;
		text-align: center;

		image {
			width: 428rpx;
			height: 360rpx;
			margin-bottom: 30rpx;
		}
	}
</style>