<template>
	<div class="mapIndex">
		<headNav :title="'地图'" :Larrow="false"></headNav>

		<div class="mapIndex_content">
			<div class="mapContainer">
				<baidu-map
					class="bm-view"
					@ready="onReady"
					:pinch-to-zoom="true"
					:center="center"
					:zoom="zoom"
				>
					<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
					<bm-geolocation
						anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
						:showAddressBar="true"
						:autoLocation="true"
						@locationSuccess="getLocation"
					></bm-geolocation>
					<bm-polyline
						:path="polylinePath"
						stroke-color="red"
						:stroke-opacity="0.5"
						:stroke-weight="3"
					></bm-polyline>
					<!-- <bm-polygon :path="polygonPath" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2" /> -->
					<bm-marker
						v-for="(item, index) in polygonPath"
						:key="index"
						:position="{ lng: item.lng, lat: item.lat }"
					>
						<bm-label
							v-if="item.my"
							:content="item.title"
							:labelStyle="{
								color: '#fff',
								backgroundColor: '#0066cc',
								border: '1px solid #0066cc',
								fontSize: '10px',
								borderRadius: '5px',
								padding: '3px 5px',
								opacity: '0.8'
							}"
							:offset="{ width: 20, height: 20 }"
						/>
						<bm-label
							v-else
							:content="item.title"
							:labelStyle="{
								color: '#0066cc',
								border: '1px solid #0066cc',
								fontSize: '10px',
								borderRadius: '5px',
								padding: '3px 5px',
								opacity: '0.8'
							}"
							:offset="{ width: 20, height: 20 }"
						/>
					</bm-marker>
				</baidu-map>
			</div>

			<div class="missionInfo">
				<div class="missionInfo_title">任务执行路线排序</div>

				<div class="missionInfo_timepicker">
					<van-cell is-link :value="currentTime" @click="show_time = true"></van-cell>
					<div class="missionInfo_timepicker_missionbar">
						<div class="mr20">
							今日任务:
							<span>{{ missionList.length }}</span>
							条
						</div>
						<div>
							任务时长:
							<span>{{ getMissionTime() }}</span>
							h
						</div>
					</div>
				</div>

				<div class="missionInfo_timebar_container">
					<div class="missionInfo_timebar_content">
						<span
							v-for="(item, ind) in missionList"
							:style="{ 'background-color': item.color, width: item.width }"
							class="missionInfo_timebar_daily"
							:key="ind"
						></span>
					</div>
				</div>

				<div class="missionInfo_missionList">
					<div class="missionInfo_missionList_container">
						<van-steps
							direction="vertical"
							active-color="#0066CC"
							:active="tabActiveNum"
							@click-step="clickStep"
						>
							<van-step>
								<template #active-icon>
									<van-icon name="location" color="#0066cc"></van-icon>
								</template>
								<div class="df">
									<div class="fb mr5">我的位置</div>
									<span class="fz12">( {{ myLocation }} )</span>
								</div>
							</van-step>
							<van-step v-for="(item, index) in missionList" :key="index">
								<template #active-icon>
									<van-icon name="location" color="#0066cc"></van-icon>
								</template>
								<div @click="showPopur(item)" class="vanStepContainer">
									<van-popover
										v-model="item.showPopover"
										trigger="click"
										placement="top-end"
									>
										<div class="mapList">
											<div class="baiduMap" @click="turnToMap(item, 1)">
												<van-image
													:src="require('../../assets/baidu.png')"
												></van-image>
											</div>
											<div class="gaodeMap" @click="turnToMap(item, 2)">
												<van-image
													:src="require('../../assets/gaode.png')"
												></van-image>
											</div>
											<div class="tencentMap" @click="turnToMap(item, 3)">
												<van-image
													:src="require('../../assets/tencent.png')"
												></van-image>
											</div>
										</div>
										<template #reference>
											<div class="title df aic jfsb">
												<div class="FontColorNormal fb title_active">
													{{ item.taskName }}
												</div>
												<div class="df aic">
													<span
														v-if="item.isComplete === '已完成'"
														class="fb mr5 FontColorOther"
													>
														已完成
													</span>
													<span v-else class="fb mr5 FontColorWarn">
														未完成
													</span>
												</div>
											</div>
											<div class="FontColorInfo fz12 title_active df aic">
												<div class="mt10 mr10">
													任务时间：
													<span>{{ item.taskTime }}</span>
												</div>
												<div class="mt10">
													根据时长：
													<span>{{ item.taskLong }}</span>
												</div>
											</div>
										</template>
									</van-popover>
								</div>
							</van-step>
						</van-steps>
					</div>
				</div>
			</div>
		</div>

		<div id="allmap" style="display: none;"></div>

		<!-- 时间弹窗 -->
		<van-popup v-model="show_time" position="bottom">
			<van-datetime-picker
				v-model="currentDate"
				type="date"
				title="选择年月"
				:min-date="minDate"
				:max-date="maxDate"
				@cancel="show_time = false"
				@confirm="chooseDate"
			/>
		</van-popup>

		<!-- 遮罩层 -->
		<v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
	</div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from '@/components/overLay_xy.vue';
import { get, post } from '@/utils/http.js';

export default {
	name: 'mapIndex',
	components: {
		headNav,
		'v-mask': mask_overLay
	},
	data() {
		return {
			zoom: 10,
			center: '成都市',
			myLocation: '尚未定位',
			currentTime: '',
			tabActiveNum: 0,
			showOverLay: false,
			tipMsg: '加载中',
			missionList: [],
			polygonPath: [],
			polylinePath: [],
			BMap: '',
			show_time: false,
			currentDate: new Date(),
			minDate: new Date(2000, 0, 1),
			maxDate: new Date(2050, 10, 1),
			searchInfo: {
				executeTime: new Date()
			}
		};
	},
	mounted() {
		this.getTime();

		// if (window.history && window.history.pushState) {
		// 	history.pushState(null, null, document.URL);
		// 	window.addEventListener('popstate', this.backPage, false);
		// }
	},
	// destroyed() {
	// 	window.removeEventListener('popstate', this.backPage, false);
	// },
	methods: {
		// 初始化
		async init() {
			this.tipMsg = '加载中';
			this.showOverLay = true;
			await this.getPagerListApi();
			this.showOverLay = false;
			this.loadMapRoute();
		},

		// 获取日常检查列表Api
		async getPagerListApi() {
			this.polygonPath = [];
			this.polylinePath = [];

			await post('/v1/api/applet/mapTask/pageList', this.searchInfo)
				.then(res => {
					if (res.success == true) {
						this.missionList = [];
						res.data.list.map(item => {
							this.missionList.push({
								color: this.backColor(),
								width: this.getWidth(item, res.data.list),
								isComplete: item.executeStatus === '2' ? '已完成' : '未完成',
								taskAddr: item.taskAddr,
								taskName: item.byCheckUnit,
								taskType:
									item.checkType === '1'
										? '【日常消防监督检查】'
										: '【行动消防检查】',
								taskTime: item.executeTime,
								taskLong:
									parseFloat(item.checkContTime) +
									parseFloat(item.commutingTime) +
									'h'
							});
						});
					} else {
						this.$toast.fail('获取检查列表失败');
					}
				})
				.catch(err => {
					this.$toast.fail('请求错误');
				});
		},

		// backPage() {
		// 	exitCurrentUi();
		// },

		getWidth(item, list) {
			let totalTime = 0;
			let nowTime = parseFloat(item.checkContTime) + parseFloat(item.commutingTime);
			list.map(i => {
				totalTime += parseFloat(i.checkContTime) + parseFloat(i.commutingTime);
			});
			return (nowTime / totalTime) * 100 + '%';
		},

		// 返回随机的颜色参数
		backColor() {
			let colorNum = '';
			let color1 = this.randomColor();
			let color2 = this.randomColor();
			let color3 = this.randomColor();
			let color4 = this.randomColor();
			let color5 = this.randomColor();
			let color6 = this.randomColor();
			return '#' + color1 + color2 + color3 + color4 + color5 + color6;
		},

		// 产生随机的颜色值
		randomColor: function() {
			let num = parseInt(Math.random() * 16);
			let color = '';
			switch (num) {
				case 0:
					color = '0';
					break;
				case 1:
					color = '1';
					break;
				case 2:
					color = '2';
					break;
				case 3:
					color = '3';
					break;
				case 4:
					color = '4';
					break;
				case 5:
					color = '5';
					break;
				case 6:
					color = '6';
					break;
				case 7:
					color = '7';
					break;
				case 8:
					color = '8';
					break;
				case 9:
					color = '9';
					break;
				case 10:
					color = 'A';
					break;
				case 11:
					color = 'B';
					break;
				case 12:
					color = 'C';
					break;
				case 13:
					color = 'D';
					break;
				case 14:
					color = 'E';
					break;
				case 15:
					color = 'F';
					break;
			}
			return color;
		},

		// 获取任务时长
		getMissionTime() {
			let time = 0;
			this.missionList.map(item => {
				time += parseFloat(item.taskLong);
			});
			return time.toFixed(1);
		},

		// 获取当前位置
		getLocation(location) {
			let cityStr = '';
			cityStr =
				location.addressComponent.city +
				location.addressComponent.street +
				location.addressComponent.streetNumber;
			this.myLocation = cityStr;

			this.polygonPath.map((item, index) => {
				if (item.my) {
					this.polygonPath.splice(index, 1);
				}
			});

			this.polygonPath.unshift({
				lat: location.point.lat,
				lng: location.point.lng,
				my: true,
				title: cityStr,
				show: false
			});

			this.routePlan();
		},

		// 格式化时间
		getTime() {
			let time = this.$getTime(this.currentDate);
			time = time.split(' ')[0];
			this.currentTime = time;
		},

		// 地图加载完毕时刻
		onReady(mapObj) {
			this.BMap = mapObj.BMap;
			this.init();
		},

		// 地图路线绘制
		loadMapRoute() {
			let that = this;
			let BMap = this.BMap;
			let map = new BMap.Map('allmap');
			map.centerAndZoom(new BMap.Point(116.404, 39.915), 12); // 初始化地图,设置中心点坐标和地图级别

			if (this.missionList.length === 0) {
				this.$toast.fail('今日无任务');
				this.polygonPath = [];
				this.polylinePath = [];
			} else {
				this.showOverLay = true;
				this.tipMsg = '路线规划中';

				let geolocation = new BMap.Geolocation(); // 定位到当前位置

				// 开启辅助定位
				geolocation.enableSDKLocation();

				geolocation.getCurrentPosition(function(r) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						let cityStr = '';
						cityStr = r.address.city + r.address.street + r.address.street_number;
						that.myLocation = cityStr;

						that.polygonPath.unshift({
							lat: r.point.lat,
							lng: r.point.lng,
							my: true,
							title: cityStr,
							show: false
						});

						let local = new BMap.LocalSearch(map, {
							renderOptions: {
								map: map,
								autoViewport: true,
								selectFirstResult: true
							},
							pageCapacity: 1
						});

						that.missionList.map((item, index) => {
							local.search(item.taskAddr);
							
							local.setSearchCompleteCallback(function(results) {
								
								if (results && results.Hr && results.Hr.length > 0) {
									that.polygonPath.push({
										lng: results.Hr[0].point.lng,
										lat: results.Hr[0].point.lat,
										my: false,
										title: results.Hr[0].title,
										show: true,
										keyword: results.keyword
									});
								} else {
									that.$toast.fail(`地址错误, 无法定位到${ results.keyword }`);
									that.polygonPath.push({
										lng: 106.558437,
										lat: 29.568996,
										my: false,
										title: `无法定位到${ results.keyword }`,
										show: true,
										keyword: results.keyword
									})
								}

								// that.missionList.map(i => {
								// 	that.polygonPath.map(j => {
								// 		if (i.address === j.keyword) {
								// 			j.missionName = '任务名称';
								// 		}
								// 	});
								// });

								// 获取到全部地图的点进行路线规划
								if (that.polygonPath.length === that.missionList.length + 1) {
									that.showOverLay = false;
									that.routePlan();
								}
							});
						});
					} else {
						that.$toast.fail('定位失败');
						that.showOverLay = false;
					}
				});
			}
		},

		// 路线规划 (最短路径：简化版迪杰斯特拉)
		routePlan() {
			let shortestRouteArr = []; // 当前最短顶点
			let otherRouteArr = []; // 剩余顶点

			shortestRouteArr.push(this.polygonPath[0]); // 出发点 设置当前位置

			this.polygonPath.map((i, index) => {
				if (index > 0) {
					otherRouteArr.push(i);
				}
			});

			for (var i = 0; i < this.polygonPath.length - 1; i++) {
				let lastCity = shortestRouteArr[shortestRouteArr.length - 1];
				let distanceArr = []; // 用于记录路径长度的数组
				let shortestVal = '';
				let shortestIndex = '';

				otherRouteArr.map(item => {
					// 计算最后最短顶点到剩余顶点的距离
					distanceArr.push(
						this.pointDistance(
							{
								lng: lastCity.lng,
								lat: lastCity.lat
							},
							{
								lng: item.lng,
								lat: item.lat
							}
						)
					);
				});

				distanceArr.map((item, index) => {
					// 获取当前最短路径的顶点
					if (index === 0) {
						shortestVal = item;
						shortestIndex = index;
					} else {
						if (item < shortestVal) {
							shortestVal = item;
							shortestIndex = index;
						}
					}
				});

				shortestRouteArr.push({ ...otherRouteArr.splice(shortestIndex, 1)[0] });
			}

			this.polylinePath = shortestRouteArr;
			let missionInfoArr = [];

			this.missionList.map((i, index) => {
				let flag = true;
				shortestRouteArr.map(j => {
					if (i.taskAddr === j.keyword && flag) {
						missionInfoArr.push(i);
						flag = false;
					}
				});
			});

			this.missionList = missionInfoArr;
		},

		// 获取两个点的距离
		pointDistance(startPoint, endPoint) {
			const map = new this.BMap.Map('container');
			const point1 = new BMap.Point(startPoint.lng, startPoint.lat);
			const point2 = new BMap.Point(endPoint.lng, endPoint.lat);
			return map.getDistance(point1, point2);
		},

		clickStep(index) {
			if (index === 0) {
				if (this.myLocation != '尚未定位') {
					this.center = this.myLocation;
				} else {
					this.$toast.fail('尚未定位');
					return;
				}
			} else {
				this.center = this.missionList[index - 1].taskAddr;
			}
			this.tabActiveNum = index;
			this.zoom = 13;
		},

		// 跳转地图
		turnToMap(item, index) {
			const that = this;
			let geolocation = new this.BMap.Geolocation(); // 定位到当前位置
			this.showOverLay = true;
			this.tipMsg = '定位当前位置中';
			geolocation.getCurrentPosition(function(r) {
				that.showOverLay = false;
				if (this.getStatus() == BMAP_STATUS_SUCCESS) {
					that.myLocation = r.address.city + r.address.street + r.address.street_number;
					let myLocation = `myLocation=${r.latitude},${r.longitude}`;
					let destination;
					that.polygonPath.map(i => {
						if (i.keyword === item.taskAddr) {
							destination = `destination=${i.lat},${i.lng}`;
						}
					});

					that.$router.push(
						`/mapDetails/${that.myLocation}/${
							item.taskAddr
						}/${myLocation}&${destination}&status=${index}`
					);
				} else {
					this.$toast.fail('定位失败');
				}
			});
		},

		showPopur(item) {
			item.showPopover = true;
		},

		// 切换日期
		chooseDate() {
			this.getTime();
			this.searchInfo.executeTime = this.currentTime;
			this.init();
			this.show_time = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.mapIndex {
	.mapIndex_content {
		.mapContainer {
			position: absolute;
			width: 100%;
			margin-top: 47px;
			height: 400px;
			z-index: 999;

			.bm-view {
				height: 100%;
			}
		}

		.missionInfo {
			height: calc(100vh - 47px - 400px);
			width: 100%;
			background-color: #fff;
			border-radius: 8px;
			position: absolute;
			bottom: 0;
			overflow: hidden;
			overflow-y: auto;

			.missionInfo_title {
				font-size: 14px;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 5px 0;
				padding-top: 10px;
				font-weight: bold;
				color: #323232;
			}

			.missionInfo_timepicker_missionbar {
				font-size: 12px;
				padding: 0 15px;
				color: #a1a1a1;
				display: flex;
			}

			.missionInfo_timebar_container {
				width: 100%;
				margin-top: 10px;

				.missionInfo_timebar_content {
					margin: 0 15px;
					height: 10px;
					display: flex;

					.missionInfo_timebar_daily {
						display: block;
						height: 10px;
					}
				}
			}

			.missionInfo_missionList {
				width: 100%;
				font-size: 14px;

				.missionInfo_missionList_container {
					padding: 10px 0px;
				}
			}

			.vanStepContainer {
				display: flex;
				justify-content: space-between;
				width: 100%;
			}
		}
	}
}
</style>

<style lang="scss">
.mapIndex {
	.van-cell {
		span {
			// font-weight: bold;
			color: #4e4e50;
		}
	}

	.van-cell.van-cell--clickable {
		padding: 5px 15px;

		&::after {
			border: none;
		}
	}

	.van-step__title {
		padding: 10px 10px;
		border-radius: 5px;
	}

	.van-step__title.van-step__title--active {
		background-color: #f1f1f1;

		.title_active {
			color: #0066cc;
		}
	}

	.BMap_pop {
		a {
			display: none;
		}
	}

	.van-popover__wrapper {
		width: 100%;
	}

	.van-hairline.van-step.van-step--vertical {
		padding: 0;
		padding-right: 15px;
		position: relative;
	}

	.missionInfo_missionList_container {
		.van-cell.van-cell--clickable {
			padding: 0;
		}
	}
}

.mapList {
	display: flex;
	justify-content: space-between;
	font-size: 14px;
	padding: 5px 5px;

	.baiduMap {
		width: 25px;
		height: 25px;
		padding: 3px 5px;

		img {
			width: 25px;
			height: 25px;
		}
	}

	.gaodeMap {
		width: 25px;
		height: 25px;
		padding: 3px 5px;
		img {
			width: 25px;
			height: 25px;
		}
	}

	.tencentMap {
		width: 25px;
		height: 25px;
		padding: 3px 5px;

		img {
			width: 25px;
			height: 25px;
		}
	}
}

.van-popup.van-popover.van-popover--light {
	z-index: 1 !important;
}
</style>
