<template>
	<div class="viewfinder">
		<div class="wrap-box" ref="wrap">
			<div class="imgStyle bgImg1" v-if="ifZm"></div>
			<div class="imgStyle bgImg2" v-else></div>
		</div>
		<span class="text">请将证件完整置于取景框内</span>
		<div class="buttonBox">
			<!-- 拍照按钮 -->
			<img class="buttonImg" id="back" src="../../static/images/back.png" />
			<img class="buttonImg" @click="photograph" src="../../static/images/pai.png" />
			<img class="buttonImg" @click="fanzhuan" src="../../static/images/fan.png" />
		</div>
		<uni-popup ref="popup" type="top" :mask-click="false">
			<view class="popup-content">

				<img :src="imageFile" style="width: 100%;height: 200px;"></image>
				<div class="popupBox">
					<button class="mini-btn" type="primary" @click="okBtn" size="mini">确认</button>
					<button class="mini-btn" @click="closeBtn" type="default" size="mini">取消</button>
				</div>
			</view>
		</uni-popup>
	</div>

</template>
<script>
	let canvasEle = null
	let video = null
	// import {
	//     UpImgHttp
	// } from '../../utils/https.js'
	export default {
		components: {},
		data() {
			return {
				ioswx: '',
				imageFile: "",
				mediaStreamTrack: "",
				timerIntv: null, //只需要此参数
				canvasEle: '',
				videoHeight: 200,
				videoDevices: [],
				selectedDeviceId: '',
				isLoding: false,
				dataMock: [],
				ifZm: true,
			}
		},
		onLoad() {},
		mounted() {
			// uniapp必须创建元素不然获取不到里面的方法
			video = document.createElement('video')
			video.setAttribute('position', 'fixed')
			video.setAttribute('height', '200px')
			// video.setAttribute('autoplay', true)
			// video.setAttribute('width', 280)
			this.canvasEle = document.createElement('canvas')
			this.canvasEle.width = window.screen.width
			this.canvasEle.height = this.videoHeight
			var wrap = this.$refs.wrap
			// wrap.appendChild(canvasEle)
			console.log(wrap);
			wrap.appendChild(video)
			this.ioswx = this.isWXandIos();
			// this.openCamera();
		},
		async onShow() {
			let cardType = localStorage.getItem("cardType")
			if (cardType === 'front') {
				this.ifZm = true;
			} else {
				this.ifZm = false;
			}
			await this.openCamera();
			this.getDevices()
			this.takePhoto()
		},
		methods: {
			isWXandIos() {
				const aegent = navigator.userAgent.toLowerCase();
				if (/micromessenger/.test(aegent) && /iPhone|mac|iPod|iPad/i.test(aegent)) {
					return true;
				}
				return false;
			},
			closeBtn() {
				this.$refs.popup.close();
				this.openCamera();
			},
			okBtn() {
				uni.$emit('eventName', {
					base64: this.imageFile
				});
				uni.navigateBack({
					delta: 1
				});
			},
			async getDevices() {
				let number = 1;
				// enumerateDevices获取所有媒体设备
				const mediaDevices = await navigator.mediaDevices.enumerateDevices();

				// 通过设备实例king属性videoinput，过滤获取摄像头设备
				const videoDevices = mediaDevices.filter(item => item.kind === 'videoinput') || [];
				this.videoDevices = videoDevices;
				videoDevices.map(item => {
					let label = '摄像头' + number;
					if (item.label && item.label.search('back') !== -1) {
						label = "后置" + label;
					}
					if (item.label && item.label.search('front') !== -1) {
						label = "前置" + label;
					}
					number++;
					this.dataMock.push({
						text: label,
						value: item.deviceId
					})
				});
			},
			async openCamera() {
				this.isLoding = true
				let constraints = {};
				if (localStorage.getItem('deviceIndex')) {
					let indexDev = localStorage.getItem('deviceIndex')
					if (this.dataMock && this.dataMock[indexDev]) {
						this.selectedDeviceId = this.dataMock[indexDev].value;
					}
				}
				if (!this.selectedDeviceId || this.dataMock.length < 3) {
					constraints = {
						audio: false,
						video: {
							facingMode: this.mode,
							width: this.videoHeight,
							height: window.screen.width,
						},
					}
				} else {
					constraints = {
						audio: false,
						video: {
							deviceId: this.selectedDeviceId,
							facingMode: "continuous",
							width: this.videoHeight,
							height: window.screen.width,
						},
					}
				}
				// 兼容
				// 老的浏览器没实现mediaDevices
				if (navigator.mediaDevices === undefined) navigator.mediaDevices = {};
				if (navigator.mediaDevices.getUserMedia === undefined) {
					navigator.mediaDevices.getUserMedia = function(constraints) {
						const getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
							navigator
							.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
						if (!getUserMedia) {
							return Promise.reject(new Error(
								'getUserMedia is not implemented in this browser'));
						}
						return new Promise(function(resolve, reject) {
							getUserMedia.call(navigator, constraints, resolve, reject);
						});
					};
				}
				// 获取视频流
				const that = this;
				navigator.mediaDevices.getUserMedia(constraints)
					.then(function(stream) {
						const video = document.querySelector('video');
						video.srcObject = stream;
						that.mediaStreamTrack = stream.getTracks()[0];
						video.onloadedmetadata = function() {
							video.play();
						};
						// 不是微信内置浏览器
						if (!that.ioswx) {
							that.status = 1;
						}
					})
					.catch(function(err) {
						// 调用原始摄像头;
						alert("访问用户媒体设备失败：" + err.name + " " + err.message);
					});
			},
			photograph() {
				// this.imageFile,'this.imageFile'
				console.log(this.imageFile, 'this.imageFile')
				if (this.mediaStreamTrack) {
					this.mediaStreamTrack.stop();
				}
				this.$refs.popup.open()
				// canvas.toDataURL('image/png')
				this.imageFile = this.canvasEle.toDataURL('image/png');
			},
			fanzhuan() {
				if (this.videoDevices && this.videoDevices.length < 3) {
					this.mode = this.mode === 'user' ? 'environment' : 'user';
					this.mediaStreamTrack.stop();
					this.openCamera();
				} else {
					uni.showActionSheet({
						itemList: this.dataMock.map(item => item.text),
						success: (res) => {
							// 用户点击了哪一个按钮，通过res.tapIndex获取索引
							console.log('用户点击了：', res.tapIndex);
							this.mediaStreamTrack.stop();
							localStorage.setItem('deviceIndex', res.tapIndex);
							this.openCamera();
						},
						fail: (err) => {
							// 处理错误情况
							console.error('显示ActionSheet失败：', err);
						}
					});

				}
			},
			takePhoto() {
				let that = this;

				function draw() {
					that.canvasEle.getContext('2d').drawImage(video, 0, 0, that.canvasEle.width, that.canvasEle.height);
					requestAnimationFrame(draw);
				}
				draw();
				// this.timerIntv = setInterval(() => {
				// 	// 待处理业务逻辑    
				// 	var aspectRatio = video.videoWidth / video.videoHeight;
				// 	that.canvasEle.getContext('2d').drawImage(video, 0, 0, that.canvasEle.width, that.canvasEle
				// 		.height);
				// }, 10)
			},
			// 将截图转化为base64格式，通过','分割，将后面的base64值转化为文件格式
			canvasToFile(canvas) {
				const dataurl = canvas.toDataURL('image/png');
				var data = {
					url: dataurl.split(',')[1]
				}
				// UpImgHttp(data).then(res => {
				//     alert(res.msg)
				//     if (JSON.parse(res.msg).error_msg == 'SUCCESS') {
				//         uni.navigateTo({
				//             url: `../photograph/photograph?Stu_id=${JSON.parse(res.msg).result.user_list[0].user_id}`
				//         })
				//     } else {
				//         uni.showToast({
				//             icon: "error",
				//             title: "暂无信息",
				//             duration: 1000
				//         })
				//     }
				// }).catch(res => {
				//     alert(res)
				// })
			},
		},
		onHide() {
			clearInterval(this.timerIntv)
		},
		destroyed() {
			clearInterval(this.timerIntv)
		}
	}
</script>
<style lang="scss" scoped>
	.imgStyle {
		width: 300px;
		height: 190px;
		/* margin-top: 50px; */
		position: absolute;
		// top: 10px;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10;

	}

	.bgImg1 {
		background-image: url('../../static/html/camera_idcard_front.png');
		background-size: 100% 100%;
	}

	.bgImg2 {
		background-image: url('../../static/html/camera_idcard_back.png');
		background-size: 100% 100%;
	}

	.viewfinder {
		background-color: blanchedalmond;
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
		position: flex;
	}

	.wrap-box {
		margin-top: 10vh;
		width: 100%;
		// height: 300px;
		position: relative;

	}

	.buttonBox {
		display: flex;
		justify-content: space-around;
		// margin-top: 25vh;
		align-items: center;
		margin-top: 28vh;
	}

	.popupBox {
		margin-top: 2vh;
		width: 100%;
		display: flex;
		justify-content: space-around;
	}

	.buttonImg {
		width: 15vw;
		object-fit: contain;
	}

	.text {
		margin-top: 3vh;
		text-align: center;
		color: #888;
		/* color: red; */
	}

	.popup-content {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: auto;
		padding: 13px 0;
		background-color: #fff;
		// border-radius: 8px;
	}
</style>