<template>
	<view class="order-tracks" @mouseup="onTouchend">
		<!-- #ifndef MP -->
		<map id="myMap" style="width: 100vw;height: 100vh;" />
		<!-- #endif -->

		<!-- #ifdef MP -->
		<map id="myMap" style="width: 100vw;height: 100vh;" :polyline="polylines" :markers="markers" :include-points="includePoints" :enable-zoom="true">
			<cover-view slot="callout" v-if="shipmentStopShowNumber">
				<block v-for="(item,index) in markers" :key="index">
					<cover-view class="customCallout shipment-stop-marker" :marker-id="item.id"> {{item.stopNumber}} </cover-view>
				</block>
			</cover-view>
		</map>
		<!-- #endif -->

		<!--详情弹窗 -->
		<view class="stops-steps-popup">
			<u-popup :show="true" :overlay='false' round="60">
				<view class="drag-btn" @touchstart="onTouchstart" @touchmove="onTouchmove" @touchend="onTouchend"
					@mousedown="onTouchstart" @mousemove="onTouchmove" @mouseup="onTouchend">
					<view class="drag-icon" />
				</view>
				<view class="poup-content" :style="{height: popupHeight}">
					<!-- 途经站点 -->
					<view class="stops-steps">
						<view class="font_bolder module-title flex_sb">途经站点</view>
						<view style="max-height: 500rpx;overflow-y: auto;">
							<u-empty mode="data" textSize='28' iconSize="70" text="暂无详细" v-if="!stopsList.length" />
							<!-- 步骤条 -->
							<u-steps direction="column" v-else inactiveColor="#2E75E6">
								<u-steps-item v-for="(item,index) in stopsList" :key="index">
									<view class="slot-icon" slot="icon" style="position: relative;">
										<image :src="stepIcon" style="width: 36rpx;height: 36rpx;">
										<text class="stepIconNum">{{item.stopNumber}}</text>
									</view>
									<view :class="['step-desc flex']" slot="desc">
										<view class="font_bolder overflowOmitRows" style="margin-right: 48rpx;width: 230rpx;">{{item.name}}</view>
										<view class="flex_col">
											<template v-if="item.stopNumber === 1">
												<view class="flex_center">
													<text class="desc-title">计划离开</text>
													<text class="desc-value">{{item.planDepartureTime}} </text>
												</view>
												<view class="flex_center">
													<text class="desc-title">实际离开</text>
													<text class="desc-value" :style="[{'color': item.statusColor}]"> {{item.actualDepartureTime}} </text>
												</view>
											</template>
											<template v-if="item.stopNumber === 2">
												<view class="flex_center">
													<text class="desc-title">计划到达</text>
													<text class="desc-value">{{item.planArrivalTime}} </text>
												</view>
												<view class="flex_center">
													<text class="desc-title">实际到达</text>
													<text class="desc-value" :style="[{'color': item.statusColor}]">{{item.actualArrivalTime}} </text>
												</view>
												<view class="flex_center">
													<text class="desc-title">计划离开</text>
													<text class="desc-value">{{item.planDepartureTime}} </text>
												</view>
												<view class="flex_center">
													<text class="desc-title">实际离开</text>
													<text class="desc-value" :style="[{'color': item.statusColor}]">{{item.actualDepartureTime}} </text>
												</view>
											</template>
											<template v-if="item.stopNumber === 3">
												<view class="flex_center">
													<text class="desc-title">计划到达</text>
													<text class="desc-value">{{item.planArrivalTime}} </text>
												</view>
												<view class="flex_center">
													<text class="desc-title">实际到达</text>
													<text class="desc-value" :style="[{'color': item.statusColor}]">{{item.actualArrivalTime}} </text>
												</view>
											</template>
										</view>
									</view>
								</u-steps-item>
							</u-steps>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import { findShipmentLbs, getMap, getMapColor } from '../../api/apiList'
	export default {
		options: { styleIsolation: 'shared' },
		data() {
			return {
				stopsList: [], //途经站点
				shipmentStopShowNumber: false, //运输轨迹站点是否显示数字
				completeTracks: [], //补全轨迹
				points: [], //实际轨迹
				popupHeight: '200rpx', //弹窗高度
				isMove: false, //是否可移动
				
				currentPosition: [], //当前位置坐标			
				mapStyle: 0, //默认地图样式				
				mapStyleList: [], //地图样式列表
				mapTheme: {}, //地图主题色
				lbsLowSpeed: 30, //最低速
				lbsOverSpeed: 80, //最高速

				stepIcon: '',

				polylines: [], //仅小程序地图展示数据
				markers: [], //仅小程序地图展示数据
				includePoints: [], //地图缩放显示所含坐标点，仅小程序地图展示数据
			}
		},
		onLoad: function(options) { //todo 定位为定车辆位置
			const { shipmentId, shipmentNo } = JSON.parse(options.data)
			this.initData(shipmentId, shipmentNo) //获取LBS数据		

			//初始化运单事件图片
			// #ifdef H5
			this.stepIcon = "../../static/img/steps/stepIcon.png"
			// #endif
			
			// #ifdef MP
			const base64 = 'data:image/jpg;base64,' //小程序不支持png格式，故转为base64
			this.stepIcon = base64 + uni.getFileSystemManager().readFileSync("static/img/steps/stepIcon.png",'base64');
			// #endif				
		},

		methods: {
			//获取地图实例
			async getMapInstance() {
				let mapCtx = null //MAap 上下文
				let newMap = null //MAap 实例
				const { serviceProvider, MapIns } = getApp().globalData

				// #ifdef MP
				newMap = MapIns
				mapCtx = uni.createMapContext('myMap')
				// #endif

				// #ifdef H5
				mapCtx = MapIns
				newMap = new MapIns.Map('myMap');
				if (serviceProvider === 'BMap') { //百度地图初始化设置
					const point = new MapIns.Point(112.324224, 33.678136);
					newMap.centerAndZoom(point, 5); //初始化地图，设置中心点坐标和地图级别
					newMap.addControl(new MapIns.ScaleControl()) // 添加比例尺控件
					newMap.enableScrollWheelZoom(); //开启鼠标滚轮缩放							
				}
				let mapStyle = this.mapStyleList[this.mapStyle]; //设置地图样式
				newMap.setMapStyle(mapStyle.value)
				// #endif

				return Promise.resolve({ mapCtx, newMap });
			},

			//获取地图主题、颜色
			findMapThem() {
				return new Promise(reslove => {
					getMapColor({}).then(res => {
						if (res) {
							const { mapStyle, mapStyleList, trackColor, shipmentStopShowNumber, lowSpeed, overSpeed} = res.data.data
							this.mapStyle = mapStyle
							this.mapStyleList = mapStyleList
							this.mapTheme = { 'light': trackColor, 'dark': trackColor }
							this.shipmentStopShowNumber = shipmentStopShowNumber
							this.lbsLowSpeed = lowSpeed
							this.lbsOverSpeed = overSpeed
							reslove('done')
						}
					})
				})
			},

			//获取LBS数据
			initData(shipmentId, shipmentNo) {
				this.$nextTick(async () => {
					await this.findMapThem() //获取地图主题色
					const { newMap, mapCtx } = await this.getMapInstance() //初始化地图实例
					const reqData = {"aux": {id: shipmentId, shipmentNo}} //shipmentNo||shipmentId 528807204405383168					
					const res = await findShipmentLbs(reqData)
					const { stops, completeTracks, tracks, points } = res.data.data || {}
					const message = res.data.message
					if (message) {
						uni.showToast({title: message, icon: 'none', duration: 3000})
					}
					this.initStops(stops)
					this.trackAnalysis(points, newMap, mapCtx) //实际轨迹线路
					this.addStopsLine(completeTracks, newMap, mapCtx) //补全轨迹线路
					// this.addStopsLine(tracks, newMap, mapCtx) //标准轨迹线路
					this.addStopsMarkers(stops, newMap, mapCtx) //添加站点标记			
				})
			},
			
			initStops(stops){ 
				const _this = this
				stops.forEach(item => { // 处理每一个经停站是否超时
				    item.statusColor = _this.getStatusColor(item)
				})
				this.stopsList = stops.reverse()            
			},
			
			getStatusColor(item){
				let color = '#8C8C8C'
				if(item.actualDepartureTime && item.planDepartureTime){ // 实际离开是否超时
				    color = new Date(item.actualDepartureTime).getTime() - new Date(item.planDepartureTime).getTime() > 0 ? '#EB2F48' : '#3DCCB9'
				}
				if(item.actualArrivalTime && item.planArrivalTime){ // 实际到达是否超时
				    color = new Date(item.actualArrivalTimee).getTime() - new Date(item.planArrivalTime).getTime() > 0 ? '#EB2F48' : '#3DCCB9'
				}
				return color
			},
			
			trackAnalysis(points=[], newMap, mapCtx){
				if(!points.length) return
				let tracks = [{lbsPointList: []}]
				for (let i = 0; i < points.length; i++) { //按速度将坐标点分段
				    let point = points[i]		
				    //相同点去除
				    if (i > 0 && point.lat === points[i -1].lat && point.lng === points[i - 1].lng) {
				        continue
				    }			
				    let status = this.getSpeedType(point)
				    if (tracks[tracks.length - 1].lbsPointList.length === 0) {
				        tracks[tracks.length - 1].status = status
				    } else if (tracks[tracks.length - 1].status !== status) {
				        tracks.push({lbsPointList: [], status})
				    }
				    tracks[tracks.length - 1].lbsPointList.push(point)    
				}
				
				//分段后拼接轨迹
				for (let i = 1; i < tracks.length; i++) {
				    tracks[i - 1].lbsPointList.push(tracks[i].lbsPointList[0])
				}
				this.addStopsLine(tracks, newMap, mapCtx)
			},
			
			//判断速度类型
			getSpeedType(point){
				let minSpeed = this.lbsLowSpeed
				let maxSpeed = this.lbsOverSpeed
				if (point.speed < minSpeed) {
				    return "LOW_SPEED"
				} else if (point.speed > maxSpeed) {
				    return "HIGH_SPEED"
				} else {
				    return "NORMAL_SPEED"
				}   
			},		

			//添加站点连线
			addStopsLine(tracks, newMap, MapInstance) { //newMap: 地图对象 MapInstance: 地图实例, 小程序中为地图上下文
				for (let i in tracks) {
					let track = tracks[i]
					let lbsPointList = track.lbsPointList
					if (lbsPointList.length === 0) {
						continue;
					}
					this.addPolyLine(lbsPointList, track.status, newMap, MapInstance)
				}
			},

			//添加连线
			addPolyLine(points, trackStatus, newMap, MapInstance) {
				if (!points.length) return
				let zIndex = 10;
				if (trackStatus === 'STANDARD_TRACK') {
					zIndex = 11
				} else if (trackStatus === 'COMPLETE_TRACK') {
					zIndex = 10
				} else {
					zIndex = 999
				}
				const strokeColor = this.getPolyLineColor(trackStatus)
				const { serviceProvider } = getApp().globalData
				
				let path = [] //转换线路坐标点
				points.forEach(point => {
					// #ifndef MP
					if (serviceProvider === 'AMap') {
						path.push([point.lng, point.lat])
					} else {
						path.push(new MapInstance.Point(point.lng, point.lat))
					}
					// #endif

					// #ifdef MP
					path.push({ latitude: point.lat, longitude: point.lng })
					// #endif
				})

				// #ifndef MP					
				let line = null
				if (serviceProvider === 'AMap') {
					// 创建折线实例
					line = new MapInstance.Polyline({
						path: path,
						zIndex,
						strokeWeight: 6, // 线条粗细
						strokeColor: strokeColor,
						showDir: true, //沿路径显示白色箭头
						cursor: '', //自定义鼠标悬停时样式
						strokeOpacity: 1, //去除路线透明度
					});
					newMap.add([line]); //添加多个覆盖物[circle, marker]
				} else {
					line = new MapInstance.Polyline(path, {
						sequence: true,
						zIndex,
						showDir: true, //沿路径显示白色箭头
						strokeColor: strokeColor, //连线颜色
						strokeWeight: 6, // 线条粗细
						strokeStyle: "solid",
						strokeOpacity: 1, //去除路线透明度
					});
					newMap.addOverlay(line);
				}
				
				//缩放地图视野
				if (serviceProvider === 'AMap') {
					newMap.setFitView() 
				} else {
					newMap.setViewport(path);
				}
				// #endif

				// #ifdef MP
				const polyline = {
					points: path,
					width: 6, // 线条粗细
					zIndex,
					color: strokeColor,
					arrowLine: true, //沿路径显示白色箭头
				}
				this.polylines = this.polylines.concat(polyline)
				this.includePoints = this.includePoints.concat(path)
				// #endif
			},

			//添加站点标记 
			addStopsMarkers(stops, newMap, MapInstance) {
				stops.forEach((stop, index) => {
					let stopIcon = require('../../static/img/lbs/load-stop.png');
					if (this.shipmentStopShowNumber) {
						if (stop.unloadStop === true) {
							stopIcon = require('../../static/img/lbs/unload-stop.png')
							if (stop.loadStop === true) {
								stopIcon = require('../../static/img/lbs/load-unload-stop.png')
							}
						}
					} else {
						stopIcon = require('../../static/img/lbs/home.png')
					}
					let marker = null
					// #ifndef MP					
					if (getApp().globalData.serviceProvider === "AMap") {
						const newMapIcon = new MapInstance.Icon({
						    image: stopIcon,// 图标的取图地址
						    imageSize: new MapInstance.Size(40, 40), // 图标所用图片大小  
						});
						const mapOptions = {
							position: [stop.lng, stop.lat],
							anchor: 'bottom-center', //icon标记的位置
							icon: newMapIcon,
							map: newMap,
						}
						if (this.shipmentStopShowNumber) {
							mapOptions.label = {
								content: stop.stopNumber,
								direction: 'center',
								offset: new MapInstance.Pixel(-0.5, 8),
							}
						} else {
							mapOptions.anchor = 'center'
						}
						marker = new MapInstance.Marker(mapOptions)
						newMap.add([marker]);
					} else {
						const iconSize = new MapInstance.Size(40, 40)
						const myIcon = new MapInstance.Icon(stopIcon, iconSize);
						const point = new MapInstance.Point(stop.lng, stop.lat);
						marker = new MapInstance.Marker(point, { icon: myIcon });
						newMap.addOverlay(marker);
					}
					// #endif

					// #ifdef MP
					marker = {
						id: Number(index), //Mark id应为数字类型
						latitude: stop.lat, //纬度
						longitude: stop.lng, //经度
						iconPath: stopIcon, //显示的图标	
						stopNumber: stop.stopNumber,
						width: 40,
						height: 40,
						customCallout: { //自定义标记点上方的气泡窗口
							anchorY: 50,
							anchorX: -0.4,
							display: "ALWAYS"
						},
					}
					this.markers = this.markers.concat(marker)
					// #endif
				})
			},

			//获取连线颜色
			getPolyLineColor(trackStatus) {
				let mapIndex = this.mapStyle
				let mapStyle = this.mapStyleList[mapIndex]
				let lineColor = this.mapTheme[mapStyle.type]
				return lineColor[trackStatus]
			},

			//移动端事件监听
			onTouchstart() {
				this.isMove = true
			},
			onTouchend() {
				this.isMove = false
			},
			onTouchmove(e) {
				if (this.isMove) {
					const { windowHeight } = uni.getSystemInfoSync()					
					let clientY
					if (uni.getSystemInfoSync().platform === 'windows') {
						clientY = e.clientY
					} else {
						clientY = e.touches[0].clientY
					}
					const height = windowHeight - clientY
					if (height <= windowHeight * 0.88 && height >= windowHeight * 0.1) { //判断屏幕间距		
						this.popupHeight = `${height * 2}rpx` //转换为rpx单位
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	.order-tracks {
        //Marker样式
		.shipment-stop-marker, /deep/.amap-marker-label{
			height: 80rpx;
			width: 80rpx;
			background-repeat: no-repeat;
			background-size: cover;
			font-size: 38rpx ;
			color: white;
			font-weight: bold;
			text-align: center;
		}

		.stops-steps-popup {
			position: relative;

			/deep/.u-popup__content {
				padding: 0 32rpx 20rpx !important;
				background: #FFFFFF;
			}

			.poup-content {
				overflow-y: auto;
			}

			.drag-btn {
				width: 100%;
				height: 80rpx;
				position: absolute;
				left: 0;
				z-index: 9999999;

				&::after {
					content: '';
					width: 92rpx;
					height: 8rpx;
					background: #000000;
					border-radius: 5rpx;
					opacity: 0.6;
					position: absolute;
					left: 50%;
					top: -15%;
					transform: translateX(-50%);
				}
			}

			.current-location {
				width: 88rpx;
				height: 88rpx;
				background: #FFFFFF;
				box-shadow: 1rpx 3rpx 8rpx 0 rgba(0, 0, 0, 0.08);
				border-radius: 24rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				position: absolute;
				right: 30rpx;
				top: -130rpx;

				.t-icon-location {
					width: 45rpx;
					height: 45rpx;
				}
			}

			.module-title {
				color: #262626;
				font-size: 28rpx;
				margin: 20rpx 10rpx;
			}

			.stops-steps {
				border-radius: 32rpx 32rpx 0 0;
				
				/deep/.u-steps-item__wrapper{
					width: 50rpx !important;	
				}
				
				/deep/.u-steps-item__content{
					margin-top: 6rpx !important;
				}
				
				/deep/.u-text{
					display: none !important;
				}

				.stepIconNum{
					font-size: 28rpx;
					color: #FFFFFF;
					position: absolute;
					left: 50%;
					top: 40%;
					transform: translate(-50%, -50%);
				}
				
				.step-desc {
					font-size: 32rpx;
					margin-left: 10rpx;

					.desc-title,
					.desc-value {
						font-size: 28rpx;
						color: #8C8C8C;
						white-space: nowrap;
					}

					.desc-title {
						margin-right: 24rpx;
					}
				}
			}
		}
	}
</style>