<template>
	<view class="ezy-course-page">
		<view class="icon-title-navBar-box">
			<view @click="goUpPage" class="nav-bar-icon"></view>
			<text class="nav-bar-title">视频播放</text>
		</view>
		<view ref="videoContent" id="wgy-player-test" :playAuth="playAuth" :change:playAuth="renderScript.receiveMsg"
			:videoId="videoId" :change:videoId="renderScript.videoIdFun" :hideFlag="hideFlag"
			:change:hideFlag="renderScript.hideFlagFun" :progressMarkers="progressMarkers"
			:change:progressMarkers="renderScript.progressMarkersMsg" :seekTime="seekTime"
			:change:seekTime="renderScript.seekTimeFun" class="course-video-box">
		</view>
		<view class="course-content-border">
			<view class="course-content-box">
				<view class="course-title">{{jieName}}</view>
				<view v-for="(item,index) in progressMarkers" :key="index" @click="markersClick(item)"
					class="course-content-item">
					<view class="course-play-btn"></view>
					<view class="course-content">
						<text>{{item.title}}</text>
						<text class="content-kcwz">课程位置：{{item.time}}</text>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popupRef" :animation="false" :is-mask-click="false"
			mask-background-color="rgba(255, 255, 255, 0.6);">
			<view class="course-score-dialog">
				<view class="text-score">20</view>
				<view class="course-btn-box">
					<view @click="goBack" class="return-btn"></view>
					<view @click="goNext" class="continue-btn"></view>
				</view>
			</view>
		</uni-popup>


	</view>
</template>

<script>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';
	import {
		videoPolicy,
		getVideoAuth,
		getVideoRefresh
	} from "@/api/shipin.js"
	import {
		toast,
		getUserIdentity
	} from "@/utils/common";
	import {
		userZhangNextInfo,
	} from "@/api/learnPlan.js"
	import cacheManager from "@/utils/cacheManager.js";
	export default {
		data() {
			return {
				pageData: null, //上个页面获取的视频参数（视频id）
				playAuth: "", //播放凭证
				progressMarkers: [],
				jieName: '',
				hideFlag: 'show',
				videoId: "", //阿里云视频id
				seekTime: '',
				jieNumber: '',
				cacheZhangInfo: {}
			}
		},
		onLoad(options) {

			this.init(options)

		},
		onHide() {
			console.log('onHideonHideonHideonHide');
			this.hideFlag = 'hide'
		},
		onUnload() {
			console.log('onUnloadonUnloadonUnloadonUnloadonUnload');
			this.hideFlag = 'hide'
		},
		methods: {
			init(options) {
				this.jieNumber = options.jieNumber
				if (!(cacheManager.get('zhangInfo') && options.jieNumber)) {
					toast('数据错误,缓存丢失/ number丢失')
					return false
				}
				this.cacheZhangInfo = cacheManager.get('zhangInfo')

				let currentObject = this.cacheZhangInfo.jieList.find(item => item.number == options.jieNumber);
				// lastFlag是否是本章最后一节,0否1是  type，1视频，2试题
				if (currentObject.lastFlag == 1 && currentObject.type == 2) {
					uni.redirectTo({
						url: `/pages/unitTest/index`
					})
				} else if (currentObject.lastFlag == 1 && currentObject.type == 1) {
					// 当前是本章最后一节，并且是 视频 切换下一章
					this.goNextZhang()
				} else {
					this.pageData = {
						...currentObject
					}
					console.log(this.pageData);
					this.videoId = this.pageData.videoId
					this.jieName = this.pageData.jieName
					this.progressMarkers = this.pageData.jiedianList
					this.getLive(); //获取播放凭证
				}
			},
			goNextZhang() {
				let that = this
				let req = {
					nianji: that.currentObject.nianji,
					zhangId: that.currentObject.zhangId,
					cardId: that.currentObject.cardId,
				}
				userZhangNextInfo(req).then(res => {
					cacheManager.set('zhangInfo', res.data)
					cacheManager.updateObject('auth', {
						zhangId: res.data.zhangId,
						cardId: res.data.cardId,
						nianji: res.data.nianji,
					})
					that.init({jieNumber: 1})
				})
			},
			playEnd(data) {
				this.$refs.popupRef.open();
			},
			goBack() {
				this.$refs.popupRef.close();
				this.goUpPage()
			},
			goNext() {
				this.$refs.popupRef.close();
				this.hideFlag = "show"
				this.videoId = ''
				this.progressMarkers = []
				this.pageData = null
				this.playAuth = ''
				this.cacheZhangInfo = {}
				Number(this.jieNumber++)
				// this.init({
				// 	jieNumber: this.jieNumber
				// })
				uni.redirectTo({
					//url: '/pages/study/lookShipin?studyData=' + JSON.stringify(pageData)
					url: '/pages/study/lookShipin?jieNumber='+this.jieNumber
				})
			},
			getLive() {
				let req = {
					videoId: this.videoId
				}
				getVideoAuth(req).then(res => {
					this.playAuth = res.data
				})
			},
			markersClick(data) {
				console.log(data)
				this.seekTime = data.offset
			},
			goUpPage() {
				// this.$refs.popupRef.open();
				uni.redirectTo({
					//	url: `/pages/study/index?xueqi=${data.activeXueqi}&nianji=${data.activeNianji}&flag=selectGrades`
					url: `/pages/study/index`

				})
			}

		},
		created() {
			// console.log("getLive")
			// this.getLive(); //获取播放凭证

		},

	}
</script>



<script module="renderScript" lang="renderjs">
	export default {
		mounted() {
			console.log("renderScript1")
			// 在适合的生命周期，通过script和link标签引入播放器sdk、css
			this.loadWebPlayerSDK()
		},
		data() {
			return {
				player: null,
				playAuth: '',
				videoId: '',
				progressMarkers: [],
				seekTime: ''

			}
		},
		methods: {

			receiveMsg(newValue, oldValue, ownerInstance, instance) {
				// console.log('service层中的options发生变化')
				// console.log('新值', newValue)
				// console.log('旧值', oldValue)
				// ownerInstance和this.$ownerInstance一样，可用来向service层通信
				// instance和ownerInstance的区别是：
				// instance.$el指向的是触发事件的那个节点；ownerInstance.$el指向当前vue文件中的根节点；
				// instance的作用目前尚不明确，官方没有给出用法
				if (newValue) {
					this.playAuth = ''
					this.playAuth = newValue
					this.playAli()
				}
			},
			videoIdFun(newValue, oldValue, ownerInstance, instance) {
				if (newValue) {
					this.videoId = ''
					this.videoId = newValue
				}
			},
			hideFlagFun(newValue, oldValue, ownerInstance, instance) {
				if (this.player) {
					this.player.pause()
				}
			},
			progressMarkersMsg(newValue, oldValue, ownerInstance, instance) {

				if (newValue) {
					this.progressMarkers = newValue
				}
			},
			seekTimeFun(newValue, oldValue, ownerInstance, instance) {

				if (newValue) {
					console.log(newValue, 'newValuenewValuenewValuenewValuenewValue')
					console.log(this.player.getStatus(), 'newValuenewValuenewValuenewValuenewValue')
					this.player.play()
					this.player.seek(newValue)
					// switch (this.player.getStatus()) {
					// 	case 'init':
					// 		break;
					// 	case 'ready':
					// 		break;
					// 	case 'loading':
					// 	this.player.play()
					// 	this.player.seek(newValue)
					// 		break;
					// 	case 'play':
					// 		this.player.seek(newValue)
					// 		break;
					// 	case 'pause':
					// 	this.player.play()
					// 	this.player.seek(newValue)
					// 		break;
					// 	case 'playing':
					// 	this.player.seek(newValue)
					// 		break;
					// 	case 'waiting':
					// 		break;
					// 	case 'error':
					// 		break;
					// 	case 'ended':
					// 		break;
					// 	default:
					// 		break;
					// }
					//	this.player.seek(newValue)
				}
			},
			playAli() {
				let that = this
				console.log(this.videoId);
				console.log(this.playAuth);
				//配置播放器
				var player = new Aliplayer({
					id: "wgy-player-test",
					"vid": this.videoId,
					"playauth": this.playAuth,
					// "playConfig": {
					// 	"EncryptType": 'AliyunVoDEncryption'
					// },
					"skinLayout": [{
							"name": "bigPlayButton",
							"align": "blabs",
							"x": 30,
							"y": 80
						},
						{
							"name": "controlBar",
							"align": "blabs",
							"x": 0,
							"y": 0,
							"children": [{
									"name": "progress",
									"align": "blabs",
									"x": 0,
									"y": 44
								},
								{
									"name": "playButton",
									"align": "tl",
									"x": 15,
									"y": 12
								},
								{
									"name": "fullScreenButton",
									"align": "tr",
									"x": 10,
									"y": 12
								}
							]
						}
					],
					"qualitySort": "asc",
					"format": "mp4",
					"mediaType": "video",
					"encryptType": 1,
					"progressMarkers": this.progressMarkers,
					"width": '100%',
					"height": '500px',
					"autoplay": false,
					"isLive": false,
					"rePlay": false,
					"playsinline": true,
					"preload": false,
					"controlBarVisibility": "hover",
					"useH5Prism": true

				}, function(player) {});
				this.player = player;
				player.on('canplay', function() {
					console.log('canplay', this.player.tag);
					player.tag.play();

				});
				player.on('ended', function() {
					that.$ownerInstance.callMethod('playEnd', {
						data: 'end'
					})
					// uni.$emit('playEnd', {
					// 	data: 'end'
					// });
				});
			},


			loadWebPlayerSDK() {
				return new Promise((resolve, reject) => {
					const s_tag = document.createElement('script'); // 引入播放器js
					s_tag.type = 'text/javascript';
					s_tag.src = 'https://g.alicdn.com/de/prismplayer/2.9.6/aliplayer-min.js';
					s_tag.charset = 'utf-8';
					s_tag.onload = () => {
						//	this.playAli()
						resolve();
					}
					document.body.appendChild(s_tag);
					const l_tag = document.createElement('link'); // 引入播放器css
					l_tag.rel = 'stylesheet';
					l_tag.href =
						'https://g.alicdn.com/de/prismplayer/2.9.6/skins/default/aliplayer-min.css';
					document.body.appendChild(l_tag);
				});
			},
		}
	}
</script>