<template>
	<page-meta :root-font-size="fontsize+'px'" style="display: block;">
	<view class="select-test">
		<Headers></Headers>
		<view class="project">
			<view style="width: 12rem;margin: auto;">职业技能在线考试系统</view>
		</view>
		
		<view class="project-content ddflex">
			<!-- 成绩区域 -->
			<view class="test-box">
				<view class="test-title">选择考试试卷</view>
				<view>
					<view class="note-item ddflex" style="font-size: 0.16rem;" v-for="item,index in testList" :key="index+'test'">
						<view class="note-item-content" @click="item.resultId?'':toTest(item)">{{index+1}}.  {{item.title}}</view>
						<view style="color: green;font-size: 0.14rem;" v-if="item.resultId" @click="queryScore(item)">成绩查询</view>
					</view>
				</view>
				
				<!-- <uni-pagination style="margin-top: 30px;" title="标题文字" show-icon="true" total="50" current="2"></uni-pagination> -->
				
				<!-- <navigator class="back-btn ddflex" hover-class="none" open-type="navigateBack">
					<image src="/static/images/back3.png"></image>
					<text>返回上一页</text>
				</navigator> -->
			</view>
			<!-- 答题卡区域 -->
			<view class="test-info ddflex" v-if="false">
				<view class="test-people ddflex">
					<image :src="examResult.avatar"></image>
					<view class="test-people-info ddflex">
						<view class="ddflex">
							<view class="test-people-label">考生姓名</view>
							<view class="fflex">{{examResult.userName}}</view>
						</view>
						<view class="ddflex">
							<view class="test-people-label">准考证号</view>
							<view class="fflex" style="word-break: break-all;">{{examResult.admissionNo}}</view>
						</view>
						<view class="ddflex">
							<view class="test-people-label">考试科目</view>
							<view class="fflex">{{examResult.title}}</view>
						</view>
					</view>
				</view>
				<view class="note-box">
					<view class="note-title ddflex">
						<image class="note-title-icon" src="/static/images/ksgg.png"></image>
						<view>考试公告</view>
					</view>
					<view>
						<view class="note-item ddflex" v-for="item,index in otherInfo" :key="index" @click="jumpUrl('/pages/contentDetail/contentDetail?id='+item.id)">
							<view class="note-item-content">{{item.title}}</view>
						</view>
					</view>
				</view>
				<!-- 注意事项 -->
				<view class="note-box">
					<view class="note-title ddflex">
						<image class="note-title-icon" src="/static/images/zysx.png"></image>
						<view>注意事项</view>
					</view>
					<view>
						<view class="note-item ddflex" v-for="item,index in noteInfo" :key="index+'zy'" @click="jumpUrl('/pages/contentDetail/contentDetail?id='+item.id)">
							<view class="note-item-content">{{item.title}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<uni-popup ref="popup" type="bottom" :is-mask-click='false'>
			<view class="popup-box">
				<view class="popup-top ddflex">
					<view>身份验证</view>
					<image src="/static/images/close.png" @click="close()"></image>
				</view>
				<view class="popup-content">您好！考试前需要进行身份验证，请手持准考证，对准摄像头进行拍照，示例如下</view>
				<view style="width: 4rem;height: 2.43rem;margin:0.3rem auto;" v-show="!isPhotoing&&!imageUrl">
					<img style="width: 100%;height: 100%" src="/static/images/sfyz.png"/>
				</view>
				<view v-show="isPhotoing" style="width: 4rem;height: 2.43rem;margin:0.3rem auto;position: relative;" id="video-box">
					<video id="video" style="width: 100%;height: 100%;" object-fit='fill' :autoplay="true" :controls="false" :show-center-play-btn="false"></video>
					<canvas id="canvas" style="width: 100%;height: 100%;position: absolute;top:100000px;"  canvas-id="canvas"></canvas>
					<view style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);z-index: 100;font-size: 0.5rem;color: #1AA1E6;font-weight: bold;">{{timeText}}</view>
				</view>
				<view style="width: 4rem;height: 2.43rem;margin:0.3rem auto;" v-show="!isPhotoing&&imageUrl">
					<img style="width: 100%;height: 100%" :src="imageUrl"/>
				</view>
				<view class="popup-bottom ddflex">
					<view class="popup-btn2" @click="yanzheng" v-show="!isPhotoing">{{imageUrl?'重新验证':'立即验证'}}</view>
					<view class="popup-btn2" v-if="imageUrl" @click="yanzhengSubmit">确认</view>
				</view>
			</view>
		</uni-popup>
		
		<Foot></Foot>
	</view>
	</page-meta>
</template>

<script>
	const app = getApp();
	const req = require('../../utils/request.js');
	const utils = require('../../utils/util.js');
	const api = require('../../utils/api.js')
	export default {
		data() {
			return {
				paperId:null,
				admissionNo:null,
				paper: '', //试卷详情
				examResult:{},//考试详情
				
				otherInfo:[],
				noteInfo:[],
				
				testList:[],
				
				userInfo:{},
				
				item:{},
				isPhotoing:false,//是否正在验证身份
				imageUrl:'',
				timeText:3,
				timeInterval:null,
				fontsize:'100px'
			}
		},
		onReady() {},
		onLoad(options) {
			let srceenNunber = 19.2; //因设计图是1920所有把设计图分为19.2份，所以html字体大小为100px
			    let that = this;
			
			    //窗体改变大小触发事件
			    uni.onWindowResize((res) => {
			        console.log('变化后的窗口宽度=', res.size.windowWidth);
			        that.fontsize = parseFloat(res.size.windowWidth) / srceenNunber;
			    })
			
			    //打开获取屏幕大小
			    uni.getSystemInfo({
			        success(res) {
			            console.log('设备信息：', res);
			            that.fontsize = res.screenWidth / srceenNunber;
			            console.log('字体大小：', that.fontsize);
			        }
			    })
			
			this.paperId = options.paperId;
			this.admissionNo = options.admissionNo;
		},
		onShow() {
			this.getTestProject()
			this.getUserInfo()
		},
		methods: {
			IsPC() {
			    var userAgentInfo = navigator.userAgent;
			    var Agents = ["Android", "iPhone",
			                "SymbianOS", "Windows Phone",
			                "iPad", "iPod"];
			    var flag = true;
			    for (var v = 0; v < Agents.length; v++) {
			        if (userAgentInfo.indexOf(Agents[v]) > 0) {
			            flag = false;
			            break;
			        }
			    }
			    return flag;
			},
			jumpUrl(url){
				uni.navigateTo({
					url:url
				})
			},
			// 考试信息
			getUserInfo(){
				req.getRequest('/api/v3/exam/user/manager/info',{},res=>{
					this.userInfo = res
				})
			},
			// 获取考试项目
			getTestProject(){
				req.getRequest('/api/v3/exam/user/manager/paper',{examId:this.paperId},res=>{
					this.testList = res
				})
			},
			// 去考试
			toTest(item){
				uni.showModal({
					title:'提示',
					content:`确定开始 ${item.title}？`,
					success: (res) => {
						if(res.confirm){
							if(this.IsPC()){
								// 如果进行身份验证
								this.item = item
								this.open()
							}else{
								// 直接考试,是否允许考试
								uni.navigateTo({
									// url: '/pages/test/test?paperId='+this.paperId,
									url: '/pages/test/test?paperId='+item.id+'&testId='+this.paperId,
									success:()=> {
										this.close()
									}
								});
								
							}
							
						}else{
							
						}
					}
				})
			},
			open() {
				this.$refs.popup.open('center')
			},
			close() {
				this.$refs.popup.close()
				clearInterval(this.timeInterval)
				this.isPhotoing = false
				this.imageUrl = ''
			},
			// 验证提交
			yanzhengSubmit(){
				let userPhotoData = {examId:this.paperId,image:this.imageUrl,paperId:this.item.id}
				req.postRequest('/api/v3/exam/user/manager/image',userPhotoData,res=>{
					uni.navigateTo({
						// url: '/pages/test/test?paperId='+this.paperId,
						url: '/pages/test/test?paperId='+this.item.id+'&testId='+this.paperId,
						success:()=> {
							this.close()
						}
					});
				})
			},
			// 身份验证
			yanzheng(){
				this.imageUrl = ''
				this.test()
			},
			takePhoto() {
				let _this = this
			    //获得Canvas对象
				const query = uni.createSelectorQuery().in(this);
			    let video = document.querySelector('video');
				let canvas = document.querySelector('canvas')
			    let ctx = canvas.getContext('2d');
				let videoInfo = {}
				query.select('video').boundingClientRect(result => {
					console.log('videoInfo',result)
					videoInfo={
						width:result.width,
						height:result.height
					}
				}).exec();
			    ctx.drawImage(video, 0, 0, videoInfo.width, videoInfo.height);
				// console.log(this.dataURLtoBlob(canvas.toDataURL(),'11'))
				req.uploadFile('/api/upload', canvas.toDataURL(), res => {
					// req.msg('图片上传成功');
					console.log('图片上传成功',res)
					// _this.imageUrl = canvas.toDataURL()
					_this.imageUrl = res.src
					_this.isPhotoing = false
				},false);
			},
			test(){
				// var video = document.querySelector('video');
				const query = uni.createSelectorQuery().in(this);
				var video = query.select('#video')
				console.log('video',video)	
				// 兼容代码
				window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
				// 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
				if (navigator.mediaDevices === undefined) {
				    navigator.mediaDevices = {};
				}
				console.log('navigator.mediaDevices',navigator.mediaDevices)
				// 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
				// 使用getUserMedia，因为它会覆盖现有的属性。
				// 这里，如果缺少getUserMedia属性，就添加它。
				if (navigator.mediaDevices.getUserMedia === undefined) {
					navigator.mediaDevices.getUserMedia = function(constraints) {
						// 首先获取现存的getUserMedia(如果存在)
					    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
						// 有些浏览器不支持，会返回错误信息
						// 保持接口一致
					    if (!getUserMedia) { //不存在则报错
					        return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
					    }
						// 否则，使用Promise将调用包装到旧的navigator.getUserMedia
					    return new Promise(function(resolve, reject) {
					        getUserMedia.call(navigator, constraints, resolve, reject);
					    });
					}
				}
				//摄像头调用配置
				var mediaOpts = {
				    audio: false,
				    video: { facingMode: "user"} 
				    
				}
							 
				let that=this;
				navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
				    that.mediaStreamTrack = stream;
				    video = document.querySelector('video');
					console.log('video = document.querySelector(video);',video)
						// 旧的浏览器可能没有srcObject
				    if ("srcObject" in video) {
				        video.srcObject = stream
				    } else {
						// 避免在新的浏览器中使用它，因为它正在被弃用。
				        video.src = window.URL && window.URL.createObjectURL(stream) || stream
				    }
				    video.play();
					that.isPhotoing = true
					that.timeText = 3
					that.timeInterval = setInterval(()=>{
						if(that.timeText>0){
							that.timeText--
						}else{
							clearInterval(that.timeInterval)
							that.timeInterval= null
							that.takePhoto()
						}
					},1000)
				}).catch(function (err) {
				    console.log(err)
					uni.showModal({
						title:'提示',
						content:'未找到摄像头',
						showCancel:false,
						success() {
							// uni.navigateBack({
								
							// })
						}
					})
				});
			},
			
			// 成绩查询
			queryScore(item){
				var formP = {
					admission: this.userInfo.admissionNo,
					paperId: item.id
				};
				console.log(this.userInfo)
				req.getRequest('/api/v3/exam/user/manager/result', formP, res => {
						uni.navigateTo({
							url:'/pages/scoreQuery/scoreQuery?paperId='+ item.id+'&admissionNo='+this.userInfo.admissionNo
						})
				});
			},
		}
	}

</script>

<style>
	@import url('./selectTest.css');
</style>