<template>
	<div class="warning-map">
		<el-dialog :visible.sync="visible" center width="86%" :modal-append-to-body="false" :close-on-click-modal="false" top="0vh"
		 :close-on-press-escape="true" :fullscreen="true">
			<span slot="title"><i class="font-sexteen">预警地图模式</i></span>
			<div>
				<baidu-map class="bm-view" :center="center" :zoom="zoom" @ready="handler" :scroll-wheel-zoom="true" @click="getClickInfo"
				 @moving="syncCenterAndZoom" @moveend="syncCenterAndZoom" @zoomend="syncCenterAndZoom">
					<bm-view style="width: 100%; height:880px;"></bm-view>
					<div v-for="(item,index) in warningList" :key=index>
						<!-- :animation="item.cameraId == cameraId ?  'BMAP_ANIMATION_BOUNCE' : 'BMAP_ANIMATION_DROP'" -->
						<bm-marker :position="{lng: item.lng, lat: item.lat}" :dragging="false" @click="infoWindowOpen(item)" :animation="item.cameraId == cameraId ?  'BMAP_ANIMATION_BOUNCE' : 'BMAP_ANIMATION_DROP'">
							<!-- v-if="item.cameraId" 摄像头被布控，但是没有被预警 -->
							<bm-label v-if="item.cameraId" :labelStyle="{fontFamily: 'Noto Sans SC',fontStyle: 'normal',color: '#333', fontSize : '14px'}"
							 :offset="{width: -90, height: -180}" :content="mapHtml(item,index)" />
							<!-- <bm-label v-if="item.cameraId" :labelStyle="{color: '#fff', fontSize : '14px'}" :offset="{width: -90, height: -170}"
							 :content="'<div style=background:#FF343E;border-radius:6px;height:160px;width:190px;padding-top:10px;><div style=height:80px;width:190px;display:flex;><div style=height:80px;width:80px;background:#F1F6F9;margin-left:10px;><canvas width=80 height=80 id=warningImage' + index + '></canvas></div><div style=background:#F1F6F9;width:80px;height:80px;margin-left:10px><img style=height:80px;width:80px;object-fit:contain; src=' + item.faceUrl +'></div></div><div style=width:190px;margin-top:10px;padding-left:10px;><div>相似度：' + item.score + '</div><div>姓名：' + item.name + '</div><div>时间：' + item.time + '</div></div></div>'" /> -->
							<!-- <bm-info-window :show="item.infoWindowShowFlag" @close="infoWindowClose(item)" style="text-align: center;">
								<h1>{{item.cameraRegion}}</h1>
								<img :src="item.bgImg" style="width:100%" />
							</bm-info-window> -->
						</bm-marker>
					</div>
				</baidu-map>
			</div>
			<!-- <span slot="footer">
				<el-button @click="cancelClick">取消</el-button>
			</span> -->
		</el-dialog>
	</div>
</template>

<script>
	import Cookies from 'js-cookie'
	export default {
		data() {
			return {
				visible: false,
				warningList: [],
				// 定义经维度和zoom
				center: {
					lng: 0,
					lat: 0
				},
				zoom: 3,
				bmLabelState: false,
				// ws推送的cameraId
				cameraId: "",
				zbUrl: require("../../../assets/img/warning/zb.png"),
				jkUrl: require("../../../assets/img/warning/jk.png"),
				tsUrl: require("../../../assets/img/warning/ts.png"),
				// 点击 marker 展开关闭
				displayCss: "block",
			}
		},
		computed: {
			mapHtml() {
				return function(item, index) {
					let bgState = ""
					let url = ""
					if (item.taskType === "1") {
						bgState = "#FF343E"
						url = this.zbUrl
					} else if (item.taskType === "2") {
						bgState = "#FFA61A"
						url = this.jkUrl
					} else if (item.taskType === "3") {
						bgState = "##2FC8FA"
						url = this.tsUrl
					} else {
						bgState = "#CCC"
					}
					return `<div style="background:#FFF;border-radius:6px;height:170px;width:190px;padding-top:10px;position:relative;display:${item.displayCss}">
								<div style="height:80px;width:190px;display:flex;">
									<div style="height:80px;width:80px;background:#F1F6F9;margin-left:10px;">
										<canvas width=80 height=80 id="warningImage${index}"></canvas>
									</div>
									<div style="background:#F1F6F9;width:80px;height:80px;margin-left:10px">
										<img style="height:80px;width:80px;object-fit:contain;" src="${item.faceUrl}">
									</div>
								</div>
								<div style="width:190px;margin-top:10px;padding-left:10px;">
									<div>相似度：<span style="font-size: 18px;font-weight: 600;color: #FF343E;font-family:Bahnschrift;">${item.score}</span></div>
									<div>名字：${item.name}</div>
									<div>时间：${item.time}</div>
								</div>
								<div style="position:absolute;top:50%;left:50%;margin-left:-25px;margin-top:-50px";>
									<img src="${url}" alt="抓捕">
								</div>
							</div>`
				}
			}
		},
		methods: {
			init() {
				this.visible = true
				// 初始化地图预警信息
				this.$http.get("/warning/getCameraWarningByTask").then(res => {
					if (res.data.code === 0) {
						let cameraArr = res.data.data
						cameraArr.forEach((item, index, arr) => {
							item.warning.lng = item.camera.cameraLongitude
							item.warning.lat = item.camera.cameraLatitude
							item.warning.infoWindowShowFlag = false
							item.warning.score = (item.warning.score * 100).toFixed(2) + "%"
							// bm-label 默认全部展示 display:block
							item.warning.displayCss = this.displayCss
							this.warningList.push(item.warning)
						})
						// 启动ws
						this.initWebSocket()
						// 画图
						this.commonCanvas()
					} else {
						this.$message.error(res.data.message)
					}
				})
			},
			// WebSocket
			initWebSocket() {
				const token = Cookies.get('token')
				// let url = window.SITE_CONFIG['apiURL']
				// let IP = url.split("//")[1].split(":")[0]
				const wsuri = `${window.GLOBAL_CONFIG.SOCKET_URL}/${token}`
				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");
			},
			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 === "WARNING") {
					let arr = []
					this.warningList.forEach(item => {
						if (wsObj.data.cameraId === item.cameraId) {
							wsObj.data.score = (wsObj.data.score * 100).toFixed(2) + "%"
							this.cameraId = wsObj.data.cameraId
							wsObj.data.displayCss = this.displayCss
							arr.push(wsObj.data)
							// 直接 item = wsObj.data 不行（需弄清原因）
						} else {
							arr.push(item)
						}
					})
					this.warningList = arr
					this.commonCanvas()
				} else {
					this.$message.error(wsObj.message)
				}
			},
			// 公共canvas
			commonCanvas() {
				this.warningList.forEach((item, index, arr) => {
					// 当摄像头有过预警信息才做处理
					if (item.cameraId) {
						this.$nextTick(() => {
							let canvas = document.getElementById(`warningImage${index}`)
							let cxt = canvas.getContext("2d");
							cxt.clearRect(0, 0, 80, 80);
							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,
									80,
									80);
							}
						})
					}
				})
			},
			cancelClick() {
				this.visible = false
			},
			// ready
			handler({
				Bmap,
				map
			}) {
				this.center.lng = 103.907065
				this.center.lat = 30.701563
				this.zoom = 18
			},
			/***
			 * 地图点击事件。
			 */
			getClickInfo(e) {
				this.center.lng = e.point.lng
				this.center.lat = e.point.lat
			},
			// 覆盖物 点 信息窗体 关闭 --------- bm-info-window  暂时不用
			// infoWindowClose(param) {
			// 	this.warningList.forEach((item, index, arr) => {
			// 		if (param.cameraId === item.cameraId) {
			// 			arr[index].infoWindowShowFlag = false
			// 		}
			// 	})
			// },
			// 覆盖物 点 信息窗体 打开 
			infoWindowOpen(param) {
				// bm-info-window  暂时不用
				// console.log(param)
				// this.warningList.forEach((item, index, arr) => {
				// 	if (param.cameraId === item.cameraId) {
				// 		arr[index].infoWindowShowFlag = true
				// 		arr[index].bgImg = param.bgImg
				// 	}
				// })
				console.log(this.warningList)
				let arr = []
				this.warningList.forEach(item => {
					if (item.cameraId == param.cameraId) {
						if (item.displayCss == "block") {
							item.displayCss = "none"
						} else {
							item.displayCss = "block"
						}
					}
					arr.push(item)
				})
				this.warningList = arr
				console.log(this.warningList)
				this.warningList.forEach((item, index, arr) => {
					// 当摄像头有过预警信息才做处理
					if (item.cameraId) {
						console.log(index)
						this.$nextTick(() => {
							let canvas = document.getElementById(`warningImage${index}`)
							let cxt = canvas.getContext("2d");
							cxt.clearRect(0, 0, 80, 80);
							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,
									80,
									80);
							}
						})
					}
				})
			},
			//  @moving @moveend @zoomend> 暂时不用
			syncCenterAndZoom(e) {
				const {
					lng,
					lat
				} = e.target.getCenter()
				this.center.lng = lng
				this.center.lat = lat
				this.zoom = e.target.getZoom()
				if (this.zoom < 14) {
					let BMapLabelDom = document.getElementsByClassName("BMapLabel")
					for (var i = 0; i < BMapLabelDom.length; i++) {
						BMapLabelDom[i].style.display = "none"
					}
				} else {
					let BMapLabelDom = document.getElementsByClassName("BMapLabel")
					for (var i = 0; i < BMapLabelDom.length; i++) {
						BMapLabelDom[i].style.display = "block"
					}
				}
			},
		}
	}
</script>

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

	.font-sexteen {
		font-size: 16px;
		font-weight: bold;
	}

	.warning-map>>>.BMapLabel {
		border: none !important;
		box-shadow: 10px 10px 5px rgb(0, 0, 0, 0.05);
		border-radius: 6px
	}


	/* 
	去除百度地图版权
	去除右上角[地图、卫星、三维]控件
	去除百度地图右上角平移缩放控件的市县区文字
	 */
	.warning-map>>>.anchorBL,
	.warning-map>>>.anchorTR,
	.warning-map>>>.BMap_zlHolder {
		display: none;
		visibility: hidden;
	}


	.warning-map>>>.el-dialog__body {
		padding: 0;
	}
</style>
