<template>
	<view class="wrap">
		<!-- <view class="header">
			<uni-icons class="back" type="back" size="20" color="#fff" @click="back"></uni-icons>
			<text>课程详情</text>
		</view> -->
			<!-- <web-view class="wv" src="https://view.officeapps.live.com/op/view.aspx?src=https://huoran.oss-cn-shenzhen.aliyuncs.com/1732588133977.xlsx"></web-view> -->
		<view class="file-wrap">
			<image v-if="!curRow.viewUrl && coverUrl" class="pic" :src="coverUrl" mode="widthFix"></image>
			<template v-else>
				<image v-if="curRow.isPic" class="pic" :src="curRow.viewUrl" mode="widthFix" @click="hidePlayList"></image>
				<video v-else-if="curRow.isVideo" class="video" :key="curRow.viewUrl" width="100%" height="100%" autoplay controls :src="curRow.viewUrl" type="video/mp4" @click="hidePlayList" @fullscreenchange="fullScreenChange"></video>
				<!-- pdf、word、excel、ppt都用webview展示 -->
				<view v-else-if="curRow.isDoc" class="webview-wrap">
					<web-view class="webview" :webview-styles="webviewStyles" :fullscreen="false" :src="curRow.viewUrl" @click="hidePlayList"></web-view>
					<cover-view :class="['webview-mask', {ppt: curRow.isPpt}]" @click="closePreview">
						<cover-image class="icon" src="https://eduvessel.com/images/occupationlab/close-gray.png" alt="" mode="widthFix" />
					</cover-view>
				</view>
			</template>
			
			<cover-view v-show="!playListVisible && curRow.viewUrl && (!curRow.isVideo || videoFullScreen)" class="select-epi">
				<cover-image class="icon" src="https://eduvessel.com/images/occupationlab/list.png" mode="widthFix" @click="showPlayList" />
			</cover-view>
			
			<cover-view v-show="chapterList.length && playListVisible" :class="['chapters-full', {'full-screen': videoFullScreen}]">
				<cover-view class="chapters-scroll">
					<cover-view v-for="(item, i) in chapterList" :key="i" class="chapter">
						<cover-view class="chapterName">{{ item.name }}</cover-view>
						<cover-view class="section" v-if="item.subsectionList.length">
							<cover-view v-for="(section, j) in item.subsectionList" :key="j"class="sectionName" :class="{ active: curRow.id === section.id }" @click="secClick(section, item)">
							  <cover-image v-if="section.fileType === 'pptx'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/ppt.png" alt="" mode="widthFix" />
							  <cover-image v-else-if="section.fileType === 'mp4'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/video.png" alt="" mode="widthFix" />
							  <cover-image v-else-if="section.fileType === 'doc' || section.fileType === 'docx'" class="ext"
								src="https://eduvessel.com/images/occupationlab/exts/word.png" alt="" mode="widthFix" />
							  <cover-image v-else-if="section.fileType === 'xlsx' || section.fileType === 'xls'" class="ext"
								src="https://eduvessel.com/images/occupationlab/exts/excel.png" alt="" />
							  <cover-image v-else-if="section.fileType === 'txt'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/txt.png" alt="" mode="widthFix" />
							  <cover-image v-else-if="section.fileType === 'pdf'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/pdf.png" alt="" mode="widthFix" />
							  <cover-image v-else class="ext" src="https://eduvessel.com/images/occupationlab/exts/pic.png" alt="" mode="widthFix" />
							  <cover-view class="text">{{ section.name }}</cover-view>
							</cover-view>
						</cover-view>
					</cover-view>
				</cover-view>
				<cover-view class="close-wrap" @click="hidePlayList">
					<cover-image class="close" src="https://eduvessel.com/images/occupationlab/close.png" mode="widthFix" />
				</cover-view>
			</cover-view>
		</view>
		
		<ul class="tabs">
			<li v-for="(item, i) in tabs" :key="i" :class="{active: curTab === item.id}" @click="tabChange(item.id)">{{ item.name }}</li>
		</ul>
			
		<view class="detail">
			<!-- 课程介绍 -->
			<view v-show="!curTab" class="des">
				<mp-html class="des-html" :tag-style="mpStyle" :content="briefIntroduction"/>
			</view>
			
			<!-- 课程目录 -->
			<view v-show="curTab === 1">
				<view v-if="chapterList.length" class="chapters">
					<view class="chapter" v-for="(item, i) in chapterList" :key="i">
					    <view class="chapterName" @click="toggleChapter(item)">
							{{ item.name }}
							<uni-icons :class="['arrow', {shrink: item.shrink}]" type="bottom" size="24" color="#909090"></uni-icons>
						</view>
					    <view :class="['section', {shrink: item.shrink}]" v-if="item.subsectionList.length">
							<view v-for="(section, j) in item.subsectionList" :key="j"class="sectionName" :class="{ active: curRow.id === section.id }" @click="secClick(section, item)">
							  <image v-if="section.fileType === 'pptx'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/ppt.png" alt="">
							  <image v-else-if="section.fileType === 'mp4'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/video.png" alt="">
							  <image v-else-if="section.fileType === 'doc' || section.fileType === 'docx'" class="ext"
								src="https://eduvessel.com/images/occupationlab/exts/word.png" alt="">
							  <image v-else-if="section.fileType === 'xlsx' || section.fileType === 'xls'" class="ext"
								src="https://eduvessel.com/images/occupationlab/exts/excel.png" alt="">
							  <image v-else-if="section.fileType === 'txt'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/txt.png" alt="">
							  <image v-else-if="section.fileType === 'pdf'" class="ext" src="https://eduvessel.com/images/occupationlab/exts/pdf.png" alt="">
							  <image v-else class="ext" src="https://eduvessel.com/images/occupationlab/exts/pic.png" alt="">
							  {{ section.name }}
							</view>
					    </view>
					</view>
				</view>
			</view>
			
			<!-- 练习成绩 -->
			<view v-show="curTab === 2">
				<view v-if="practices.length" class="list">
					<view v-for="(item, i) in practices" :key="i" class="item" @click="toPrac(item)">
						<view class="c-name">{{ item.projectName }}</view>
						<view class="line">最高分：{{ item.hightScore }}&emsp;&emsp;练习次数：{{ item.practiceNum }}</view>
						<view class="line">累计练习时长（小时）：{{ item.duration }}</view>
						<view class="line">最近练习时间：{{ item.lastTime }}</view>
						<view class="btn">练习情况</view>
					</view>
				</view>
				<empty v-else />
			</view>
			
			
			<!-- 考核成绩 -->
			<view v-show="curTab === 3">
				<view v-if="ass.length" class="list">
					<view v-for="(item, i) in ass" :key="i" class="item" @click="toReport(item)">
						<view class="c-name">{{ item.experimentalName }}</view>
						<view class="line">得分：{{ item.score }}&emsp;&emsp;耗时：{{ item.timeSum }}min</view>
						<view class="line">考核开始时间：{{ item.startTime }}</view>
						<view class="line">考核结束时间：{{ item.submitTime }}</view>
						<view class="btn">成绩报告</view>
					</view>
				</view>
				<empty v-else />
			</view>
		</view>
	</view>
</template>

<script>
	import { queryChaptersAndSubsections, detailsOfGoods, queryPracticeByStudent, queryAssessmentByStudent, getPlayAuth, playRecordSave, recordRecentUsage, getALinkToTheExperimentReport, getExamPaperReportUrl } from '@/apis/modules/course.js'
	export default {
		data() {
			return {
				cid: '',
				mallId: '',
				startTime: Date.now(), // 页面进来的时间
				curTab: 1,
				tabs: [
					{
						name: '课程介绍',
						id: 0
					},
					{
						name: '课程目录',
						id: 1
					},
					{
						name: '练习成绩',
						id: 2
					},
					{
						name: '考核成绩',
						id: 3
					}
				],
				searchTimer: null,
				keyword: '',
				chapterList: [],
				coverUrl: '',
				briefIntroduction: '',
				
				practices: [],
				reachBottom: 0, // 是否是上拉加载。0->否,1->是,-1->加载完所有数据
				status: 'more', // 上拉加载状态 more|loading|noMore
				page: 1,
				pageSize: 10,
				
				ass: [],
				reachBottomAss: 0, // 是否是上拉加载。0->否,1->是,-1->加载完所有数据
				statusAss: 'more', // 上拉加载状态 more|loading|noMore
				pageAss: 1,
				pageSizeAss: 10,
				
				dotsStyles: {
					backgroundColor: 'rgba(83, 200, 249,0.3)',
					border: '1px rgba(83, 200, 249,0.3) solid',
					color: '#fff',
					selectedBackgroundColor: 'rgba(83, 200, 249,0.9)',
					selectedBorder: '1px rgba(83, 200, 249,0.9) solid'
				},
				mpStyle: {
					p: 'font-size: 25rpx !important;font-family: Microsoft Yahei !important;font-weight: 400 !important;color: #333 !important;',
					span: 'font-size: 25rpx !important;font-family: Microsoft Yahei !important;font-weight: 400 !important;color: #333 !important;'
				},
				
				playAuth: '',
				player: null,
				curRow: {},
				playListVisible: false,
				videoFullScreen: false,
				webviewStyles: {
					progress: {
						color: '#FF3333'
					},
					width: '100%',
					height: '400'
				}
			}
		},
		watch: {
			keyword () {
				clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					this.getChapter()
				}, 500)
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.curTab === 2 && this.initPrac()
			this.curTab === 3 && this.initAss()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1500)
		},
		// 上拉加载
		onReachBottom() {
			if (this.curTab === 2) {
				// 练习
				if (this.reachBottom >= 0) {
					this.reachBottom = 1
					this.status = 'loading'
					this.getPractices()
				}
			} else if (this.curTab === 3) {
				// 练习
				if (this.reachBottomAss >= 0) {
					this.reachBottomAss = 1
					this.statusAss = 'loading'
					this.getAss()
				}
			}
		},
	    onUnload () {
			// 记录播放时长
			if (this.cid) {
				playRecordSave({
					courseId: this.cid,
					courseType: 0,
					playTime: Math.ceil((Date.now() - this.startTime) / 1000 / 60)
				})
			}
	    },
		onShow() {
			const pages = getCurrentPages()
			console.log(444,pages)
			const { options } = pages[pages.length - 1]
			this.cid = options.cid
			this.mallId = options.mallId
			this.getInfo()
			this.getChapter()
			this.addRecord()
		},
		methods: {
			// 获取章节小节
			async getChapter () {
			    if (this.cid) {
					const res = await queryChaptersAndSubsections(this.cid)
					this.chapterList = res.chapterList
			    }
			},
			// 获取介绍
			async getInfo () {
			    if (this.mallId) {
					const res = await detailsOfGoods({
						mallId: this.mallId
					})
					const e = res.orderDetails.mall
					this.coverUrl = e.coverDrawing
					this.briefIntroduction = e.detailedIntroduction
			    }
			},
			// 记录最近使用
			async addRecord () {
			    await recordRecentUsage(this.mallId)
			},
			// 练习成绩
			async getPractices () {
			    const { page } = await queryPracticeByStudent({
					pageNum: this.page,
					pageSize: this.pageSize,
					mallId: this.mallId,
					curriculumId: this.cid
				})
				this.practices = this.reachBottom > 0 ? [...this.practices, ...page.records] : page.records
				this.page++ // 每次获取了数据后page+1
				const noMore = this.practices.length === page.total // 是否加载完所有数据
				this.status = noMore ? 'noMore' : 'more' // 加载完了则设置为noMore
				this.reachBottom = noMore ? -1 : 0 // 加载完了则设置为-1
			},
			// 考核成绩
			async getAss () {
			    const { page } = await queryAssessmentByStudent({
					pageNum: this.pageAss,
					pageSize: this.pageSizeAss,
					mallId: this.mallId,
					curriculumId: this.cid
				})
				this.ass = this.reachBottom > 0 ? [...this.ass, ...page.records] : page.records
				this.pageAss++ // 每次获取了数据后page+1
				const noMore = this.ass.length === page.total // 是否加载完所有数据
				this.statusAss = noMore ? 'noMore' : 'more' // 加载完了则设置为noMore
				this.reachBottomAss = noMore ? -1 : 0 // 加载完了则设置为-1
			},
			initPrac() {
				this.page = 1
				this.reachBottom = 0
				this.getPractices()
			},
			initAss() {
				this.pageAss = 1
				this.reachBottomAss = 0
				this.getAss()
			},
			// tab切换
			tabChange(id) {
				this.curTab = id
				// !id && !this.briefIntroduction && this.getInfo()
				id === 2 && !this.practices.length && this.initPrac()
				id === 3 && !this.ass.length && this.initAss()
			},
			// 章节收缩
			toggleChapter(item) {
				this.$set(item, 'shrink', !item.shrink)
			},
			// 练习跳转
			toPrac(row) {
				this.$util.to(`../practiceDetail/practiceDetail?cid=${this.cid}&projectId=${row.projectId || ''}&paperId=${row.paperId || ''}`)
			},
			// 考核查看实验报告
			async toReport(row) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				
				let res
				if (row.paperId) {
					// 理论
					res = await getExamPaperReportUrl({
						reportId: row.reportId
					})
				} else {
					// 导出
					res = await getALinkToTheExperimentReport(row.reportId)
				}
				// 下载文件资源到本地
				uni.downloadFile({
					url: res.url,
					success: function(res) {
						console.log(11, res)
						// 新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
						uni.openDocument({
							filePath: res.tempFilePath,
							fileType: 'docx', // 文件类型，指定文件类型打开文件，有效值 doc, xls, ppt, pdf, docx, xlsx, pptx 
							showMenu: true, // 允许出现分享功能
							success: res => {
								uni.hideLoading()
							},
							fail: openError => {
								uni.hideLoading()
							}
						})
					},
					fail: function(err) {
						uni.hideLoading()
					}
				})
			},
			
			// 判断文件是图片/视频/pdf等
			handleFileType(row) {
				const type = row.fileType
				if (type === 'pptx' || type === 'ppt') {
					row.isPpt = true
					row.isDoc = true
					row.viewUrl = 'https://view.officeapps.live.com/op/view.aspx?src=' + row.fileUrl
				} else {
					if (this.$util.exts.video.includes(type)) {
						row.isVideo = true
					} else if (this.$util.exts.img.includes(type)) {
						row.isPic = true
					} else if (this.$util.exts.doc.includes(type)) {
						row.isDoc = true
					}
					row.viewUrl = row.fileUrl
				}
				this.curRow = row
			const pages = getCurrentPages()
			console.log('preview：',pages)
			},
			// 预览文件
			secClick(row) {
				this.playListVisible = false
				this.videoFullScreen = false
				this.handleFileType(row)
			},
			// 视频全屏回调
			fullScreenChange(e) {
				console.log(444, e)
				const { fullScreen } = e.detail
				this.playListVisible = false
				this.videoFullScreen = fullScreen
			},
			// 选集
			showPlayList() {
				this.playListVisible = !this.playListVisible
			},
			hidePlayList() {
				console.log('close clicked')
				this.playListVisible = false
			},
			// 关闭预览状态
			closePreview() {
				this.curRow = {}
			},
			// 返回
			back() {
				if (this.curRow.viewUrl) {
					this.curRow = {}
				} else {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			},
		}
	}
</script>

<style scoped lang="scss">
.wrap {
	min-height: 100%;
	background-color: #fff;
	.header {
		position: relative;
		width: 100%;
		height: 60rpx;
		padding: calc(var(--status-bar-height) + 60rpx) 0 10rpx;
		font-size: 28rpx;
		text-align: center;
		color: #fff;
		background-color: #007EFF;
		// box-sizing: border-box;
		.back {
			position: absolute;
			top: calc(var(--status-bar-height) + 60rpx);
			left: 10rpx;
		}
	}
}
.file-wrap {
	position: relative;
	.pic, .video {
		width: 100%;
		height: 400rpx;
	}
	.webview {
		display: block;
	}
	.pic {
		display: block;
		object-fit: cover;
	}
	
	.select-epi {
	    z-index: 1000;
	    position: fixed;
	    top: 40px;
	    right: -5px;
		padding: 5px 12px;
		background-color: rgba(0, 0, 0, .6);
		border-radius: 0;
		border-top-left-radius: 10px;
		border-bottom-left-radius: 10px;
		// border-top-right-radius: 0;
		// border-bottom-right-radius: 0;
		.icon {
			width: 24px;
		}
	}
	.webview-wrap {
		height: 90vh;
		overflow: hidden;
	}
	.webview-mask {
		z-index: 9;
		position: fixed;
		top: 20rpx;
		left: 0;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: 100%;
		height: 50rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		&.ppt {
			top: 0;
			background-color: #fff;
		}
		.icon {
			width: 44rpx;
			height: 44rpx;
		}
	}
}
.webview {
	position: absolute;
	top: -80rpx;
}
.chapters-full {
	z-index: 100;
	position: fixed;
	top: 0;
	right: 0;
	width: 100vw;
	height: 100vh;
	padding: 15px;
	margin-bottom: 20px;
	color: #fff;
	background-color: rgba(0, 0, 0, .7);
	box-sizing: border-box;
	.close-wrap {
		z-index: 100;
		position: absolute;
		top: 10px;
		right: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 80rpx;
		height: 80rpx;
	}
	.close {
		width: 22px;
		height: 22px;
	}
	.chapters-scroll {
		height: 95vh;
		overflow: scroll;
	}
	.chapter {
		margin-bottom: 10px;
		.chapterName {
			display: flex;
			justify-content: space-between;
			font-size: 14px;
		}
		.section {
			margin: 5px 0;
		}
		.sectionName {
			display: flex;
			align-items: center;
			padding: 10rpx 6px;
			margin: 6px 0;
			font-size: 12px;

			&.active {
			    color: #007EFF;
			}
		}
		.ext {
			width: 14px;
			margin-right: 12px;
		}
		.text {
			max-width: 75vw;
			text-overflow: ellipsis;
		}
	}
	&.full-screen {
		width: 50vw;
		.close {
			top: 30px;
			right: 30px;
		}
	}
}
.tabs {
	z-index: 1;
	position: sticky;
	top: 0;
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	background-color: #fff;
	li {
		position: relative;
		text-align: center;
		font-size: 28rpx;
		color: #333;
		white-space: nowrap;
	}
	.active {
		color: #007EFF;
		&:after {
			content: '';
			position: absolute;
			bottom: -12rpx;
			left: 50%;
			width: 116%;
			height: 4rpx;
			margin: 10rpx auto 0;
			background-color: #007EFF;
			transform: translateX(-50%);
		}
	}
}
.detail {
	padding: 0 30rpx 30rpx;
	.chapters {
		margin-top: 20rpx;
	}
	.chapter {
		margin-bottom: 40rpx;
		.chapterName {
			display: flex;
			justify-content: space-between;
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
		}
		.arrow {
			font-size: 28rpx;
		}
		.section {
			height: auto;
			transition: .5s;
			overflow: hidden;
			&.shrink {
				// display: none;
				height: 0;
				// transform: scaleY(0);
			}
		}
		.sectionName {
			display: flex;
			align-items: center;
			margin: 40rpx 0;
			font-size: 24rpx;
			color: #333;

			&.active {
			    color: #007EFF;
			}
		}
		.ext {
			width: 36rpx;
			height: 36rpx;
			margin-right: 20rpx;
		}
	}
	.list {
		.item {
			position: relative;
			padding: 20rpx 0;
			&:not(:last-child) {
				border-bottom: 1px solid #e6e6e6;
			}
		}
		.c-name {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
		.line {
			margin-top: 14rpx;
			font-size: 26rpx;
			color: #828282;
		}
		.btn {
			position: absolute;
			bottom: 20rpx;
			right: 0;
			padding: 10rpx 30rpx;
			font-size: 28rpx;
			color: #fff;
			background-color: #007EFF;
			border-radius: 36rpx;
		}
	}
}
</style>
