<template>
	<div>
		<div id="mapContainer" class="mapContainer"></div>

		<!-- 点位分类 -->
		<div class="type-box">
			<div :class="['type-item',{'type-active': index == typeIndex}]" v-for="(item,index) in mapType"
				@click="getSpotsByCategory(index)">{{item.name}}</div>
		</div>

		<div class="area-box">
			<!-- 区域分类 -->
			<div>
				<div class="area-item area-items" @click="areaMore = !areaMore">
					<img :src="'https://static.ticket.sz-trip.com/yandu/images/map/'+ (areaMore ? 'topIcon.png' : 'bottomIcon.png')"
						alt="" />
					{{areaMore ? '收起' : '展开'}}
				</div>
				<div v-if="areaMore">
					<div v-for="(item,index) in areaList" :key="index"
						:class="['area-item',{'area-active':index == areaIndex}]" @click="changeArea(index)">
						{{item.name}}
					</div>
				</div>
			</div>
			<!-- 行程线路 -->
			<div>
				<div class="area-item area-items" @click="addLine">
					<img src="https://static.ticket.sz-trip.com/yandu/images/map/addLine.png" alt="" />
					添加<br>行程
				</div>
				<div class="area-item area-items" @click="gotoLine">
					<img src="https://static.ticket.sz-trip.com/yandu/images/map/line.png" alt="" />
					线路<br>推荐
				</div>
			</div>
		</div>

		<!-- 详情弹框 -->
		<van-popup v-model="detailShow" @close="audioPause" :overlay-style="{'background-color': 'rgba(0, 0, 0, 0)'}"
			position="bottom" round>
			<ProductDetail ref="detailRef" />
		</van-popup>

		<!-- 输入线路信息弹框 -->
		<van-popup v-model="addLineShow" position="center" round>
			<div class="addLine-box">
				添加行程
				<div class="addLine-item">
					线路名称: <input type="text" v-model="lineName" placeholder="请输入线路名称" />
				</div>
				<div class="addLine-item">
					开始时间: <input type="text" v-model="lineDate" placeholder="请选择出发时间" readonly
						@click="lineDateShow = true" />
					<img src="https://static.ticket.sz-trip.com/yandu/images/map/dateRight.png" alt="">
				</div>
				<div class="addLine-btn flex-around">
					<div @click="addLineShow = false">取消</div>
					<div @click="lineClick">下一步</div>
				</div>
			</div>
		</van-popup>

		<!-- 日期选择 -->
		<van-popup v-model="lineDateShow" round position="bottom">
			<van-datetime-picker v-model="currentDate" type="date" title="选择年月日" @confirm="lineDateConfirm" />
		</van-popup>

		<!-- 添加线路行程弹框 -->
		<van-popup v-model="lineRouteShow" round position="bottom">
			<LineRoute :id="lineId" :lineDate="lineDate" ref="lineRouteRef" />
		</van-popup>
	</div>
</template>

<script>
	import moment from 'moment'
	import ProductDetail from './compoents/productDetail'
	import LineRoute from './compoents/lineRoute'
	export default {
		components: {
			ProductDetail,
			LineRoute
		},
		data() {
			return {
				mapObj: null,
				mapMarker: null,
				basics: {},
				mapType: [],
				typeIndex: -1,
				areaList: [],
				areaIndex: 0,
				areaMore: true,
				detailShow: false, // 详情弹框
				addLineShow: false, // 输入线路名称和日期弹框
				lineName: '',
				lineDate: '',
				lineDateShow: false, // 选择日期弹框
				currentDate: new Date(),
				lineRouteShow: false, // 添加线路行程弹框
				lineAddStatus: false, // 点击添加行程时为true，地图景点图标改变为加号
				lineId: '',
				maps: [], //热点
			};
		},
		mounted() {
			this.getAreaList()
		},
		methods: {
			// 获取全部区域
			getAreaList() {
				this.post({}, '/api/emap/get_map_list').then(res => {
					this.areaList = res.data
					if (res.data.length > 0) {
						this.getAreaDetail()
						this.getCategory()
					}
				})
			},
			// 更改地图区域
			changeArea(index) {
				this.areaIndex = index
				this.getAreaDetail()
			},
			// 根据code获取当前区域信息
			getAreaDetail() {
				this.post({
					code: this.areaList[this.areaIndex].code
				}, '/api/emap/get_init').then(res => {
					this.basics = res.data
					this.basics.center_poi = JSON.parse(this.basics.center_poi)
					this.basics.lb_poi = JSON.parse(this.basics.lb_poi)
					this.basics.rt_poi = JSON.parse(this.basics.rt_poi)
					this.$nextTick(() => {
						this.initMap()
					})
				})
			},
			// 根据code获取热点分类
			getCategory() {
				this.post({
					code: this.areaList[this.areaIndex].code
				}, '/api/emap/getByCategory').then(res => {
					this.mapType = Array.from(res.data)
					if(this.mapType.length > 0) this.getSpotsByCategory(0)
				})
			},
			// 根据code、热点分类获取热点
			getSpotsByCategory(index) {
				this.typeIndex = index
				this.post({
					code: this.areaList[this.areaIndex].code,
					category_id: this.mapType[this.typeIndex].id
				},'/api/emap/getSpotsByCategory').then(res => {
					console.log(res)
					this.maps = res.data
					// 移除原先点位
					this.clearMarkers()
					if(this.maps.length > 0) this.setMarkers()
				})
			},
			initMap() {
				let centerLat = this.basics.center_poi[1]
				let centerLon = this.basics.center_poi[0]
				var center = new TMap.LatLng(this.basics.center_poi[1], this.basics.center_poi[0]) //设置中心点坐标
				var sw = new TMap.LatLng(this.basics.rt_poi[1], this.basics.rt_poi[0]); //东北角坐标,
				var ne = new TMap.LatLng(this.basics.lb_poi[1], this.basics.lb_poi[0]); //西南角坐标,
				var latlngBounds = new TMap.LatLngBounds(ne, sw);
				// 初始化地图
				this.mapObj = new TMap.Map("mapContainer", {
					center: center,
					boundary: latlngBounds,
					zoom: 12, // 地图默认缩放级别
					minZoom: 12,
					maxZoom: 15,
					showControl: true, // 是否显示地图上的控件
					// viewMode: '2D',  // 地图视图模式，支持2D和3D，默认为3D。2D模式下俯仰角和旋转角度始终为0
					rotation: 0, //设置地图旋转角度
				});

				this.mapObj.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM); // 移除缩放控件
				this.mapObj.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION); // 移除旋转控件

				// 初始化瓦片
				// 瓦片图需要切好每个位置的图
				// x,y,z 为上图的坐标
				new TMap.ImageTileLayer({
					getTileUrl: function(x, y, z) {
						console.log(x, y, z)
						//拼接瓦片URL
						let url =
							`https://static.ticket.sz-trip.com/yandu/images/maps/` +
							z +
							"/" +
							x +
							"/" +
							y +
							".png";
						return url;
					},
					tileSize: 256, //瓦片像素尺寸
					minZoom: 12, //显示自定义瓦片的最小级别
					maxZoom: 15, //显示自定义瓦片的最大级别
					visible: true, //是否可见
					zIndex: 5000, //层级高度（z轴）
					opacity: 1, //图层透明度：1不透明，0为全透明
					map: this.mapObj, //设置图层显示到哪个地图实例中
				});

				// 创建点聚合实例
				// this.markerCluster = new TMap.MarkerCluster({
				// 	id: "cluster",
				// 	map: this.mapObj,
				// 	enableDefaultStyle: true, // 是否启用默认样式
				// 	minimumClusterSize: 5, // 形成聚合簇的最小个数
				// 	geometries: [],	// 点数组
				// 	zoomOnClick: true,
				// 	gridSize: 60,
				// 	averageCenter: true,
				// });
			},
			// 地图打点
			setMarkers() {
				// 聚合点点位
				// this.markerCluster.setGeometries([
				// 	{
				// 		position: new TMap.LatLng(33.332682, 120.16451)
				// 	},
				// 	{
				// 		position: new TMap.LatLng(33.329281, 120.161117)
				// 	}
				// ]);
				
				let markers = []
				let labels = []
				this.maps.forEach(item => {
					markers.push({
						"styleId": 'marker',
						text: item.name,
						position: new TMap.LatLng(item.poi_gcj02[1], item.poi_gcj02[0])
					})
					
					labels.push({
						id: 'label', // 点图形数据的标志信息
						styleId: 'label', // 样式id
						position: new TMap.LatLng(item.poi_gcj02[1], item.poi_gcj02[0]), // 标注点位置
						content: item.name, // 标注文本
						properties: {
							// 标注点的属性数据
							title: 'label',
						},
					})
				})
				
				// 添加marker点
				this.multiMarker = new TMap.MultiMarker({
					id: 'marker-layer',
					map: this.mapObj,
					styles: {
						"marker": new TMap.MarkerStyle({
							"width": 24,
							"height": 30,
							"src": 'https://static.ticket.sz-trip.com/yandu/images/map/scenic.png',
							"src": this.util.showImg(this.mapType.find(i => {return i.id == this.maps[0].category_id}).icon_image)
						})
					},
					// 点数组
					geometries: markers,
				})

				// 标记点点击事件
				this.multiMarker.on("click", this.markerClick)

				// 文本标记
				this.multiLabel = new TMap.MultiLabel({
					id: 'label-layer',
					map: this.mapObj,
					collisionOptions: {
						sameSource: true,
					}, //开启图层内部的文本标注碰撞
					styles: {
						label: new TMap.LabelStyle({
							color: '#FFF', // 颜色属性
							size: 13, // 文字大小属性
							offset: {
								x: 0,
								y: 15
							}, // 文字偏移属性单位为像素
							angle: 0, // 文字旋转属性
							alignment: 'center', // 文字水平对齐属性
							verticalAlignment: 'middle', // 文字垂直对齐属性
							backgroundColor: 'rgba(0, 0, 0, .5)',
							borderRadius: 7,
							padding: '2px 8px',
						}),
					},
					geometries: labels,
				})

				// 标记文本点击事件
				// this.multiLabel.on("click", this.markerClick)
			},
			// 移除点位
			clearMarkers() {
				if (this.multiMarker) {
					this.multiMarker.setMap(null);
					this.multiMarker = null;
				}
				
				if(this.multiLabel) {
					this.multiLabel.setMap(null);
					this.multiLabel = null;
				}
			},
			// 改变地图中心
			changeMapCenter() {
				this.mapObj.panTo(new TMap.LatLng(33.37307, 120.18467));
			},
			// 标记点点击事件
			markerClick(evt) {
				console.log(evt, evt.geometry.text)
				if (this.lineAddStatus) {
					//添加行程时
					this.$dialog.confirm({
						title: '',
						message: '是否将' + evt.geometry.text + '加入行程?'
					}).then(() => {
						this.lineId = 1
						this.$refs.lineRouteRef.addLineList()
					}).catch(() => {

					})
				} else {
					this.detailShow = true
				}
			},
			// 路线规划
			gotoLine() {
				// this.MultiPolyline = new TMap.MultiPolyline({
				// 	id: 'polyline-layer',
				// 	map: this.mapObj,
				// 	styles: {
				// 		"style_blue": new TMap.PolylineStyle({
				// 			"width": 4,
				// 			'color': '#3777FF', //线填充色
				// 			'borderWidth': 2, //边线宽度
				// 			'borderColor': '#FFF', //边线颜色
				// 			'lineCap': 'butt' //线端头方式
				// 		})
				// 	},
				// 	// 折线数据定义
				// 	geometries: [{
				// 		"id": 'style_blue',
				// 		"styleId": 'style_blue',
				// 		"paths": [new TMap.LatLng(33.347305, 120.136504), new TMap.LatLng(33.323448,
				// 			120.157053), new TMap.LatLng(33.338249, 120.1832)]
				// 	}]
				// })
				
				this.$router.push({
					path: '/lineList',
					query: {
						code: this.areaList[this.areaIndex].code
					}
				})
			},
			// 关闭弹框后暂停音频
			audioPause() {
				this.$refs.detailRef.audioPlay(false)
			},
			// 添加线路
			addLine() {
				this.lineName = ''
				this.lineDate = ''
				this.addLineShow = true
			},
			// 确认日期
			lineDateConfirm() {
				this.lineDate = moment(this.currentDate).format('YYYY-MM-DD')
				this.lineDateShow = false
			},
			// 输入线路名称和时间,下一步
			lineClick() {
				if (this.lineName.trim().length == 0 || this.lineDate.trim().length == 0) {
					this.$toast('请输入行程信息')
				} else {
					this.addLineShow = false
					this.lineRouteShow = true
				}
			},
			// 点击添加行程、关闭添加行程弹框，改变景点标识图标
			addlineRoute(status) {
				this.lineRouteShow = false

				if (status) {
					// 更换marker样式方法
					this.multiMarker.setStyles({
						"marker": new TMap.MarkerStyle({
							"width": 24,
							"height": 30,
							"src": 'https://static.ticket.sz-trip.com/yandu/images/map/add.png'
						})
					})

					// 添加行程时为true
					this.lineAddStatus = true
				} else {
					this.typeIndex = -1
					this.setMarkers(0)
				}
			}
		},
	};
</script>

<style scoped lang="scss">
	div {
		box-sizing: border-box;
	}

	.mapContainer {
		width: 100%;
		height: 100vh;
	}

	.type-box {
		position: fixed;
		z-index: 2000;
		width: 723px;
		height: 53px;
		top: 22px;
		left: 27px;
		display: flex;
		overflow-x: auto;

		.type-item {
			padding: 0 26px;
			line-height: 53px;
			background: #FFFFFF;
			border-radius: 13px;
			font-weight: 500;
			font-size: 27px;
			color: #000000;
			margin-right: 27px;
			flex-shrink: 0;
		}

		.type-active {
			background: linear-gradient(130deg, #9EE4FE, #7FD491);
			font-weight: bold;
		}
	}

	.type-box::-webkit-scrollbar {
		display: none;
	}

	.area-box {
		position: fixed;
		z-index: 2000;
		top: 153px;
		right: 17px;

		&>div {
			width: 87px;
			height: auto;
			background: #FFFFFF;
			border-radius: 43px;
			border: 2px solid #FFFFFF;
			overflow: hidden;
		}

		&>div:last-child {
			margin-top: 24px;

			.area-items {
				height: 133px !important;
			}
		}

		.area-item {
			height: 93px;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;
			border-top: 1px solid #D8D8D8;
			font-weight: 500;
			font-size: 22px;
			color: #666666;
		}

		.area-items {
			flex-direction: column;
			justify-content: space-around;
			height: 100px;

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

		.area-active {
			background: linear-gradient(130deg, #9EE4FE, #7FD491);
			color: #000000;
			font-weight: bold;
		}
	}

	// 线路弹框
	.addLine-box {
		width: 673px;
		height: 413px;
		background: #FFFFFF;
		border-radius: 27px;
		padding: 32px 33px 0 37px;
		font-weight: bold;
		font-size: 40px;
		color: #000000;

		.addLine-item {
			font-weight: 400;
			font-size: 29px;
			margin-top: 40px;

			input {
				outline: none;
				border: none;
				height: 27px;
				width: 380px;
				margin-left: 30px;
			}

			input::placeholder {
				color: #BEBEBE;
			}

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

		.addLine-btn {
			margin-top: 50px;

			div {
				width: 233px;
				line-height: 67px;
				background: #EAEAEA;
				border-radius: 13px;
				text-align: center;
				font-weight: 500;
				font-size: 29px;
				color: #000000;
			}

			div:last-child {
				background: #71B580;
				color: #FFFFFF;
			}
		}
	}
</style>