<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">{{shipinTitle}}</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)">
					<view class="title-play-box">
						<text class="course-title">{{item.title}}</text>
						<view class="course-play-btn" @click="markersClick(item)"></view>
					</view>
					<rich-text :nodes="item.describe" class="course-content-item"></rich-text>
				</view>
			</view>
		</view>
		<uni-popup ref="popupRef" :animation="false" :is-mask-click="false"
			mask-background-color="rgba(255, 255, 255, 0.6);">
			<view :class="courseClass">
				<view class="text-score">{{credit}}</view>
				<view class="course-btn-box">
					<view @click="goBack" class="return-btn"></view>
					<view @click="goNext" class="continue-btn"></view>
				</view>
			</view>
		</uni-popup>
		<tip-middle-dialog ref="youkeDialogRef" @confirm-btn="ykConfirm" :content="YouKeContent"></tip-middle-dialog>
		<svip-dialog ref="svipDialogRef" @confirm-btn="svipConfirm"></svip-dialog>
	</view>

</template>

<script>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';
	import {
		getVideoAuth,
		getVideoAuthYk,
		videoWancheng
	} from "@/api/shipin.js"
	import tipMiddleDialog from '@/components/dialog/tipMiddleDialog.vue';
	import svipDialog from './svipDialog.vue';
	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
				cardId: '',
				credit: '',
				nianji: '',
				zhangId: '',
				seekTime: '',
				jieId: '',
				courseClass: '',
				shipinTitle: '',
				cacheZhangInfo: {},
				cacheCurrentZhangIndex: '',
				YouKeContent: '您当前是游客身份，登录后才能浏览内容，现在去登录？'
			}
		},
		components: {
			tipMiddleDialog,
			svipDialog
		},
		onLoad(options) {
			if (!cacheManager.get('auth')) {
				const youkeData = JSON.parse(options.youkePageData)
				// 游客
				this.videoId = youkeData.jieList[0].videoId
				this.nianji = youkeData.nianji
				this.zhangId = youkeData.zhangId
				this.cardId = youkeData.cardId
				this.shipinTitle = youkeData.jieName
				this.progressMarkers = youkeData.jieList[0].jiedianList||[]
				this.getLiveYk(); //获取播放凭证
			} else {
				this.init(options)
			}
		},
		onHide() {
			console.log('onHideonHideonHideonHide');
			this.hideFlag = 'hide'
		},
		onUnload() {
			console.log('onUnloadonUnloadonUnloadonUnloadonUnload');
			this.hideFlag = 'hide'
		},
		methods: {

			init(options) {
				this.jieId = options.jieId
				if (!(cacheManager.get('zhangInfo') && options.jieId)) {
					toast('数据错误,缓存丢失/ jieId丢失')
					return false
				}
				this.cacheCurrentZhangIndex = cacheManager.get('auth').currentZhang
				this.cacheZhangInfo = cacheManager.get('zhangInfo')

				// let zhang = this.cacheZhangInfo.zhangList.find(zhang => zhang.zhangId == this.zhangId);
				// if (!zhang) {
				// 	return
				// }
				let zhang = this.cacheZhangInfo.zhangList[this.cacheCurrentZhangIndex]
				let currentObject = zhang.jieList.find(item => item.jieId == options.jieId);
				console.log(currentObject);
				this.shipinTitle = currentObject.jieName
				this.pageData = {
					...currentObject
				}
				console.log(this.pageData);
				this.videoId = this.pageData.videoId
				this.jieName = this.pageData.jieName
				this.credit = this.pageData.credit
				this.progressMarkers = this.pageData.jiedianList || []
				this.getLive(); //获取播放凭证
			},
			goNextZhang() {
				let that = this
				cacheManager.updateObject('auth', {
					currentZhang: this.cacheCurrentZhangIndex + 1
				})
				this.cacheZhangInfo = cacheManager.get('zhangInfo')
				let zhang = this.cacheZhangInfo.zhangList[this.cacheCurrentZhangIndex + 1]
				uni.redirectTo({
					url: '/pages/study/lookShipin?jieId=' + zhang.jieList[0].jieId
				})
			},
			playEnd(data) {
				const AuthCode = getUserIdentity();
				console.log(AuthCode);
				if (AuthCode == 'Visitor') {
					return false
				} else {

					let currentJieData = cacheManager.getCurrentJieData('zhangInfo', this.cacheCurrentZhangIndex, this.jieId)
					if (currentJieData.studyFlag == 1) {
						// 学完一遍
						this.courseClass = 'course-finish-dialog'
						this.$refs.popupRef.open();
					} else {
						cacheManager.updateJieStatus('zhangInfo', this.cacheCurrentZhangIndex, this.jieId)
						this.courseClass = 'course-score-dialog'
						this.$refs.popupRef.open();
						let req = {
							credit: this.credit,
							jieId: this.jieId,
						}
						videoWancheng(req).then(res => {

						})
					}
				}

			},
			goBack() {
				this.$refs.popupRef.close();
				this.goUpPage()
			},
			goNext() {
				this.$refs.popupRef.close();
				if (!cacheManager.get('auth')) {
					console.log(this);
					this.$refs.youkeDialogRef.handleShow();
				} else {
					const AuthCode = getUserIdentity();
					console.log(AuthCode);
					if (AuthCode == 'Not-Vip') {
						this.$refs.svipDialogRef.handleShow();
						return false
					}
					//	debugger
					Number(this.jieId++)
					let currentObject = this.cacheZhangInfo.zhangList[this.cacheCurrentZhangIndex].jieList.find(item =>
						item.jieId == this.jieId);
					this.pageData = {
						...currentObject
					}
					// lastFlag是否是本章最后一节,0否1是  type，1视频，2试题
					if (this.pageData.lastFlag == 1 && this.pageData.type == 2) {
						uni.redirectTo({
							url: `/pages/unitTest/index?jieId=` + this.pageData.jieId
						})
					} else if (this.pageData.lastFlag == 1 && this.pageData.type == 1) {
						// 当前是本章最后一节，并且是 视频 切换下一章
						this.goNextZhang()
					} else {
						uni.redirectTo({
							//url: '/pages/study/lookShipin?studyData=' + JSON.stringify(pageData)
							url: '/pages/study/lookShipin?jieId=' + this.jieId
						})
					}
				}
			},
			getLiveYk() {
				let req = {
					videoId: this.videoId
				}
				getVideoAuthYk(req).then(res => {
					this.playAuth = res.data
				})
			},
			getLive() {
				let req = {
					videoId: this.videoId
				}
				getVideoAuth(req).then(res => {
					this.playAuth = res.data
				})
			},
			markersClick(data) {
				this.seekTime = ""
				this.$nextTick(() => {
					this.seekTime = data.offset
				});
			},
			goUpPage() {
				if (!cacheManager.get('auth')) {
					uni.redirectTo({
						url: '/pages/study/index?cardId=' + this.cardId + '&nianji=' + this.nianji + '&zhangId=' +
							this.zhangId
					})
				} else {
					uni.redirectTo({
						url: `/pages/study/index`

					})
				}



			},
			svipConfirm() {
				uni.redirectTo({
					url: '/pages/pay/svip'
				})
			},
			ykConfirm() {
				uni.redirectTo({
					url: '/pages/login/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.loadWebPlayerSDK()

				}
			},
			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) {
					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);
				//配置播放器
				if (!this.playAuth) {
					return false;
				}
				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 = () => {
						//	console.log(this.playAuth);
						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>