<!--
 * @Author: your name
 * @Date: 2020-08-28 15:20:15
 * @LastEditTime: 2020-10-10 17:19:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xfhd-vue-scaffold/src/page/index/Home/Index.vue
-->
<template>
	<div class="camera">
		<div class="video-con">
			<div class="kuang" ref="kuang"></div>
			<video
				id="gum-local"
				class="video"
				width="100%"
				height="100%"
				autoplay
				playsinline
				ref="myVideo"
			></video>
		</div>

		<!-- 获取权限 -->
		<button
			id="showVideo"
			class="btn"
			ref="showVideoBtn"
			@click="initVideo($event)"
		>
			开启摄像头
		</button>
		<button class="btn2" ref="takePhotoBtn" @click="takePhoto($event)">
			拍照
		</button>

		<img ref="photo" class="photo" :src="imgsrc" />
	</div>
</template>
<script>
// @ is an alias to /src
import gsap from "gsap";

export default {
	name: "Index",
	components: {},
	data() {
		return {
			imgsrc: "",
		};
	},
	mounted() {
		this.initCanvas();
		// this.requestPermission().then((res) => {
		//     if (res === true) {
		//         // 权限获取成功
		//     }
		// });
	},
	methods: {
		// 获取设备权限
		getDevicePermission(constraints) {
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function (constraints) {
					var 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
						);
					});
				};
			}

			return global.navigator.mediaDevices
				.getUserMedia(constraints)
				.then((stream) => {
					if (stream) {
						stopStreamTracks(stream);
						return true;
					}
					return Promise.reject(new Error("EmptyStreamError"));
				})
				.catch((errMsg) => {
					if (errMsg && "NotAllowedError" === errMsg.name) {
						return false;
					}
					return Promise.reject(errMsg);
				});
		},
		// 开始获取权限
		requestPermission() {
			return this.getDevicePermission({ video: true, audio: true })
				.catch(() =>
					this.getDevicePermission({ video: false, audio: true })
				)
				.catch(() =>
					this.getDevicePermission({ video: true, audio: false })
				)
				.catch(() => true);
		},
		// 初始化 video
		async initVideo(e) {
			const constraints = {
				video: {
					facingMode: "user",
				},
			};

			try {
				this.stream = await navigator.mediaDevices.getUserMedia(
					constraints
				);
				this.handleSuccess(this.stream, constraints);
				e.target.disabled = true;
			} catch (e) {
				this.handleError(e);
			}
		},
		handleSuccess(stream, constraints) {
			this.video = this.$refs.myVideo;
			const videoTracks = stream.getVideoTracks();
			gsap.to(this.$refs.kuang, { autoAlpha: 1 });
			gsap.to(this.$refs.showVideoBtn, { autoAlpha: 0 });
			gsap.to(this.$refs.takePhotoBtn, { autoAlpha: 1 });
			console.log("Got stream with constraints:", constraints);
			console.log(`Using video device: ${videoTracks[0].label}`);
			window.stream = stream; // make variable available to browser console
			this.video.srcObject = stream;
		},
		handleError(error) {
			console.error(error);
		},
		initCanvas() {
			this.canvas = document.createElement("canvas");
			this.ctx = this.canvas.getContext("2d");
			this.canvas.width = 650 * 1.2;
			this.canvas.height = 900 * 1.2;
		},
		async takePhoto() {
			this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			// this.ctx.fillStyle = "#fff";
			// this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
			this.ctx.drawImage(
				this.$refs.myVideo,
				0,
				0,
				650,
				900,
				650 * 0.14,
				900 * 0.1,
				650,
				900
			);
			let img = await this.loadImage(
				require("@/assets/images/overlay.png")
			);
			this.ctx.drawImage(img, 0, 0, 650 * 1.2, 900 * 1.2);

			this.imgsrc = this.canvas.toDataURL("image/jpeg");

			gsap.to(this.$refs.photo, { autoAlpha: 1 });
		},
		loadImage(src) {
			return new Promise((resolve, reject) => {
				let img = new Image();
				img.onload = (res) => {
					resolve(img);
				};
				img.onerror = (res) => {
					reject(img);
				};
				img.src = src;
			});
		},
	},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.camera {
	// min-height: 100vh;
	padding: 100px 0;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-content: center;
	align-items: center;
	.kuang {
		visibility: hidden;
		.paLayout(-12.5%,-10%,120%,120%,1);
		.bg-norepeat("overlay","png");
		pointer-events: none;
	}
	.video-con {
		.prLayout(650px,900px);
		// border: 1px solid #fff;
		.video {
			position: relative;
			z-index: 0;
			// width: 700px;
			// height: 700px;
		}
	}
	.btn,
	.btn2 {
		margin: 50px;
		background-color: #fff;
		.prLayout(200px,50px);
		line-height: 40px;
		text-align: center;
		border-radius: 4px;
		font-size: 14px;
	}
	.btn2 {
		visibility: hidden;
	}
	.photo {
		visibility: hidden;
		.prLayout(750px,1000px);
	}
}
</style>