<template>
	
		<div class="container2" :style="{ backgroundImage: `url(${bg})` }">
			<div class="tracking-wrap">
				<img class="border" :src="border" alt="" />
				<div
					class="tracking"
					:style="{ opacity: tabIndex === 0 ? '1' : '0' }"
				>
					<video
						id="video"
						width="620"
						height="460"
						preload
						autoplay
						loop
						muted
					></video>
					<canvas id="canvas" width="620" height="460"></canvas>
				</div>
			</div>
			<!--      <div class="tabs">-->
			<!--        <div-->
			<!--            class="tab"-->
			<!--            :class="tabIndex === index? 'active' : ''"-->
			<!--            v-for="(item, index) in tabs" :key="index"-->
			<!--            @click="tabHandle(index)"-->
			<!--        >-->
			<!--          <Icon :type="item.icon" size="80" color="#fff" />-->
			<!--          <span class="label">{{ item.text === '扫码登录' ? (isUpdateFace ? '人脸录入' : item.text) : item.text }}</span>-->
			<!--        </div>-->
			<!--      </div>-->
			<div
				class="form"
				:style="{ opacity: tabIndex === 1 ? '1' : '0' }"
				@keyup.enter="enterHandle"
			>
				<div class="title">登录</div>
				<div class="content">
					<Form ref="form" :model="form" :rules="rules">
						<FormItem prop="user">
							<Input
								type="text"
								v-model="form.account"
								placeholder="请输入用户"
							>
								<Icon
									type="ios-person-outline"
									slot="prepend"
								></Icon>
							</Input>
						</FormItem>
						<FormItem prop="pwd">
							<Input
								type="password"
								v-model="form.password"
								placeholder="请输入密码"
							>
								<Icon type="ios-lock-outline" slot="prepend" />
							</Input>
						</FormItem>
					</Form>
				</div>
				<div class="btn">
					<Button type="primary" @click="login">密码登录</Button>
				</div>
			</div>
		</div>
</template>

<script>
import '@/assets/js/tracking'
import '@/assets/js/face-min.js'
import { Login, UpdateFace, getUserInfo } from '@/api/account'
import { logOut, getStoreTitle, getToken } from '@/libs/util'
import { FindByFace } from '@/api/account'
import border from '_static/images/border.png'
import bg from '_static/images/bg.jpg'
export default {
	name: 'Home',
	data() {
		return {
			modal: false,
			loginTimer: null,
			saveFaceTimer: null,
			tabIndex: 1,
			tabs: [
				{ icon: 'md-qr-scanner', text: '扫码登录' },
				{ icon: 'ios-contact-outline', text: '账户登录' },
			],
			type: '',
			form: {
				account: '',
				password: '',
			},
			rules: {
				account: [
					{ required: true, message: '请输入用户', trigger: 'blur' },
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
				],
			},
			border,
			bg,
			trackerTask: null,
			tracking: true, // 捕获人脸中
			isUpdateFace: false, // 登录人脸录入
			video: null,
			tokenCopy:getToken(),
		}
	},
	props: {
		// 是否显示表单
		value: {
			type: Boolean,
			default: false,
			require: true,
		},
	},
	watch: {
		value: {
			handler(n) {
				this.$emit('input', this.value)
			},
			immediate: true,
		},
		// modal (n) {
		//   this.$emit('input', n)
		//   if (n) {
		//     this.$nextTick(() => {
		//       setTimeout(() => {
		//         this.openCamera()
		//       }, 300)
		//     })
		//   } else {
		//     this.trackerTask.stop()
		//     this.stopMediaStreamTrack()
		//   }
		// }
	},
	methods: {
		enterHandle() {
			this.login()
		},
		login() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					Login(this.form).then((res) => {
						if (res.code === 0) {
							this.$store.commit('setToken', res.result.token)
							getUserInfo().then((res) => {
								if (res.code === 0) {
									if (res.result.isBindFace) {
										this.toNext()
									} else {
										this.$Message.error(
											'当前用户未绑定人脸,请绑定人脸后登入'
										)
										this.tabIndex = 0
										this.tracking = true
										this.trackerTask.run()
										this.isUpdateFace = true
									}
								}
							})
						}
					})
				}
			})
		},
		/* 选项卡切换 */
		tabHandle(index) {
			this.tabIndex = index
			if (index === 0) {
				this.tracking = true
				this.trackerTask.run()
			} else {
				this.trackerTask.stop()
				this.tracking = false
				this.isUpdateFace = false
				clearTimeout(this.loginTimer)
				clearTimeout(this.saveFaceTimer)
			}
		},
		/* 登录成功后跳转 */
		toNext() {
			const _this = this
			this.$store.dispatch('getUserInfo').then((res) => {
				if (
					['storekeeper', 'supervisor'].includes(res.result.roleKey)
				) {
					this.$Message.success('登录成功！')
					this.$store.commit('setToken', _this.tokenCopy)
					this.$store.dispatch('getUserInfo')
					_this.$emit('face-check', true)
					return
					PlcStorageOut({
						inOutStorageNo: this.data.inOutStorageNo,
						storageDoor: sessionStorage.getItem('door'),
						plcStationCode: sessionStorage.getItem('plcCode'),
						rfidList: this.scanData.scanTagMesList.map(
							(item) => item.rfidCode
						),
					}).then((res) => {
						if (res.code === 0) {
							this.$Message.info('出库成功！')
							setTimeout(() => {
								this.$router.push({
									name: 'Home',
									query: {
										plcCode:
											sessionStorage.getItem('plcCode'),
										door: sessionStorage.getItem('door'),
									},
								})
							}, 500)
						}
					})
					logOut()
					// this.trackerTask.stop();
					// this.$router.push({
					//   name: 'warning-list',
					//   query: {
					//     data: this.data
					//   }
					// })
				} else {
					this.$Message.error('请联系仓库员或总监处理！')
				}
			})
		},
		stopMediaStreamTrack() {
			if (typeof window.stream === 'object') {
				//	this.videoEl是视频流容器，也就是video标签，需要在data中声明这个变量，然后在打开摄像头的方法中this.videoEl.srcObject = window.stream
				this.video.srcObject = null
				window.stream.stop()
			}
		},
		openCamera() {
			let _this = this
			let video = (this.video = document.getElementById('video'))
			let canvas = document.getElementById('canvas')
			let context = canvas.getContext('2d')
			context.lineWidth = 2
			context.strokeStyle = 'blue'

			let tracker = new tracking.ObjectTracker('face')
			tracker.setInitialScale(4)
			tracker.setStepSize(1)
			tracker.setEdgesDensity(0.1)

			this.trackerTask = tracking.track('#video', tracker, {
				camera: true,
			})

			tracker.on('track', function (event) {
				context.clearRect(0, 0, canvas.width, canvas.height)
				if (_this.tracking && event.data.length === 1) {
					console.log('获取人脸--')
					let rect = event.data[0]
					context.strokeRect(rect.x, rect.y, rect.width, rect.height)
					_this.tracking = false
					let cut = document.createElement('canvas')
					cut.width = video.width
					cut.height = video.height
					if (_this.isUpdateFace) {
						cut.getContext('2d').drawImage(
							video,
							rect.x - 100,
							rect.y - 100,
							rect.width + 500,
							rect.height + 500,
							0,
							0,
							800,
							800
						)
					} else {
						cut.getContext('2d').drawImage(
							video,
							rect.x - 100,
							rect.y - 100,
							rect.width + 500,
							rect.height + 500,
							0,
							0,
							400,
							400
						)
					}
					let url = cut.toDataURL('image/png')
					FindByFace({
						data: {
							base64: url,
						},
						sign: '_sign',
						source: '_source',
					}).then((res) => {
						if (
							res.code === 0 &&
							['storekeeper', 'ckjy'].includes(res.result.roleKey)
						) {
							_this.modal = false
							_this.$emit('face-check', true)
						} else {
							_this.$Message.info('请联系仓库员扫脸登录！')
							_this.loginTimer = setTimeout(() => {
								_this.tracking = true
							}, 2000)
						}
					})
				}
			})
		},
	},
	mounted() {},
	beforeDestroy() {
		if (this.trackerTask) {
			this.trackerTask.stop()
			this.stopMediaStreamTrack()
		}
	},
}
</script>

<style lang="scss" scoped>
.container2 {
	position: relative;
	width: 100vw;
	height: 80vh;
	min-width: 500px;
	min-height: 400px;
	background-repeat: no-repeat;
	background-size: cover;
	.tabs {
		display: none;
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		justify-content: center;
		background: rgba(5, 10, 30, 0.5);
		.tab {
			padding: 20px 40px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			&.active {
				background: rgba(255, 255, 255, 0.2);
				transition: all 0.5s;
			}
			.label {
				padding: 10px;
				font-size: 18px;
				font-weight: bold;
				color: #ffffff;
			}
		}
	}
	.update-face {
		position: absolute;
		top: 20px;
		left: 20px;
		font-size: 20px;
		font-weight: bold;
		color: #ffffff;
	}
}
.form {
	z-index: 999;
	padding: 0 40px;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 400px;
	border-radius: 10px;
	background: rgba(0, 0, 0, 0.5);
	.title {
		padding: 20px 0;
		font-size: 30px;
		font-weight: bold;
		color: #ffffff;
	}
	.btn {
		padding: 20px 0;
	}
}
.tracking-wrap {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	.border {
		position: absolute;
		top: -60px;
		left: -40px;
		width: 700px;
		height: 580px;
	}
	.tracking {
		position: relative;
		width: 620px;
		height: 460px;
		> * {
			position: absolute;
			left: 0;
			top: 0;
			border-radius: 10px;
		}
		video,
		canvas {
			top: 0;
		}
	}
}
.back {
	position: fixed;
	top: 20px;
	left: 20px;
}
</style>
