<template>
	<view class="login">
		<Headers></Headers>
		<image class="bg" src="/static/images/bg.png"></image>
		<view class="ddflex" style="flex-direction: column;">
			<view class="register ddflex">
				<view class="re-con-pic">
					<image src="/static/images/loginBg1.png"></image>
				</view>
				<view class="re-con">
					<view class="re-tit">考生登录</view>
					<view class="re-li dflex">
						<input v-model="testNumber" type="number" placeholder="准考证号" maxlength="-1" placeholder-class="placeholder" class="re-ipt flex" />
					</view>
					<uni-data-select
					      v-model="paperId"
					      :localdata="range"
					      @change="changeTestPro"
						  placeholder="考试项目"
					    ></uni-data-select>
					<view class="re-btn" @click="okLogin()">登录</view>
					<view class="re-btn-text" @click="queryScore">考生成绩查询</view>
				</view>
			</view>
			<view class="bottom-content ddflex">
				<!-- 考试公告 -->
				<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 class="note-item-date">{{dateFormat(item.createDate)}}</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 class="note-item-date">{{dateFormat(item.createDate)}}</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: 400px;height: 243px;margin:30px auto;" v-show="!isPhotoing&&!imageUrl">
					<img style="width: 100%;height: 100%" src="/static/images/sfyz.png"/>
				</view>
				<view v-show="isPhotoing" style="width: 400px;height: 243px;margin:30px 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: 50px;color: #1AA1E6;font-weight: bold;">{{timeText}}</view>
				</view>
				<view style="width: 400px;height: 243px;margin:30px 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 :havaBackground='false'></Foot>
	</view>
</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 {
			title: 'Hello',
			width: 115,
			height: 36,
			testNumber: '',
			code: '',
			isCheckArg: true,
			range:[],
			otherInfo:[],//考试公告
			noteInfo:[],//注意事项
			
			paperId:'',//考试id
			
			isPhotoing:false,//是否正在验证身份
			imageUrl:'',
			timeText:3,
			timeInterval:null
		};
	},
	onLoad() {
		var tha = this;
		this.getTestProject()
		this.getTextOtherInfo()
		this.getTextNoteInfo()
	},
	onShow() {
	},
	methods: {
		jumpUrl(url){
			uni.navigateTo({
				url:url
			})
		},
		// 考试下拉框
		changeTestPro(e){
			console.log("e:", e);
		},
		// 获取考试项目
		getTestProject(){
			console.log('11')
			req.getRequest('/api/v3/exam/user/manager',{},res=>{
				console.log('this.range',res)
				this.range = res.map(item=>{return {text:item.title,value:item.id}})
				console.log(this.range)
			})
		},
		// 考试公告
		getTextOtherInfo(){
			let form={
				code:req.public.ksggCode,
				page:1,
				limit:3
			}
			req.getRequest('/api/content/list',form,res=>{
				this.otherInfo = res
			})
		},
		// 注意事项
		getTextNoteInfo(){
			let form={
				code:req.public.zysxCode,
				page:1,
				limit:3
			}
			req.getRequest('/api/content/list',form,res=>{
				this.noteInfo = res
			})
		},
		
		open() {
			this.$refs.popup.open('center')
		},
		close() {
			this.$refs.popup.close()
			clearInterval(this.timeInterval)
			this.isPhotoing = false
			this.imageUrl = ''
		},
		
		okLogin() {
			if (!this.testNumber) {
				return req.msg('请输入准考证号');
			}
			if (!this.paperId) {
				return req.msg('请选择考试项目');
			}
			var formP = {
				admission: this.testNumber,
				paperId: this.paperId
			};
			req.postRequest('/api/admission/login', formP, data => {
				if(data){
					req.setStorage('userInfo', data);
					// 如果进行身份验证
					// this.open()
					
					// 直接考试,是否允许考试
					req.getRequest(api.get_exam_question + this.paperId,{},quests=>{
						if (quests && quests.length > 0) {
							uni.navigateTo({
								url: '/pages/test/test?paperId='+this.paperId,
								success:()=> {
									this.close()
								}
							});
						}
					})
				}
			});
		},
		queryScore(){
			if (!this.testNumber) {
				return req.msg('请输入准考证号');
			}
			if (!this.paperId) {
				return req.msg('请选择考试项目');
			}
			var formP = {
				admission: this.testNumber,
				paperId: this.paperId
			};
			req.getRequest('/api/v3/exam/user/manager/result', formP, res => {
					uni.navigateTo({
						url:'/pages/scoreQuery/scoreQuery?paperId='+ this.paperId+'&admissionNo='+this.testNumber
					})
			});
			// req.postRequest('/api/admission/login', formP, data => {
			// 	if(data){
			// 		req.setStorage('userInfo', data);
			// 		req.getRequest('/api/v3/exam/user/manager/result', formP, res => {
			// 				uni.navigateTo({
			// 					url:'/pages/scoreQuery/scoreQuery?paperId='+ this.paperId+'&admissionNo='+this.testNumber
			// 				})
			// 		});
			// 	}
			// });
		},
		// 验证提交
		yanzhengSubmit(){
			uni.navigateTo({
				url: '/pages/test/test?paperId='+this.paperId,
				success:()=> {
					this.close()
				}
			});
		},
		// 时间格式化
		dateFormat(date){
			return req.dateFormat(date).v5
		},
		getUserInfo() {
			req.getRequest(
				'/api/v3/hy/account/userInfo',
				{},
				data => {
					req.setStorage('userInfo', data);
					if(data.type==1||data.isStaff){
						uni.reLaunch({
							url: '/pages/learn/learn'
						});
					}else{
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				},
				true
			);
		},
		
		// 身份验证
		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.isPhotoing = false
			// setTimeout(() => {
			// 	uni.canvasToTempFilePath({
			// 		canvasId: 'canvas',
			// 		destWidth: 60,
			// 		destHeight: 40,
			// 		success: function (res) {
			// 			console.log(res.tempFilePath) //图片路径
			// 			// resolve(res.tempFilePath)
			// 			_this.imgUrl = res.tempFilePath
			// 		},
			// 		fail: function (res) {
			// 			console.log(res.errMsg)
			// 		}
			// 	})
			// }, 100)
		},
		dataURLtoBlob(dataurl) {
		    var arr = dataurl.split(','),
		            mime = arr[0].match(/:(.*?);/)[1],
		            bstr = atob(arr[1]),
		            n = bstr.length,
		            u8arr = new Uint8Array(n);//8位无符号整数，长度1个字节
		        console.log(mime)
		        while (n--) {
		            u8arr[n] = bstr.charCodeAt(n);
		        }
		        // console.log(JSON.stringify(u8arr));
		        return new Blob([u8arr], {
		            type: mime
		        });
		    },
		base64toFile (dataurl, filename){
			var arr = dataurl.split(','),
			    mime = arr[0].match(/:(.*?);/)[1],
			    bstr = atob(arr[1]),
			    n = bstr.length,
			    u8arr = new Uint8Array(n);
			while (n--) {
			    u8arr[n] = bstr.charCodeAt(n);
			}
			return new File([u8arr], filename, {
			    type: mime
			});
		},
		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({
							
						// })
					}
				})
			});
		},
	}
};
</script>

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