<template>
	<view >
		<cu-custom ref="cuCustom" bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true" :backUrl="backUrl">
			<block slot="backText">返回</block>
			<block slot="content">学习详细</block>
		</cu-custom>
		<view v-show="isNoPass" class="waring">
			<text>人脸识别失败，无法视频播放视频！</text>
		</view>
		<view v-if="TabCur == 0" class="svideo">
			<video v-if="movie.poster" id="coursewareVideo" style="width: 100%;" :src="movie.src" :poster="movie.poster" :show-progress="false"
				   :enable-progress-gesture="false" direction="-90" @play="onPlayerPlay($event)"
			 @pause="onPlayerPause($event)" @ended="onPlayerEnded($event)" @timeupdate="onPlayerTimeupdate($event)"></video>
		</view>

		<view class="sdetail">
			<scroll-view scroll-x class="bg-white nav text-center" scroll-with-animation :scroll-left="scrollLeft">
				<view class="cu-item " :class="index==TabCur?'text-blue cur':''" v-for="(item,index) in tabNav" :key="index" @tap="tabSelect"
				 :data-id="index">
					{{item.name}}
				</view>
			</scroll-view>

			<block v-if="TabCur==0">
				<view v-if="pd.VIDEOLIST.length>0">
					<view class="tcl_box" v-for="(item,index) in pd.VIDEOLIST" :key="item.COURSEWAREID">
						<view class="tcl_item">
							<view class="sleft">
								<text class=" cuIcon-videofill mr10" :class="item.COURSEWAREID == currentCoursewareID ? 'text-blue' : 'text-grey'"></text>
								<text @click="$noMultipleClicks(studyVideo,index)" class="text-title">{{item.COURSEWARENAME}}</text>
								<text v-show="item.PLAYCOUNT>0" class="text-green">(已学习)</text>
							</view>
							<view class="tcl_time">
								<view class="tcl_text">
									<text class="mr20">{{item.VIDEOTIMEFORMAT}}</text>
									<text v-if="item.VIDEOTIME != 0" >已学{{item.VIDEOPROGRESS}}%</text>
								</view>
								<button class="cu-btn bg-orange round sm" @click="$noMultipleClicks(goStudyQuestion,item)">习题练习</button>
							</view>
						</view>
					</view>
					 <!--<view class="svideol" v-for="(item,index) in pd.VIDEOLIST" :key="item.COURSEWAREID">
						<view class="sitem">
							<view class="sleft">
								<text v-if="item.COURSEWAREID == currentCoursewareID" class="text-blue cuIcon-videofill mr10"></text>
								<text @click="$noMultipleClicks(studyVideo,index)">{{item.COURSEWARENAME}}</text>
								<text v-show="item.PLAYCOUNT>0" class="text-green">(已学习)</text>
							</view>
							<view class="sright">
								<button class="cu-btn bg-green round sm" @click="$noMultipleClicks(goStudyQuestion,item)">习题练习</button>
							</view>
						</view>
					</view>-->
				</view>
				<view v-else-if="dataFlag=='noData'" class="dy-null">
					<view class="dy-null-img">
						<image src="../../../static/null.png" mode=""></image>
					</view>
					<view class="dy-null-title">
						暂无数据
					</view>
				</view>
				<view class="cu-tabbar-height"></view>
			</block>

			<block v-if="TabCur==1">
				<view v-if="pd.DATALIST.length>0">
					<view class="svideol" v-for="(item,index) in pd.DATALIST" :key="item.COURSEWAREID">
						<view class="sitem">
							<view class="sleft">
								<text class="text-blue cuIcon-newsfill mr10"></text>
<!--								<text class="text-red">(必修)</text>-->
								<text @click="$noMultipleClicks(studyData,index)">{{item.COURSEWARENAME}}</text>
								<text v-show="item.PLAYCOUNT>0" class="text-green">(已学习)</text>
							</view>
							<view class="sright">
								<button class="cu-btn bg-green round sm" @click="$noMultipleClicks(goStudyQuestion,item)">习题练习</button>
							</view>
						</view>
					</view>
				</view>
				<view v-else-if="dataFlag=='noData'" class="dy-null">
					<view class="dy-null-img">
						<image src="../../../static/null.png" mode=""></image>
					</view>
					<view class="dy-null-title">
						暂无数据
					</view>
				</view>
				<view class="cu-tabbar-height"></view>
			</block>
			<view class="bottom-fixed">
				<button class="cu-btn bg-green lg" @click="$noMultipleClicks(goExam)">课程考试</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		basePath,
		corpinfoId,
		baseImgPath,
		loginUser
	} from '@/common/tool.js';
	export default {
		data() {
			return {
				baseImgPath: baseImgPath,
				backUrl: '/pages/application/onlinexxks/my-tasks',
				loading: false,
				sTop: 0,
				totalHeight: 0,
				tabNav: [{
						name: '视频课件'
					},
					{
						name: '资料课件'
					}
				],
				TabCur: 0,
				scrollLeft: 0,
				noClick: true,
				coursewareIntroduce: '课程课件介绍',
				STAGESTUDENTRELATION_ID: '',
				coursewareFiles: '',
				coursewareCapture: '',
				list: [],
				pd: {
					STUDYTASK_ID: '',
					STUDY_NAME: '',
					COURSEWARE_COUNT: 0,
					STAGEEXAMPAPER_ID: '',
					EXAMNAME: '',
					EXAMTIME: '',
					ANSWERSHEETTIME: '',
					EXAMSCORE: '',
					QUESTIONNUM: '',
					EXAMSTATE: '',
					PASSSCORE: '',
					STAGEEXAMSTATE: '',
					STAGEEXAMSCORE: '',
					COMPLETE_COURSEWARE: 0,
					VIDEOLIST: [],
					DATALIST: [],
				}, // 数据,
				currentCoursewareListIndex: 0,
				currentCoursewareID: '',
				currentCurriculumID: '',
				videoRecord: {},
				movie: {
					'id': 0,
					'title': '课件名称',
					'src': '',	//视频地址
					'poster':'',	//封面地址
					'actors': '主讲人',
					'desc': '课件简介'
				},
				dataFlag: 'noData',
				//定时跳转人脸识别验证
				timer: null,
				seconds: 0,
				isNoPass: false,
				//视频相关
				playTime: 0,
				isPaused: false,
				currentTime:0,
				randomTiem:(Math.random()*5).toFixed(0)
			}
		},
		async onLoad(event) {
			this.STAGESTUDENTRELATION_ID = event.STAGESTUDENTRELATION_ID
			if(event.isNoPass) {
				this.isNoPass = event.isNoPass
			}
			if (event.CURRENTCOURSEWAREID) {
				this.currentCoursewareID = event.CURRENTCOURSEWAREID
				this.coursewareFiles = event.COURSEWAREFILES
				this.coursewareCapture = event.COURSEWARECAPTURE
				this.movie.poster = baseImgPath + event.COURSEWARECAPTURE
				this.movie.src = baseImgPath + event.COURSEWAREFILES
				this.playTime = event.PLAYTIME

				this.currentCoursewareListIndex = event.COURSEWAREINDEX
			}
			await this.getData()
				this.$forceUpdate()
		},
		onReady(){
			if (this.movie.src) {
				var myvideo = uni.createVideoContext('coursewareVideo')
				if (this.currentCoursewareID != '') {
					myvideo.seek(parseInt(this.playTime))
					myvideo.play()
					if(this.timer) {
						clearInterval(this.timer)
						this.timer = null
					}
					// console.info('this.randomTiem:'+(Number(this.randomTiem)+10))
					this.timer = setInterval(this.startTimer, 1000)
				}
			} else {
				uni.showModal({
					title: '温馨提示',
					content: '重要提醒：尊敬的用户，根据规定我们会在您学习过程中多次进行人脸识别认证，为了保护您的隐私请您在摄像设备视野内确保衣冠整齐。',
					confirmText: '同意并继续',
					cancelText: '取消',
					success: function (res) {
						if (res.confirm) {

						} else if (res.cancel) {
							uni.redirectTo({
								url: '/pages/application/onlinexxks/my-tasks'
							});
						}
					}
				});
			}
		},
		onBackPress() {
			if(this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.$refs.cuCustom.BackPage()
			return true
		},
		onUnload() {
			// 如果定时器在运行则关闭
			this.saveVideoRecord(0)
			if(this.timer) {
				clearInterval(this.timer)
				this.timer = null
				// console.info('页面卸载')
				// console.info(this.timer)
			}
		},
		methods: {
			startTimer(){
				this.seconds += 1
				// console.info('this.seconds:'+this.seconds)
				if (this.seconds == (Number(this.randomTiem)+10) * 60) {
					this.goFaceRecognition(this.currentCoursewareListIndex)
				}
			},
			tabSelect(e) {
				if(this.TabCur != e.currentTarget.dataset.id) {
					this.TabCur = e.currentTarget.dataset.id;
					this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
					this.currentCoursewareID = ''
					if (this.TabCur == 1) {
						this.movie.poster = ''
						this.movie.src = ''
						this.saveVideoRecord(0)
						if(this.timer) {
							clearInterval(this.timer)
							this.timer = null
						}
					} else {
						this.movie.poster = baseImgPath + this.pd.VIDEOLIST[0].COURSEWARECAPTURE
						this.movie.src = baseImgPath + this.pd.VIDEOLIST[0].COURSEWAREFILES
					}
				}
			},
			getData() {
				return new Promise((resolve, reject) => {
					var _this = this;
					uni.showLoading({
						title: '请稍候'
					})
					uni.request({
						url: basePath + '/app/stagestudentrelation/getMyTask',
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							STAGESTUDENTRELATION_ID: this.STAGESTUDENTRELATION_ID,
							USER_ID:loginUser.USER_ID
						},
						success: (res) => {
							if ("success" == res.data.result) {
								uni.hideLoading();
								_this.pd = res.data.pd;
								_this.pd.VIDEOLIST.forEach((ele) => {
									if (ele.VIDEOTIME == 0) {
										ele.VIDEOTIMEFORMAT = ''
										ele.VIDEOPROGRESS = ''
									} else {
										ele.VIDEOTIMEFORMAT = _this.formatVideoTime(ele.VIDEOTIME)
										_this.operatVideoList(ele)
									}
									// 如果数据不更新的话，增加下面代码
									// res.data.varList.splice(1, 0)
								})
								// 进入后自动播放第一个
								console.info(_this.pd.VIDEOLIST)
								if (_this.currentCoursewareID == '') {
									_this.movie.poster = baseImgPath + _this.pd.VIDEOLIST[0].COURSEWARECAPTURE
									_this.movie.src = baseImgPath + _this.pd.VIDEOLIST[0].COURSEWAREFILES
								}
							} else {
								uni.showToast({
									icon: 'none',
									title: res.data.message,
									duration: 2000
								});
							}
							resolve(true)
						}
					})
				})
			},
			operatVideoList(ele) {
				if (ele.PLAYCOUNT > 0) {		//已学习
					ele.VIDEOPROGRESS = 100
				} else {
					if (ele.VIDEOTIME == 0 || ele.RESOURCETIME == 0) {		//视频无时长信息或没有开始学习
						ele.VIDEOPROGRESS = 0
					} else {
						ele.VIDEOPROGRESS = (ele.RESOURCETIME / ele.VIDEOTIME * 100).toFixed(0)
						this.$forceUpdate()
					}
				}
			},
			formatVideoTime(VIDEOTIME) {
				var minute = Math.floor((VIDEOTIME / 60))
				var second = (VIDEOTIME - minute * 60).toFixed(0)
				return (minute < 10 ? ("0"+minute) : minute) + ":" + (second < 10 ? ("0"+second) : second)
			},
			validStr(str) {
				if (str != null && str != '' && typeof(str) != "undefined" && str != 0)
					return true
				return false
			},
			async studyVideo(index) {
				var item = this.pd.VIDEOLIST[index]
				if (this.currentCoursewareID != item.COURSEWAREID) { //播放视频不是同一个的时候
					this.currentCoursewareListIndex = index
					if (this.currentCoursewareID != '') { //保存上个视频的播放进度
						this.saveVideoRecord(0)
					}
					this.playTime = 0
					this.currentTime = 0
					this.isPaused = false
					this.currentCoursewareID = item.COURSEWAREID
					this.currentCurriculumID = item.CURRICULUMID
					if (this.validStr(item.COURSEWAREFILES)) {
						this.coursewareFiles = item.COURSEWAREFILES
						this.coursewareCapture = item.COURSEWARECAPTURE
						this.movie.poster = baseImgPath + item.COURSEWARECAPTURE
						this.movie.src = baseImgPath + item.COURSEWAREFILES
						var myvideo = uni.createVideoContext('coursewareVideo')
						await this.getVideoProgress()	//方法放在studyVideo加载后，此方法里的this.playTime获取不到值
						if (!this.pd.VIDEOLIST[index].ISCHECKFACE && this.pd.GJ_STATE == '1') {
							this.pd.VIDEOLIST[index].ISCHECKFACE = 1
							this.goFaceRecognition(index)
							return
						}
						// myvideo.seek(parseInt(this.playTime));
						// if(this.timer) {
						// 	clearInterval(this.timer)
						// 	this.timer = null
						// }
						// this.timer = setInterval(this.startTimer, 1000)
					} else {
						uni.showToast({
							icon: 'none',
							title: '课件视频资源已失效，请联系管理员',
							duration: 2000
						});
					}
				}

			},
			// 监听播放
			onPlayerPlay(player) {
				if (this.currentCoursewareID == '') {
					this.studyVideo(0)
				}
				this.isPaused = false
			},
			// 监听暂停
			onPlayerPause(player) {
				this.isPaused = true
			},
			// 当前播放位置发生变化时触发。
			onPlayerTimeupdate(player) {
				this.playTime = player.detail.currentTime
				if(this.playTime - this.currentTime >=15){
					this.currentTime = this.playTime
					this.saveVideoRecord(0)
				}
				if (this.pd.VIDEOLIST[this.currentCoursewareListIndex].VIDEOTIME != 0) {
					this.pd.VIDEOLIST[this.currentCoursewareListIndex].RESOURCETIME = this.playTime
					this.operatVideoList(this.pd.VIDEOLIST[this.currentCoursewareListIndex])
				}
			},
			onPlayerEnded(player) {
				this.isPaused = true
				// localStorage.setItem('currentTime' + this.currentCoursewareID, 0)
				this.playTime = 0
				this.currentTime = 0
				this.saveVideoRecord(1)
				if(this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
				if (this.pd.VIDEOLIST[this.currentCoursewareListIndex].VIDEOTIME != 0) {
					this.pd.VIDEOLIST[this.currentCoursewareListIndex].PLAYCOUNT = Number(this.pd.VIDEOLIST[this.currentCoursewareListIndex].PLAYCOUNT) + 1
					this.pd.VIDEOLIST[this.currentCoursewareListIndex].RESOURCETIME = this.playTime
					this.operatVideoList(this.pd.VIDEOLIST[this.currentCoursewareListIndex])
				}
			},
			saveVideoRecord(isEnd) {
				if (this.currentCoursewareID != '') {
					uni.request({
						url: basePath + 'app/coursestudyvideorecord/save',
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							CORPINFO_ID: corpinfoId,
							USER_ID: loginUser.USER_ID,
							USERNAME: loginUser.USERNAME,
							CURRICULUM_ID: this.currentCurriculumID,
							VIDEOCOURSEWARE_ID: this.currentCoursewareID,
							RESOURCETIME: this.playTime,
							STUDYTASK_ID: this.pd.STUDYTASK_ID,
							IS_END: isEnd,
							TYPE: 1
						},
						success: (res) => {
							this.videoRecord = res.data.pd
							if (isEnd == 1){
								this.pd.COMPLETE_COURSEWARE = res.data.pd.COMPLETE_COURSEWARE
								this.pd.VIDEOLIST[this.currentCoursewareListIndex].PLAYCOUNT = res.data.pd.PLAYCOUNT
							}
						}
					})
				}
			},
			getVideoProgress() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: basePath + 'app/coursestudyvideorecord/getVideoProgress',
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							USER_ID: loginUser.USER_ID,
							CURRICULUM_ID: this.currentCurriculumID,
							VIDEOCOURSEWARE_ID: this.currentCoursewareID
						},
						success: (res) => {
							if (res.data.pd != '') {
								this.videoRecord = res.data.pd
								this.playTime = this.videoRecord.RESOURCETIME
							}
							resolve(true)
						}
					})
				})
			},
			studyData(index) {
				var item  = this.pd.DATALIST[index]
				this.currentCoursewareListIndex = index
				this.currentCoursewareID = item.COURSEWAREID
				this.currentCurriculumID = item.CURRICULUMID
				if (this.validStr(item.COURSEWAREFILES)) {
					uni.showLoading({
						title: "加载中..."
					}); //加载中动画
					uni.downloadFile({
						url: baseImgPath + item.COURSEWAREFILES,
						success: (res) => {
							uni.hideLoading(); //结束加载中动画
							uni.openDocument({
								filePath: res.tempFilePath,
								success: function(res) {
									// console.log(res)
								}
							})
						}
					})
					uni.request({
						url: basePath + 'app/coursestudyvideorecord/save',
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							CORPINFO_ID: corpinfoId,
							USER_ID: loginUser.USER_ID,
							USERNAME: loginUser.USERNAME,
							CURRICULUM_ID: item.CURRICULUMID,
							VIDEOCOURSEWARE_ID: item.COURSEWAREID,
							RESOURCETIME: item.VIDEOTIME,
							STUDYTASK_ID: this.pd.STUDYTASK_ID,
							IS_END: 1,
							TYPE: 2
						},
						success: (res) => {
							this.pd.COMPLETE_COURSEWARE = res.data.pd.COMPLETE_COURSEWARE
							this.pd.DATALIST[this.currentCoursewareListIndex].PLAYCOUNT = res.data.pd.PLAYCOUNT
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: '课件文件资源已失效，请联系管理员',
						duration: 2000
					});
				}

			},
			goFaceRecognition(index) {
				uni.redirectTo({
					url: '/pages/application/onlinexxks/face/index?CURRICULUM_ID=' + this.currentCurriculumID
							+ '&STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
							+ '&CURRENTCOURSEWAREID=' + this.currentCoursewareID + '&COURSEWAREFILES=' + this.coursewareFiles
							+ '&COURSEWARECAPTURE=' + this.coursewareCapture + '&PLAYTIME=' + this.playTime
							+ '&COURSEWAREINDEX=' + index

				})
			},
			//习题练习
			goStudyQuestion(item) {
				uni.request({
					url: basePath + '/app/mycurriculum/countForStudyByCoursewareId',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						CURRICULUMID: item.CURRICULUMID,
						COURSEWAREID: item.COURSEWAREID,
						COURSEWARETYPE: item.COURSEWARETYPE
					},
					success: (res) => {
						uni.hideLoading(); //结束加载中动画
						if ("success" == res.data.result) {
							if (res.data.pd.COUNT > 0) {
								this.goStudyDetail(item)
							} else {
								uni.showToast({
									icon: 'none',
									title: '课件还没有添加课件习题',
									duration: 2000
								})
							}
						}
					}
				})

			},
			goStudyDetail(item) {
				/*
				if (item.STUDYSTATE == '1') {
					uni.request({
						url: basePath + '/app/coursestudentrelation/updateStudentState',
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							USERNAME: loginUser.USERNAME,
							TYPE: '1',
							STUDYSTATE: '2',
							STAGESTUDENTRELATION_ID: this.STAGESTUDENTRELATION_ID,
						},
						success: (res) => {
							if ("success" == res.data.result) {
								// console.log(_this.pd)
							} else {
								uni.showToast({
									icon: 'none',
									title: res.data.message,
									duration: 2000
								});
							}
						}
					});
				}*/
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-study-detail?STUDYTASK_ID=' + this.pd.STUDYTASK_ID + '&COURSEWAREID=' + item.COURSEWAREID + '&COURSEWARETYPE=' +
						item.COURSEWARETYPE + '&CURRICULUM_ID=' + item.CURRICULUMID + '&STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
				})
			},
			goExam() {
				if (this.pd.COURSEWARE_COUNT <= this.pd.COMPLETE_COURSEWARE) {
					// uni.request({
					// 	url: basePath + '/app/coursepapers/checkCurriculumExam',
					// 	method: 'POST',
					// 	dataType: 'json',
					// 	header: {
					// 		'Content-type': 'application/x-www-form-urlencoded'
					// 	},
					// 	data: {
					// 		CURRICULUMID: this.currentCurriculumID
					// 	},
					// 	success: (res) => {
					// 		uni.hideLoading(); //结束加载中动画
					// 		if ("success" == res.data.result) {
					// 			if (res.data.pd == null) {
					// 				uni.showToast({
					// 					icon: 'none',
					// 					title: '课程还没有创建试卷，请联系管理员',
					// 					duration: 2000
					// 				})
					// 			} else if (res.data.pd.QUESTIONLIST.length == 0) {
					// 				uni.showToast({
					// 					icon: 'none',
					// 					title: '试卷考题缺失，请联系管理员',
					// 					duration: 2000
					// 				})
					// 			} else {
									uni.showModal({
										title: '',
										content: '确定要进行考试吗？',
										cancelColor: '#000000',
										cancelText: '取消',
										confirmText: '确定',
										success: res => {
											if (res.confirm) {
												// uni.redirectTo({
												// 	url: '/pages/application/onlinexxks/my-exam-curriculum?CURRICULUM_ID=' + this.currentCurriculumID +
												// 		'&STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
												// })
												uni.redirectTo({
													url: '/pages/application/onlinexxks/my-exam-stage?STUDYTASK_ID=' + this.pd.STUDYTASK_ID + '&STAGEEXAMPAPER_ID=' + this.pd.STAGEEXAMPAPER_ID +
															'&STAGESTUDENTRELATION_ID=' + this.pd.STAGESTUDENTRELATION_ID
												});
											}
										}
									})
					// 			}
					// 		}
					// 	}
					// })
				} else {
					uni.showToast({
						icon: 'none',
						title: '请完成所有课件学习，再进行考试。',
						duration: 2000
					})
				}
			},
			BackPage() {
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-curriculum',
				})
			}
		}
	}
</script>

<style>
</style>
