<template>
	<view class="kecheng-study-page">
		<!-- <view class="icon-title-bjcolor-navBar-box">
			<view @click="goUpPage" class="nav-bar-icon"></view>
			<text class="nav-bar-title">{{name}}</text>
		</view> -->
		<!-- 播放器 -->
		<videoPlayVue v-if="showVideo" ref="videoRef" class="phone-video-box" @play-end="onPlayEnd" @play-play="onPlay"
			@play-pause="onPause" @play-timeupdate="onTimeupdate"></videoPlayVue>
			<!-- 视频背景图 -->
		<view v-else class="phone-video-box master-image">
			<view class="bifaibg-icon" @click="handlePlayFirst"></view>
		</view>
		<!-- 中间区域 -->
		<view class="kc-name-box">
			<icon @click="goUpPage"></icon>
			<view>{{zyName}} {{zyLevelName}}</view>
		</view>
		<view class="kc-info-box">
			<view>时长：{{period}}</view>
			<view>{{userCount}}人学习</view>
		</view>
		<!-- 大纲 -->
		<view class="phone-tab-box">
			<uni-segmented-control :current="current" :values="items" style-type="text" :active-color="activeColor"
				@clickItem="onClickItem" />
		</view>
		<view class="kecheng-content-box">
			<!-- 目录 -->
			<kechengMuluVue v-if="current === 0" :chapterArr="list" @play="handlePlay" :isHasProgress="true"
				:activeKjId="curPlayData&&curPlayData.kjId"></kechengMuluVue>
			<!-- 介绍 -->
			<rich-text :nodes="intro || '暂无内容'" v-if="current === 1 && intro" class="kecheng-jieshao-box"></rich-text>
		</view>
	</view>
</template>

<script>
	import * as kechengApi from "@/api/kecheng.js";
	import videoPlayVue from "@/components/videoPlay/videoPlay.vue";
	import kechengMuluVue from "@/components/kecheng-mulu/kecheng-mulu.vue";
	import {
		useUserCache
	} from "@/utils/userCache.js"
	import {
		formatSecondsToCnhms
	} from "@/utils/common.js"
	import {
		useKechengTools
	} from "./useKechengCache.js"

	const {
		getCurKjIndex,
		saveKechengData,
		getKechengDataFromHistory,
		saveKechengSectionPage,
		getKechengSectionPageFromHistory,
		mergeProgress,
		initCourseProgressAll,
		saveCourseProgress,
		updateSectionProgress,
	} = useKechengTools();

	export default {
		components: {
			videoPlayVue,
			kechengMuluVue
		},
		data() {
			return {
				showVideo: false,
				items: ['目录', '介绍'],
				colors: ['#007aff', '#4cd964', '#dd524d'],
				activeColor: '#3fd2a1',
				current: 0, // 激活的选项卡
				operId: '', // 课程
				name: '',
				period: 0, // 时长
				userCount: 0, // 学习人数
				list: [],
				intro: '',
				curPlayData: null,
				timer1: null,
				kcId: null,
				from: '',
				zyName: '',
				zyLevelName: '',
				userKaozhengId: null,
			}
		},
		onLoad(options) {
			this.kcId = options.kcId;
			this.from = options.from;
			this.userKaozhengId = options.userKaozhengId;
			this.init();
		},
		methods: {
			handlePlayFirst() {
				let sectionPage = getKechengSectionPageFromHistory(this.operId)
				if (sectionPage) {
					const {
						zhangIndex,
						jieIndex
					} = getCurKjIndex(sectionPage.kjId,this.operId)
					sectionPage.iChapter = zhangIndex;
					sectionPage.iSection = jieIndex;
					sectionPage.kjId = sectionPage.kjId;
					sectionPage.operId = this.operId;
					
					// 设置默认展开项
					this.list[zhangIndex].open = true;
					this.list[zhangIndex].jieList[jieIndex].open = true;
					
					const kejian = this.list[0].jieList && this.list[zhangIndex].jieList[jieIndex].kejianList.find(item => item.kjId ==sectionPage.kjId )
					this.handlePlay(kejian)
				} else {
					if (this.list && this.list[0].jieList && this.list[0].jieList[0].kejianList) {
						// 设置默认展开项
						this.list[0].open = true;
						this.list[0].jieList[0].open = true;
						// 设置播放可见
						const kejian = this.list[0].jieList[0].kejianList[0];
						this.handlePlay(kejian)
						// 更新缓存
						sectionPage = {
							kjId: kejian.kjId,
							iChapter: 0,
							iSection: 0,
							operId: this.operId
						}
					}
				}
						
				saveKechengSectionPage(this.operId, sectionPage)
			},
			onPause() {
				clearInterval(this.timer1);
				this.timer1 = null;
			},
			onPlay() {
				clearInterval(this.timer1);
				this.timer1 = null;
				this.timer = setInterval(() => {
					updateSectionProgress(this.operId);
				}, 1000 * 1 * 60) // 自动保存进度 1分钟已保存
			
			},
			sectionPlayerProgress(progress) {
				let sectionPage = getKechengSectionPageFromHistory(this.operId);
				let maxProcess = this.list[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList.find(it1=>it1.kjId == sectionPage.kjId).maxProcess;
				// 更新缓存进度
				this.list[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList.find(it1=>it1.kjId == sectionPage.kjId).curProcess = progress;
				if (progress < 100) {
					// 播放进度小于100
					if (progress < maxProcess) {
						this.list[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList.find(it1=>it1.kjId == sectionPage.kjId).maxProcess = maxProcess
					} else {
						this.list[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList.find(it1=>it1.kjId == sectionPage.kjId).maxProcess = progress
					}
				} else {
					// 播放进度大于100
					this.list[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList.find(it1=>it1.kjId == sectionPage.kjId).maxProcess = 100
				}
			},
			onTimeupdate(time) {
				const progress = parseInt(time / this.curPlayData.duration * 100);
				this.curPlayData.curProgress = parseInt(progress >= 100 ? '99' : progress);
				// 保存进度
				saveCourseProgress(time, this.curPlayData.duration, this.operId)
				// 更新进度
				this.sectionPlayerProgress(progress)
			},
			onPlayEnd() {
				clearInterval(this.timer1);
				this.timer1 = null;
				saveCourseProgress(this.curPlayData.duration, this.curPlayData.duration, this.operId, 'end');
				updateSectionProgress(this.operId, 'end', 'video', () => {
					this.curPlayData.maxProcess = 99;
					this.curPlayData.curProcess = 99;
				});
				console.log('end')
			},
			goUpPage() {
				const pages = getCurrentPages();
				if (pages.length>1) {
					uni.navigateBack()
				} else {
					/* if (this.from == 'kechengList') {
						uni.redirectTo({
							url: '/pages/client/Kecheng/list'
						})
					} else if (this.from == 'shouye') {
						uni.redirectTo({
							url: '/pages/client/ShouYe/shouye'
						})
					} else {
						uni.redirectTo({
							url: '/pages/client/ShouYe/shouye'
						})
					} */
					 history.back();
				}
				
			},
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			formatData(data) {
				data.forEach(zhang => {
					zhang.open = false;
					zhang.jieList.forEach(jie => {
						jie.open = false;
					})
				})
				return data;
			},
			handlePlay(data) {
				this.showVideo = true;
				if (this.curPlayData && this.curPlayData.url == data.url) {
					return;
				}
				this.curPlayData = data;
				const {
					zhangIndex,
					jieIndex
				} = getCurKjIndex(data.kjId,this.operId)
				const sectionPage = {};
				sectionPage.iChapter = zhangIndex;
				sectionPage.iSection = jieIndex;
				sectionPage.kjId = data.kjId;
				sectionPage.operId = this.operId;
				saveKechengSectionPage(this.operId, sectionPage)
				kechengApi.getVideoAuth({
					videoId: data.url
				}).then(res => {
					const progress = data.curProcess || 0;
					this.$refs.videoRef.init({
						videoId: data.url,
						playAuth: res.data,
						seekTime: data.duration * progress / 100,
						isPlay: false
					})

				})
			},
			initFirstVideo() {
				let sectionPage = getKechengSectionPageFromHistory(this.operId)
				if (sectionPage) {
					const {
						zhangIndex,
						jieIndex
					} = getCurKjIndex(sectionPage.kjId,this.operId)
					sectionPage.iChapter = zhangIndex;
					sectionPage.iSection = jieIndex;
					sectionPage.kjId = sectionPage.kjId;
					sectionPage.operId = this.operId;
					
					// 设置默认展开项
					this.list[zhangIndex].open = true;
					this.list[zhangIndex].jieList[jieIndex].open = true;
					
					const kejian = this.list[0].jieList && this.list[zhangIndex].jieList[jieIndex].kejianList.find(item => item.kjId ==sectionPage.kjId )
					// this.handlePlay(kejian)
				} else {
					if (this.list && this.list[0].jieList && this.list[0].jieList[0].kejianList) {
						// 设置默认展开项
						this.list[0].open = true;
						this.list[0].jieList[0].open = true;
						// 设置播放可见
						const kejian = this.list[0].jieList[0].kejianList[0];
						// this.handlePlay(kejian)
						// 更新缓存
						sectionPage = {
							kjId: kejian.kjId,
							iChapter: 0,
							iSection: 0,
							operId: this.operId
						}
					}
				}
		
				saveKechengSectionPage(this.operId, sectionPage)
			},

			init() {
				kechengApi.getClientKechengStart({
					kcId: this.kcId,
					userKaozhengId:this.userKaozhengId
				}).then(res => {
					const {
						userCount,
						period,
						name,
						kejianUserVo,
						intro,
						operId,
						zyName,
						zyLevelName,
					} = res.data;
					this.userCount = userCount;
					this.period = formatSecondsToCnhms(period,true);
					this.name = name;
					this.zyName = zyName;
					this.zyLevelName = zyLevelName;
					this.formatData(kejianUserVo.zhangList)
					this.list = kejianUserVo.zhangList;
					this.intro = intro;
					this.operId = operId;

					// 获取课程缓存 && 课件缓存(课件缓存点击后产生)
					let historyArrKecheng = getKechengDataFromHistory(this.operId)
					let sectionPageHistory = getKechengSectionPageFromHistory(this.operId)
					// 判断是否有前台缓存
					if (historyArrKecheng && sectionPageHistory) {
						// 有缓存---- 把start接口中，返回数据进度100%，更新到前台缓存
						const arrKecheng = mergeProgress(kejianUserVo && kejianUserVo.zhangList,
							historyArrKecheng);
						// 后台数据 同步前台缓存
						saveKechengData(this.operId, arrKecheng)
					} else {
						// 无缓存----把start接口中，返回的所有数据，更新到前台缓存
						saveKechengData(this.operId, kejianUserVo && kejianUserVo.zhangList)
					}
					// 初始化页面 常规数据
					initCourseProgressAll(this.operId)

					console.log('初始化播放首次')
					// 设置播放视频
					this.initFirstVideo();
				}).catch(err => {
					this.goUpPage();
				})
			}
		}
	}
</script>


<style>

</style>