<template>
	<div class="screen-main">
		<!--头部展示-->
		<div class="screen-header">
			<div class="timeWrap"> 
				<el-date-picker
                  v-model="form.startTime"
                  type="datetime"
				  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择开始时间"
                  :default-time="defaultStartTime"
                />
				<el-date-picker
					v-model="form.endTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
                  	format="YYYY-MM-DD HH:mm:ss"
					placeholder="选择结束时间"
					:default-time="defaultEndTime"
				/>
				<el-button class="searchBtn" @click="trackSearch">查询</el-button>
				<el-button class="searchBtn" @click="userLineTrackCancel">取消跟踪</el-button>
			</div>
			<div class="header-right-action">
				<div class="right-action-clock">
					<span class="action-time">{{ currentDay }}</span>
					<span class="action-time">{{ currentWeek }} </span>
					<span class="action-time">{{ currentTime }}</span>
				</div>
			</div>
		</div>
		<!--地图-->
		<div id='mapContainer'></div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			mac:null,
			type:null,
			name:'',
			line1:null,
			timeNow:'',
			currentDay: '',
			currentTime: '',
			currentWeek: '',
			todayDate:'',
			timerTime:null,
			userMarker:null,
			userMaskerLayer:null,
			defaultStartTime:new Date(2000, 1, 1, 8, 0, 0),
			defaultEndTime:new Date(2000, 1, 1, 11, 0, 0),
			form:{
				endTime:'',
				startTime:''
			}
		}
	},
	mounted() {
		let that = this;
		that.item = JSON.parse(localStorage.getItem('trackItem')) 
		console.log(that.item)
		let date = new Date();
		that.timeNow = date.getDay();
		that.todayDate = that.$TOOL.dateFormat(new Date(), 'yyyy-MM-dd');
		that.showTime();
		that.timerTime = setInterval(() => {
			that.showTime();
		}, 1000);
		let host = window.location.host;
		let jsUrl = '/jsmap/jsmap.js';
		that.loadScript('mapId',jsUrl, () => {
			window.map = new jsmap.JSMap({
				mapType: jsmap.JSMapType.MAP_3D,
				container: 'mapContainer',
				mapServerURL: 'data/map',
				enableShadows: false, //是否开启阴影 默认false
				enableLighting: false, //是否开发光照 默认false
				showBuildingMarker: true,
				// showNavigationDisplay: true,
				mapScaleLevelRange: [16, 23],//比例尺级别范围， 16级到23级,默认[1,24]
				floorControlOptions: {
					floorHeight: 20,//楼层间距
					position: jsmap.JSControlPosition.RIGHT_TOP,//控件位置
					offset: {
						x: 10,
						y: 200,
					}//控件偏移位置
				},
				imageryProvider: jsmap.JSImageryProviderType.IMAGE_TDT,
				backgroundColor: '#3798ff',  //背景颜色
				viewOptions: {
					//屏幕中心坐标
					center: { x: 114.63059258861512, y: 38.81407163905287, z: 1 },
					// center: {x:120,y:30,z:10},
					//相机距屏幕中心点距离（单位m）
					distance: 550,
					// 旋转角（单位°）
					rotate: 0,
					//倾斜角（单位°）
					tilt: 45,
				}
			});
			window.map.openMapById('0000');
			window.map.on('loadComplete', e => {
				let compassControl = new jsmap.JSCompassControl({
					position: jsmap.JSControlPosition.LEFT_TOP,
					offset: {
						x: 20,
						y: 50
					}
				});
				window.map.addControl(compassControl);
				let zoomControl = new jsmap.JSZoomControl({
					position: jsmap.JSControlPosition.LEFT_TOP,
					offset: {
						x: 50,
						y: 5
					}
				});
				window.map.addControl(zoomControl);
				that.userMaskerLayers();
			});
		})
	},
	beforeUnmount(){
		window.map.destroy();
		window.map = null;
	},
	methods: {
		loadScript(id, url, callback) {
			debugger;
			let that = this;
			//如果已经存在这个id，则证明已经加载过，已经有这个js文件了，可以直接执行回调里面的操作
			if (document.querySelector(`#${id}`)) {
				that.ElLoading = null;
				callback && callback();
				return;
			}else{
				that.ElLoading = this.$loading({
				lock: true,
				text: '地图资源加载中...',
				background: 'rgba(0, 0, 0, 0)',
			})
			}
			//第一次加载，先创建 script 标签
			const script = document.createElement('script');
			script.src = url;
			//创建id属性
			script.setAttribute('id', id);
			//获取第一个script标签
			const firstScript = document.getElementsByTagName('script')[0];
			//获取第一个script标签的父节点 BODY,在body的第一个script引用之前插入，即把这个动态的js文件放在第一个调用
			firstScript.parentNode.insertBefore(script, firstScript);
			//script 一加载就执行
			script.onload = script.onreadystatechange = function() {
				that.ElLoading.close();
				// 加载完成
				if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
					callback && callback()
				}
			};
		},
		//显示右上角的时间
		showTime() {
			this.currentTime = this.$TOOL.dateFormat(new Date(), 'hh:mm:ss');
			this.currentWeek = this.$TOOL.dateFormat(new Date(), 'week');
			this.currentDay = this.$TOOL.dateFormat(new Date(), 'yyyy年MM月dd日')
		},
		//获取人员详细信息
		showUserDetail() {
			this.$API.hrm.employee.item.req(this.screenUserItem.id).then(res => {
				this.screenUserItemDetail = res;
			})
		},

		//员工标记layer
		userMaskerLayers() {//图标文字
			let that = this;
			// that.userMaskerLayer = new jsmap.JSIconTextMarkerLayer({
			// 	minimumLevel: 3,
			// 	maxmumLevel: 22,
			// 	show: false
			// });
			// window.map.addLayer(that.userMaskerLayer);
			let endTime = new Date().getTime();
			let startTime = endTime-60*60 * 1000;
			that.userLineTrack(startTime,endTime);
		},
		//人员轨迹
		userLineTrack(startTime,endTime){
			let that = this;
			let params = {
				url:"/api/datacenter/user/historypathV2",
				method:"post",
				json:{
					mac: that.item.mac,
					startTime: startTime,
					endTime: endTime,
					locationType: "real"
				}
			};
			let points0 = [];
			that.$API.third.blt.xunxiCommon.req(params).then(res => {
				if (res.err_msg) { } else {
					let points = [];
					res.forEach(item=>{
						item.points.forEach(poi=>{
							points.push(poi)
						})
					})
					points.forEach(item=>{
						let obj=new Object();
						obj.x=item.longitude;
						obj.y=item.latitude;
						obj.z=item.z;
						points0.push(obj); 
					});
					if(points0.length>0){
						that.line1 = null;
					if (that.line1==null) {
						that.line1 = new jsmap.JSLineMarker({
							position: points0,
							floorId: 1,
							lineType: jsmap.JSLineType.ARROW,
							color: '#0000ff',
							width: 10,
							depthTest: true
						});
						window.map.addMarker(that.line1);
					}
					let trackItem = that.item;
					//标记图片
					let userImage = '';
					if (trackItem.type === 'employee') {
						userImage = "/img/employee.png"
					}else if (trackItem.type === 'driver') {
						userImage = "/img/driver.png"
					}  else if (trackItem.type === 'remployee') {
						userImage = "/img/driver.png"
					}else {
						userImage = "/img/visitor.png"
					}
					that.trackMarker = new jsmap.JSIconTextMarker({
						id: '1',
						position: points0[0],
						image: userImage,
						rotation: {
							rx: 0,
							ry: 0,
							rz: -90
						},
						text: trackItem.name,
						fontColor: '#0000ff',
						font: '14px 微软雅黑',
						backgroundColor: 'rgba(112,253,147,0.5)',
						backgroundRadius: 5,
						textOffsetInMeter: 1.6,
						backgroundStrokeColor: 'rgb(255,255,255)',
						modelAnimate: {
							multiplier: 2,
						},
						scale: 1,
						properties: {
							name: 'trackMarker'
						},
						callback: (marker) => {
							window.map.trackMarker(marker, {
							range: 100,
							tilt: 60,
							rotate: 310
							});
							for (let i = 1; i < points0.length; i++) {
								setTimeout(() => {
									window.map.updateMarkerPosition(marker, {
										position: points0[i],
										animate: {
											duration: 1000,
											update: (pos) => {
												that.line1.trace(pos)
											}
										}
									});
								}, i * 1000);
							}
						}
					});
					window.map.addMarker(that.trackMarker);
					}else{
						that.$message.error('暂无运动痕迹');
					}
				}
			})
		},
		trackSearch(){
			let that = this;
			window.map.cancelTrack();
			window.map.removeMarker(that.trackMarker);
			window.map.removeAllIconTextMarker();
			window.map.removeMarker(that.line1);
			window.map.removeAllLineMarker();
			let startTime = new Date(this.form.startTime).getTime();
			let endTime = new Date(this.form.endTime).getTime();
			this.userLineTrack(startTime,endTime);
		},
		userLineTrackClear(){
			let that = this;
			window.map.cancelTrack();
			window.map.removeMarker(that.trackMarker);
			window.map.removeAllPointMarker();
			window.map.removeMarker(that.line1);
			window.map.removeAllLineMarker();
			that.trackMarker = null;
			that.line1 = null;
		},
		userLineTrackCancel(){
			this.$router.push({
				name: "bigScreen"
			});
		},
		
	},
	unmounted() {
		// window.map.destroy();
		window.map = null;
	},
}
</script>

<style lang="scss">
.screen-main {
	width: 100%;
	height: 100%;
	.screen-header {
		width: 100% !important;
		height: 84px !important;
		position: absolute !important;
		left: 0 !important;
		top: 0 !important;
		background: linear-gradient(0deg, rgba(0, 113, 155, 0) 0, #00455f) !important;
		z-index: 2 !important;
		transition: all .5s linear !important;
		.timeWrap{
			width: 100% !important;
			// position: absolute !important;
			// top: 84px !important;
			z-index: 2 !important;
			display: flex;
			align-items: self-end;
			.searchBtn{
				background-color: aquamarine;
			}
		}
		.header-left-bg {
			height: 60px;
			position: absolute;
			left: 18px;
			top: 12px;
			font-size: 40px;
			font-weight: 700;
			color: #fff;
		}

		.header-right-action {
			position: absolute;
			top: 10px;
			right: 18px;
			display: flex;
			align-items: center;

			.right-action-clock {
				:before {
					content: " ";
					display: inline;
					position: absolute;
					left: -24px;
					top: 9px;
					width: 16px;
					height: 16px;
					/*background: url(/img/screen5/clock.png) no-repeat;*/
					background-size: 100% 100%;
				}

				.action-time {
					width: 56px;
					height: 19px;
					font-size: 14px;
					font-weight: 400;
					color: #fff;
					position: relative;
					margin-right: 20px;
				}
			}

		}
	}
	
}
#mapContainer {
	width: 100%;
	height: 100%;
	background-color: #49a1ff;
}

[class*=" el-icon-"],
[class^=el-icon-] {
	font-family: element-icons !important;
	speak: none;
	font-style: normal;
	font-weight: 400;
	font-variant: normal;
	text-transform: none;
	line-height: 1;
	vertical-align: baseline;
	display: inline-block;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}




</style>
