<template>
	<view class="main-content">
		<headers :showBack="false" :themeType="true">
			<view class="top-diy">
				<view class="headerBack" @click="returnBack">
					<u-icon name="arrow-left" color="#ffffff" size="40"></u-icon>
				</view>
				<text>学习详情</text>
			</view>
		</headers>
		<view class="video rules" v-show="videoList.length || dataList.length">
			<view class="rules-box" v-for="(item,index) in dataList" :key="item.url">
				<image :src="item.url" v-if="fileTypeCondition(item.url)"></image>
				<image src="../../../../static/images.png" v-else></image>
				<view>
					<view class="rules-text1">
						<text>{{item.name}}</text>
					</view>
					<view class="rules-text2" @click="downLoadFile(item,2,index)">
						<text>下载预览</text>
					</view>
				</view>
			</view>
			<video v-for="(item,index) in videoList" :key="index" id="myVideo" class="disable-progress"
				style="width: 100%;height: 390rpx;" :muted="false" :show-mute-btn="true" :src="item.url"
				:enable-progress-gesture="false" :controls="item.controlsBool" @play="videoStart(index)"
				@ended="videoEnd(index)">
			</video>
			<!-- <swiper circular :indicator-dots="false" indicator-color="rgba(99, 99, 99, 1)"
				style="width: 100%;height: 390rpx;">
				<swiper-item v-for="(item,index) in videoList" :key="index" style="width: 100%;height: 390rpx;">
					<video id="myVideo" class="disable-progress" style="width: 100%;height: 390rpx;"
						:muted="true" :show-mute-btn="true" :src="item.url" :enable-progress-gesture="false"
						:controls="item.controlsBool" @play="videoStart(index)" @ended="videoEnd(index)">
					</video>
				</swiper-item>
			</swiper> -->
		</view>
		<view class="studybox" v-if="videoList.length || dataList.length">
			<view class="studybox-line"></view>
			<view class="studybox-text1">
				<!-- <text>安全教育——视频</text> -->
				<text>{{responseData.courseName}}</text>
			</view>
		</view>
		<!-- || pageData.examCount<=0 -->
		<button type="primary" :disabled="isStartExam" class="btn" @click="goHiidden"
			v-if="pageData.examPaperId">开始考试</button>
		<levitatedsphere :x="100" :y="80"></levitatedsphere>
	</view>
</template>

<script>
	import levitatedsphere from "@/components/levitatedsphere/levitatedsphere.vue"
	export default {
		data() {
			return {
				videoUrl: "",
				videoList: [],
				dataList: [],
				pageData: {},
				videoStartTime: "",
				userInfo: "",
				responseData: {},
				isPageLength: 0,
				startFlag: true,
				// isStartExam: false
			}
		},
		computed: {
			isStartExam() {
				const videoEvery = this.videoList.every(item => item.isVideoOver && item.controlsBool);
				const dataEvery = this.dataList.every(item => item.isFileOver);
				console.log('计算属性执行了', this.videoList, this.dataList, videoEvery, dataEvery)
				if(this.startFlag){
					this.videoStartTime = this.$formatDates(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss');
					this.startFlag = false;
				}
				console.log(dataEvery, videoEvery, (this.videoList.length > 0 || this.dataList  > 0))
				if(dataEvery && videoEvery && (this.videoList.length > 0 || this.dataList  > 0)){
					let requestData = {
						workerId: this.userInfo.id,
						trainId: this.pageData.trainId,
						beginTime: this.videoStartTime,
						endTime: this.$formatDates(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss')
					}
					this.sendRequest({
						url: "xmgl/workerExam/submitStudy",
						data: requestData,
						method: 'post',
						success(res) {}
					})
				}
				
				return !(videoEvery && dataEvery);
			}
		},
		onReady: function(res) {
			// #ifndef MP-ALIPAY
			// this.videoContext = uni.createVideoContext('myVideo')
			// #endif
		},
		onLoad(options) {
			this.userInfo = JSON.parse(uni.getStorageSync("userInfo"))
			this.pageData = JSON.parse(options.transportData)
			console.log(this.pageData)
			this.getDataFn();
		},
		onShow() {
			// 刷新页面
			this.$forceUpdate();
		},
		methods: {
			fileTypeCondition(file) {
				// 获取文件后缀名
				const extension = file.substring(file.lastIndexOf('.') + 1).toLowerCase();

				// 常见的图片文件后缀名
				const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];

				// 检查文件后缀名是否在图片后缀名数组中
				return imageExtensions.includes(extension);
			},
			downLoadFile(val, type, index) {
				// let url = this.url_config + 'image/' + val.logoUrl
				let that = this;
				let url = val.url
				console.log(val)
				uni.showLoading({
					icon: 'loading',
					title: '下载中...'
				});
				uni.downloadFile({
					url: url,
					success: function(res) {
						var filePath = res.tempFilePath;
						// if (type == 1) {
						// 	//文件保存到本地
						// 	console.log(navigator && navigator.userAgent && /Mobi|Android|iPhone/i.test(navigator.userAgent))
						// 	if(navigator && navigator.userAgent && /Mobi|Android|iPhone/i.test(navigator.userAgent)){
						// 		console.log("111")
						// 		window.open(filePath, "_blank");
						// 		return
						// 	}
						// 	console.log("222")
						// 	return
						// 	uni.saveFile({
						// 		tempFilePath: filePath, //临时路径
						// 		success: function(res) {
						// 			uni.showToast({
						// 				icon: 'none',
						// 				mask: true,
						// 				title: '文件已保存：' + res.savedFilePath, //保存路径
						// 				duration: 3000,
						// 			});
						// 			setTimeout(() => {
						// 				//打开文档查看
						// 				uni.openDocument({
						// 					filePath: res.savedFilePath,
						// 					success: function(res) {
						// 						// console.log('打开文档成功');
						// 					}
						// 				});
						// 			}, 3000)
						// 		}
						// 	});
						// } else 
						if (type == 2) {
							uni.openDocument({
								filePath: filePath,
								success: function(res) {
									console.log('打开文档成功');
									uni.hideLoading();
									that.dataList[index].isFileOver = true;
									console.log(that.dataList);
								}
							});
						}
					}
				});
			},
			returnBack() {
				uni.navigateTo({
					url: '../index/index'
				})
			},
			videoStart(index) {
				
			},
			videoEnd(index) {
				var that = this
				// 判断是否可以开始考试，需要视频全部看完
				that.videoList[index].isVideoOver = true;
				that.videoList[index].controlsBool = true;
				// 尝试多次刷新视图
				that.$forceUpdate();
				setTimeout(function() {
					that.$forceUpdate();
				}, 500)
				// let startExamBool = true;
				// that.videoList.map(item => {
				// 	if (!item.isVideoOver) {
				// 		startExamBool = false;
				// 	}
				// })
				// if (!startExamBool) {
				// 	that.isStartExam = true;
				// } else {
				// 	that.isStartExam = false;
				// }
				
			},
			getDataFn() {
				var that = this
				let requestData = {
					courseId: this.pageData.courseId
				}
				this.sendRequest({
					url: "xmgl/workerExam/queryCourse",
					data: requestData,
					method: 'post',
					success(res) {
						console.log('试题信息', res)
						if (res.result) {
							that.responseData = res.result;
							const result = res.result.fileUrl ? JSON.parse(res.result.fileUrl) : [];
							that.videoList = result.filter(item => item.url.substring(item.url.lastIndexOf(".") +
								1) == "mp4");
							that.dataList = result.filter(item => item.url.substring(item.url.lastIndexOf(".") +
								1) != "mp4");
							console.log(result, that.videoList, that.dataList);
							// that.videoList
							// dataList
							// if (that.videoList.length) {
							// 	that.isStartExam = true;
							// 	that.videoUrl = that.videoList[0].url
							// }
							that.trainRecordId();
							console.log(that.src)
						}
					}
				})
			},
			videoErrorCallback: function(e) {
				uni.showModal({
					content: e.target.errMsg,
					showCancel: false
				})
			},
			trainRecordId() {
				var that = this
				const devInfoList = uni.getStorageSync('devInfoList')
				let requestData = {
					pageNo: 1,
					pageSize: 10,
					number: 1,
					trainId: this.pageData.trainId,
					workerCard: devInfoList.idCard,
					projectSn: devInfoList.projectSn,
				}
				this.sendRequest({
					url: "exam/courseRecord/page",
					data: requestData,
					method: 'post',
					success(res) {
						if (res.code == 200) {
							that.isPageLength = Array.isArray(res.result.records) ? res.result.records.length : 0;
							console.log(22222, res.result.records.length, that.isPageLength);
							const isPageFlag = that.isPageLength > 0 ? true : false;
							console.log(isPageFlag);
							that.dataList.map(item => {
								that.$set(item,'isFileOver',isPageFlag)
							})
							that.videoList.map(item => {
								that.$set(item,'isVideoOver',isPageFlag)
								that.$set(item,'controlsBool',isPageFlag)
							})
						}
					}
				})
			},
			goHiidden() {
				var that = this
				let requestData = {
					id: this.pageData.trainRecordId
				}
				this.sendRequest({
					url: "xmgl/workerExam/startExam",
					data: requestData,
					method: 'post',
					success(res) {
						if (res.code == 200) {
							uni.navigateTo({
								url: '../beginexam/beginexam?transportData=' + JSON.stringify(that
									.pageData)
							});
						}
					}
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.main-content {
		height: 100vh;
		display: flex;
		flex-direction: column;

		.top-diy {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.headerBack {
				position: absolute;
				left: 3%;
			}
		}

		.video {
			width: 100%;

			:deep() {
				.uni-video-ball {
					display: none !important;
				}
			}
		}

		// #myVideo {
		// 	width: 100%;
		// 	height: 386.25rpx;
		// 	position: relative;
		// }

		.studybox {
			height: 170rpx;
			background: #FFFFFF;
			box-shadow: 18rpx 8rpx 16rpx 4rpx rgba(168, 193, 255, 0.17);
			display: flex;
			align-items: center;

			.studybox-line {
				width: 14rpx;
				height: 100%;
				background: #4B8DEC;
			}

			.studybox-text1 {
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 500;
				font-size: 40rpx;
				color: #000000;
				margin-left: 40rpx;
			}
		}

		.btn {
			margin: 159.62rpx 40.38rpx;
		}
	}

	.rules {
		box-shadow: 4rpx 4rpx 8rpx 2rpx rgba(81, 129, 246, 0.12);
		// height: calc(100vh - 270rpx);
		// padding-bottom: 60rpx;
		// overflow-y: scroll;
	}

	.rules-box {
		display: flex;
		padding: 13.46rpx 28.85rpx 17.31rpx 23.08rpx;
		border-top: 2rpx solid #D8DBE8;
	}

	.rules-box image {
		width: 61.15rpx;
		height: 70.77rpx;
	}

	.rules-box>view {
		display: flex;
		justify-content: space-between;
		flex: 1;
	}

	.rules-text1 {
		display: flex;
		flex-direction: column;
		justify-content: center;
		margin-left: 13.46rpx;
	}

	.rules-text1>text {
		font-size: 25rpx;
		line-height: 40rpx;
	}

	.rules-text2 {
		display: flex;
		justify-content: center;
		align-items: center;
		color: #5181F6;
		font-size: 19.23rpx;
		white-space: nowrap;

		>text:last-child {
			margin-left: 10rpx;
		}
	}
</style>