<template>
	<div>
		<div v-show="!allPicState">
			<!-- 右 预警-->
			<div style="float:right;width: 528px;box-sizing: border-box;">
				<div style="margin-bottom: 8px; display: flex;justify-content: space-between;">
					<i style="font-size: 18px;font-weight: bold;color: #333;">人脸比中</i>
					<i @click="showAllClick()" style="cursor: pointer;">查看全部
						<i class="el-icon-arrow-right">
						</i>
					</i>
				</div>
				<div style="width: 528px;height: 190px;margin-bottom: 10px;background: #FFF;border-radius:2px; cursor: pointer;"
					v-for="(item,index) in warningList" class="warning-class" @click="openTask(item)">
					<div
						style="height:40px;display:flex;align-items: center; justify-content: space-between;border-bottom: 1px solid #F1F8FF;box-sizing: border-box;">
						<i style="font-weight: bold;color: #333333;margin-left: 20px">{{item.cameraRegion}}</i>
						<i style="font-weight: bold;color: #333333;margin-right: 20px;">{{item.time}}</i>
					</div>
					<div style="display: flex;align-items: center;height: 150px;margin-left: 34px;">
						<div style="width: 120px;height: 120px;background: #F1F6F9;">
							<!--<canvas width=120 height=120 :ref="'warningImage'+index">
							</canvas>-->
							<img style="width: 120px;height: 120px;" :src="item.cphoto" fit="contain"/>
						</div>
						<div
							style="width: 120px;height: 120px;background: #F1F6F9;margin: 0 20px;text-align: center;position: relative;">
							<img style="width: 120px;height: 120px;" :src="item.rphoto" />
							<div
								style="position: absolute;width: 100%;background-color: red;bottom: 0;opacity: 0.6;background: #000;color: #FFF;line-height: 1.8;">
								<i>测试库</i>
							</div>
						</div>
						<div style="width: 194px;height: 120px;position: relative;">
							<div
								style="display: flex;flex-direction: column;justify-content: space-around;height: 120px;">
								<span><iv
							style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgr			style="width: 120px;height: 120px;backgritem.name}}</i></span>
								<span><i>性别：未知</i></span>
								<span><i>来源：测试库</i></span>
								<span><i>相似度：</i><i
										style="font-size: 30px;font-weight: 600;color: #FF343E;	font-family:Bahnschrift;">{{item.xsd }}</i></span>
							</div>
							<div style="position: absolute;top:0;right: 0;">
								<img v-if="item.taskType=='3'" src="../../../assets/img/warning/ts.png" alt="提示">
								<img v-if="item.taskType=='2'" src="../../../assets/img/warning/jk.png" alt="监控">
								<img v-if="item.taskType=='1'" src="../../../assets/img/warning/zb.png" alt="抓捕">
							</div>
						</div>
					</div>
				</div>
				<!-- 子组件 任务详情 -->
				<task v-if="taskVisible" ref="task" @refreshTaskList></task>
			</div>
			<!-- 左 抓拍-->
			<div style="margin-right:548px;">
				<!-- 条件 -->
				<div style=";margin-bottom: 8px;">
					<i style="font-size: 18px;font-weight: bold;color: #333;">卡口切换</i>
					<span class="el-icon-caret-right" style="font-size: 18px;cursor: pointer;"
						@click.stop="barrierSelectStateClick()" v-show="!barrierState"></span>
					<span class="el-icon-caret-bottom" style="font-size: 18px;cursor: pointer;"
						@click.stop="barrierSelectStateClick" v-show="barrierState"></span>
					<i style="font-size: 18px;margin-left: 30px;">{{barrierName}}</i>
					<i style="font-size: 18px;float:right">布控任务:{{taskName}}</i>
				</div>
				<!-- 卡口树 -->
				<div style="width: 305px;height: 600px;position: absolute;background-color: #FFF;z-index:1"
					v-show="barrierState">
					<div class="tree-div"
						style="width: 300px;height: 600px;position: absolute;background-color: #FFF;overflow-y: scroll;"
						v-clickoutside="handleClose">
						<el-tree v-model="treeArr" :data="treeList" :props="defaultProps" @node-click="handleNodeClick"
							:default-expand-all="true" style="margin-top: 20px;">
							<span slot-scope="{ node, data }"
								:style="{color: barrierName==node.label ? '#409EFF' : 'inherit' }">
								<i class="el-icon-map-location" v-if="data.type=='region'"></i>
								<span v-else>
									<i class="el-icon-video-camera" v-if="data.status==='N'" style="color:#CCC"></i>
									<i class="el-icon-video-camera" v-else></i>
								</span>
								<del v-if="data.status==='N'" style="padding-left: 4px;color:#CCC">{{node.label}}</del>
								<span v-else style="padding-left: 4px;">{{node.label}}</span>
							</span>
						</el-tree>
					</div>
				</div>
				<!-- 背景图 -->
				<!-- fits: ['fill', 'contain', 'cover', 'none', 'scale-down'], -->
				<div style="width: 100%;display: flex;justify-content: center;background-color: #333;height:600px;">
					<el-image style="width: 100%;" :src="require('./test.png')" :preview-src-list="[require('./test.png')]"fit="contain">
						<div slot="error" class="image-slot" style="text-align: center;margin-top:270px ;">
							<i style="color: #666;font-size: 60px;" class="el-icon-picture-outline"></i>
						</div>
					</el-image>

				</div>
				<!-- 抓拍图片详情 -->
				<div style="display: flex;justify-content: space-between;margin: 10px 0 8px 0;">
					<span>
						<i style="color:#333;font-size: 14px;font-weight:bold ;">今日抓拍</i>
						<i
							style="color:#333;font-size: 18px;font-weight:bold;margin-left: 5px;font-family:Bahnschrift">{{toDaySnapShot}}</i>
						<i style="color:#333;font-size: 14px;font-weight:bold ;">/累计抓拍 </i>
						<i
							style="color:#333;font-size: 18px;font-weight:bold;margin-left: 5px;font-family:Bahnschrift">{{totalSnapShot}}</i>
					</span>
					<i style="font-size: 14px;font-weight: 400;cursor: pointer;" @click="showAllPicClick()">查看全部
						<span class="el-icon-arrow-right">
						</span>
					</i>
				</div>
				<!-- 抓拍图片 -->
				<div class="pic-div">
					<div style="display: flex;align-items: center;">
						<template v-for="(item,i) in warningList">
							<img width=120 height=120 style="margin-left: 12px;" :src="item.cphoto">
						</template>
					</div>
				</div>
				<!-- 声音提醒 -->
				<audio ref="notice">
					<source src="../../../assets/mp3/warning1.mp3" type="audio/mpeg">
					<!-- 文字转语音，需要外网支持 -->
					<!-- <source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&per=1&text=你有新的短消息了" type="audio/mpeg"> -->
				</audio>
			</div>
		</div>
		<div v-show="allPicState">
			<!-- 子组件 全部图片 -->
			<barrier-all-pic ref="allPicRef" @returnAllPicState="returnAllPicState"></barrier-all-pic>
		</div>
	</div>
</template>

<script>
	const clickoutside = {
		// 初始化指令
		bind(el, binding, vnode) {
			function documentHandler(e) {
				// 这里判断点击的元素是否是本身，是本身，则返回
				if (el.contains(e.target)) {
					return false;
				}
				// 判断指令中是否绑定了函数
				if (binding.expression) {
					// 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
					binding.value(e);
				}
			}
			// 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
			el.vueClickOutside = documentHandler;
			document.addEventListener('click', documentHandler);
		},
		update() {},
		unbind(el, binding) {
			// 解除事件监听
			document.removeEventListener('click', el.vueClickOutside);
			delete el.vueClickOutside;
		},
	};
	import Cookies from 'js-cookie'
	import 'element-ui/lib/theme-chalk/display.css';
	import Task from './barrier-task'
	import barrierAllPic from './barrier-all-pic'
	export default {
		directives: {
			clickoutside
		},
		components: {
			Task,
			barrierAllPic
		},
		data() {
			return {
				// 卡口下拉状态的隐藏显示
				barrierState: false,
				// 卡口名字
				barrierName: "",
				// 任务名字
				taskName: "",
				cameraId: "",
				// 任务弹窗状态
				taskVisible: false,
				// 是否显示全部图片
				allPicState: false,
				treeList: [],
				// 选中的树的层级结构
				treeArr: [],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// 图片信息
				faceBgUrl: "",
				faces: [],
				currentFaces: [],
				toDaySnapShot: 0,
				totalSnapShot: 0,
				// 预警列表
				warningList: [],
				// 预警音乐类型
				warningType: "",
			}
		},
		mounted() {
			//this.timer = setInterval(this.get, 1000);
		},
		beforeDestroy() {},
		created() {
			// 初始化选择默认卡口
			this.initGetCameraId()
			// 初始化获取4条预警信息
			this.initGetWarningPicture()
		},

		methods: {
			get(){
				this.$http.get("/faces/list").then(res => {
					this.warningList  = res.data;
				})
			},
			// 初始化4条预警数据
			initGetWarningPicture() {
				this.$http.post("/warning/alarm", {
					"page": {
						"pageNo": 1,
						"pageSize": 4,
					},
				}).then(res => {
					if (res.data.code === 0) {
						this.warningList = res.data.data.records
						// 处理预警数据
						this.getWarningPicture(this.warningList)
					} else {
						this.$message.error(res.data.message)
					}
				})
			},
			/**
			 * 初始化获取摄像头id
			 */
			initGetCameraId() {
				this.$http.get("/warning/bayonet").then((res) => {
					if (res.data.code === 0) {
						this.cameraId = res.data.data.cameraId
						this.barrierName = res.data.data.cameraName
						// 卡口树状结构多级id
						this.treeArr = res.data.data.camera_region_firstlevel.split(",")
						// 初始化根据摄像头id获取任务名称
						this.getTaskNameByCameraId(this.cameraId)
						// 初始化获取 今日抓拍/累计抓拍
						this.initTotal(this.cameraId)
						// 启动webSocket----------启动webSocket----------启动webSocket----------启动webSocket
						this.initWebSocket()
					} else {
						this.$message.error(res.data.message)
					}
				})
				this.initWebSocket()
			},
			/**
			 * @param {String} cameraId
			 * 根据任务Id获取任务名
			 */
			getTaskNameByCameraId(cameraId) {
				this.$http.get(`warning/taskInfo/${cameraId}`).then(res => {
					if (res.data.code === 0) {
						this.taskName = res.data.data.taskName
					} else {
						this.$message.warning(res.data.message)
					}
				})
			},
			// 初始化获取 今日抓拍/累计抓拍
			initTotal(cameraId) {
				this.$http.get(`/warning/todayBayonet/${this.cameraId}`).then(res => {
					if (res.data.code === 0) {
						// 初始化toDaySnapShot 和 totalSnapShot两个字段与ws推送的这两个字段的json结构不一样（来自潘辉）
						res.data.data.result.toDaySnapShot = res.data.data.toDaySnapShot
						res.data.data.result.totalSnapShot = res.data.data.totalSnapShot
						this.getPicture(res.data.data.result)
					} else {
						this.$message.error(res.data.message)
					}
				})
			},
			// WebSocket
			initWebSocket() {
				console.log("启动WebSocket")
				const token = Cookies.get('token')
				// let url = window.SITE_CONFIG['apiURL']
				// let IP = url.split("//")[1].split(":")[0]
				// const wsuri = `ws://${IP}:1993/task/webSocket/${token}`
				const wsuri = `${window.GLOBAL_CONFIG.SOCKET_URL}`
				console.log(wsuri)
				this.websock = new WebSocket(wsuri);
				this.websock.onopen = this.websocketonopen;
				this.websock.onerror = this.websocketonerror;
				this.websock.onclose = this.websocketclose;
				this.websock.onmessage = this.websocketonmessage;
			},
			websocketonopen(e) {
				console.log("WebSocket Connection successful");
				let obj = {
					"code": 200,
					"message": "成功",
					"cmd": "BAYONET",
					"data": {
						"carmeraId": this.cameraId
					}
				}
				let objString = JSON.stringify(obj)
				// 此处有效参数只有 this.cameraId，但是后台执意这样传递参数（来自潘辉）
				this.websock.send(objString)
			},
			websocketonerror(e) {
				console.log("WebSocket Connection error");
			},
			websocketclose(e) {
				console.log("WebSocket Connection closed");
			},
			websocketonmessage(e) {
				// ws数据字符串转json
				let wsObj = JSON.parse(e.data)
				// ws数据推送成功
				if (wsObj.code === 200) {
					// wsObj.cmd === "BAYONET" 人脸抓拍图片
					if (wsObj.cmd === "BAYONET") {
						this.getPicture(wsObj.data)
					}
					// wsObj.cmd === "WARNING" 预警信息
					else {
						// 处理ws推送的预警信息
						this.getWarningPicture(wsObj.data)
					}
				} else if (wsObj.code === 401) {
					this.$router.replace({
						name: 'login'
					})
				} else {
					this.$message.error(wsObj.message)
					this
				}
			},
			// 抓拍的图片处理
			getPicture(obj) {
				this.toDaySnapShot = obj.toDaySnapShot
				this.totalSnapShot = obj.totalSnapShot
				this.faceBgUrl = obj.faceBgUrl
				this.faces = obj.faces.map(item => {
					item.faceBgUrl = obj.faceBgUrl
					return item
				})
				this.currentFaces = this.faces.concat(this.currentFaces)
				// 今日抓拍最多显示50张
				if (this.currentFaces.length > 50) {
					this.currentFaces = this.currentFaces.slice(0, 50)
				}
				this.currentFaces.forEach((item, index, arr) => {
					this.$nextTick(() => {
						let canvas = this.$refs[`image${index}`][0]
						let cxt = canvas.getContext("2d");
						cxt.clearRect(0, 0, 120, 120);
						let img = new Image();
						img.src = item.faceBgUrl;
						img.onload = function() {
							// cxt.drawImage(img, item.faceRect.x, item.faceRect.y, item.faceRect.w, item.faceRect.h, 0, 0, item.faceRect.w,item.faceRect.h);
							cxt.drawImage(img, item.faceRect.x, item.faceRect.y, item.faceRect.w, item
								.faceRect.h, 0, 0, 120,
								120);
						}
					})
				})
			},
			/**
			 * 预警数据处理
			 * @param {Object} wsObj
			 */
			getWarningPicture(warningData) {
				// warningData为数组说明是初始化数据，为对象说明是ws推送的数据
				if (!Array.isArray(warningData)) {
					if (this.warningList.length === 4) {
						this.warningList.pop()
						this.warningList.unshift(warningData)
					} else {
						this.warningList.unshift(warningData)
					}
					// 声音 和 tips预警
					let warningType = this.$refs.notice
					warningType.play()
					this.$message.warning("有新的预警信息")
				}
				this.warningList.forEach((item, index, arr) => {
					// "1" 红色#FF343E "2" 橙色#FFA61A  "0" 蓝色#2FC8FA
					// if (item.taskType == "1" || item.taskType == "2" || item.taskType == "3") {
					// 	if (item.taskType == "1") {
					// 		item.taskType = "#FF343E"
					// 	} else if (item.taskType == "2") {
					// 		item.taskType = "#FFA61A"
					// 	} else if (item.taskType == "3") {
					// 		item.taskType = "#2FC8FA"
					// 	} else {
					// 		item.taskType = "#CCC"
					// 	}
					// }
					this.$nextTick(() => {
						if (this.$refs[`warningImage${index}`].length != 0) {
							let canvas = this.$refs[`warningImage${index}`][0]
							let cxt = canvas.getContext("2d");
							cxt.clearRect(0, 0, 120, 120);
							let img = new Image();
							img.src = item.bgImg;
							img.onload = function() {
								cxt.drawImage(img, item.positionVO.x, item.positionVO.y, item
									.positionVO.w, item.positionVO.h, 0, 0,
									120,
									120);
							}
						}
					})
				})
			},
			// 卡口树隐藏显示
			barrierSelectStateClick() {
				this.barrierState = !this.barrierState
				if (this.barrierState && this.treeList.length == 0) {
					this.$http.get("/camera/getBayonet").then(res => {
						if (res.data.code === 0) {
							this.treeList = res.data.data
						} else if (res.data.code === 60001) {
							this.$message.warning(res.data.message)
						} else {
							console.log(res)
						}
					})
				}
			},
			// 级联事件切换摄像头
			handleNodeClick(data, a, b) {
				console.log(data)
				if (data.type == "camera" && data.status === "Y") {
					// 切换摄像头清空上一个摄像头的今日抓拍
					this.currentFaces = []
					// 摄像头名字用于展示
					this.barrierName = data.label
					this.cameraId = data.id
					// 三级卡口id用于点击查看全部后绑定区域级联下拉框
					this.treeArr = data.camera_region_firstlevel.split(",")
					// 获取任务名称
					this.getTaskNameByCameraId(this.cameraId)
					// 切换摄像头时默认查询一条数据展示
					this.initTotal(this.cameraId)
					// ws 关闭再打开是为了调用send()方法传递摄像头id
					this.websocketclose()
					this.websocketonopen()
				}
			},
			// 打开预警任务
			openTask(param) {
				this.taskVisible = true
				this.$nextTick(() => {
					this.$refs.task.init(JSON.stringify(param))
				})
			},
			// 查看所有图片
			showAllPicClick() {
				this.allPicState = true
				this.$nextTick(() => {
					this.$refs.allPicRef.init(this.cameraId, this.treeArr)
				})
			},
			// 返回主页面
			returnAllPicState(param) {
				this.allPicState = false
			},
			// 跳转预警页面
			showAllClick() {
				// 路由传递参数
				this.$router.push({
					name: "monitoring-warning",
					params: {
						taskId: ''
					},
				})
			},
			// 自定义指令事件
			handleClose() {
				this.barrierState = false
			},
		},
	}
</script>

<style scoped>
	i {
		font-style: normal;
		font-family: "Noto Sans SC";
	}

	/*滚动条滑块*/
	.tree-div::-webkit-scrollbar-thumb {
		border-radius: 10px;
		-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
		background-color: rgba(144, 147, 153, .3);
	}

	/*滚动条轨道*/
	.tree-div::-webkit-scrollbar-track {
		-webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0);
		border-radius: 10px;
		background: #FFF;
	}

	.tree-div::-webkit-scrollbar {
		height: 1px;
		width: 8px;
	}

	.pic-div {
		width: 100%;
		padding: 12px 0;
		border-radius: 4px;
		background: #FFF;
		overflow: scroll;
		height: 152px
	}

	/*滚动条滑块*/
	.pic-div::-webkit-scrollbar-thumb {
		border-radius: 10px;
		-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
		background-color: rgba(144, 147, 153, .3);
	}

	/*滚动条轨道*/
	.pic-div::-webkit-scrollbar-track {
		-webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0);
		border-radius: 10px;
		background: #FFF;
	}

	.pic-div::-webkit-scrollbar {
		height: 8px;
		width: 1px;
	}

	.warning-class:nth-child(5) {
		margin-bottom: 0 !important;
	}
</style>
