<template>
	<page-meta :root-font-size="fontsize+'px'" style="display: block;">
	<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/loginBg2.png"></image>
				</view>
				<view class="re-con">
					<view class="re-tit">考生登录</view>
					<view class="re-li dflex">
						<input v-model="testNumber" @blur="getTestProject" type="idcard" 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 style="font-size: 0.16rem;">注意事项</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: 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 :havaBackground='false'></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 {
			title: 'Hello',
			width: 115,
			height: 36,
			testNumber: '',
			code: '',
			isCheckArg: true,
			range:[],
			otherInfo:[],//考试公告
			noteInfo:[],//注意事项
			
			paperId:'',//考试id
			
			isPhotoing:false,//是否正在验证身份
			imageUrl:'',
			timeText:3,
			timeInterval:null,
			
			fontsize:'100px'
		};
	},
	onLoad() {
		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);
                }
            })
		
		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')
			let data = {
				
			}
			if(this.testNumber) data.idNumber = this.testNumber
			else delete data.idNumber
			req.getRequest('/api/v3/exam/user/manager',data,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()
					
					// 直接考试,是否允许考试
					uni.navigateTo({
						// url: '/pages/test/test?paperId='+this.paperId,
						url: '/pages/selectTest/selectTest?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
					})
			});
		},
		// 验证提交
		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>
