<template>
	<view class="trip">
		<map id="Map" class="map" style="width: 100%;" :longitude="longitude" :latitude="latitude" 
			:includePoints="includePoints" enable-poi :polyline="polyline" show-location :markers="markers"
			@regionchange="mapChange">
			<image class="current" v-show="step == 1" src="../../static/current.png" mode=""></image>
			<image class="btn" src="../../static/map-position.png" mode="" @click="myPosition"></image>
		</map>
		<view class="content">
			<template v-if="step == 1">
				<image class="bg" src="http://hyxhsh.oss-cn-chengdu.aliyuncs.com/63b7c68b71a69169d1b33f92/store/bdb/user/avatar/4wLUSMH6JJgI8c0598e7a5597db70d809806a0f0541f.png/1.png" mode=""></image>
				<view class="title" @click="go">
					专业代驾·安全无忧
				</view>
				<view class="desc">
					首次体验领66代驾券
				</view>

				<view class="operation">
					<view class="start-box" @click="chooseAddress('start')">
						<view class="point"></view>
						<view class="start">
							您将从 <text class="green">{{form.start}}</text> 出发
						</view>
					</view>
					<view class="end" @click="chooseAddress('end')">
						{{form.end||'您想去哪里'}}
					</view>
				</view>
			</template>
			<template v-else>
				<view class="charging-box">
					<view class="box">
						<view class="item"  @click="chooseAddress('start')">
							{{form.start}}
							<image class="jiantou" src="../../static/jiantou-icon.png" mode=""></image>
						</view>
						<view class="item"  @click="chooseAddress('end')">
							{{form.end}}
							<image class="jiantou" src="../../static/jiantou-icon.png" mode=""></image>
						</view>
						<view class="price" @click="jump('../expense/index')">
							预计 <text class="num">{{form.taxi_fare}}</text>元
							<image class="jiantou" src="../../static/jiantou-icon.png" mode=""></image>
						</view>
					</view>
				<view class="btn">
					呼叫秋香代驾
				</view>
				</view>
			</template>


		</view>
	</view>
</template>

<script>
	// 高德地图
	var amapFile = require('../../libs/amap-wx.130.js');
	var AMap = new amapFile.AMapWX({
		key: '0ebb337dd2e77cb84e40525a5b80d640'
	});
	// 腾讯地图
	var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
	var qqmapsdk = new QQMapWX({
		key: 'KX5BZ-B64RC-RO62W-AMWAZ-VVTC3-YAFXF'
	});
	import {earthDistance} from '@/utils/tool.js'
	export default {
		data() {
			return {
				step: 1, //
				map: null,
				longitude: 0,
				latitude: 0,
				polyline: 0,
				scale: 19,
				flag: false, //
				markers: [],
				mapCenter: {
					longitude: 0,
					latitude: 0
				},
				includePoints: [],
				form: {
					start: '',
					startLocation: {
						lat: 0,
						lng: 0
					},
					end: '',
					endLocation: {
						lat: 0,
						lng: 0
					},
					taxi_fare:0
				}
			}
		},
		methods: {
			// 跳转
			jump(url){
				uni.navigateTo({
					url
				})
			},
			// 回到我的位置
			myPosition() {
				let that = this
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						that.map.moveToLocation({
							longitude: res.longitude,
							latitude: res.latitude
						})

					}
				})
			},
			// 地图拖动
			mapChange(val) {
				// 绘制出路线后 就不能拖动地图选择起点
				if(this.step == 2) return
				let that = this
				if (val.type == 'end') {
					this.mapCenter = val.target.centerLocation
					// 高德
					// AMap.getPoiAround({
					// 	location:`${val.target.centerLocation.latitude},${val.target.centerLocation.longitude}`,
					// 	success(res){
					// 		console.log(111111111,res)
					// 	}
					// })
				
					qqmapsdk.reverseGeocoder({
						location: {
							longitude: val.target.centerLocation.longitude,
							latitude: val.target.centerLocation.latitude
						},
						poi_options: 'policy=3&address_format=short&radius=30',
						get_poi: 1,
						success(r) {
							console.log('地图拖动',r);
							if (r.result.address_reference.landmark_l2._dir_desc == '内') {
							
							}
							
							// 获取最近的店铺
							let arr = r.result.pois.sort((a,b)=>{return a._distance - b._distance})
							that.form.start = r.result.pois[0].title
							that.form.startLocation =  r.result.pois[0].location
							uni.setStorageSync('city', r.result.address_component.city)
						},
						fail(e) {
							console.log('错误', e);
						}
					})

				}
			},
			// 选择地址
			chooseAddress(type) {
				uni.setStorageSync('form', JSON.stringify(this.form))
				uni.navigateTo({
					url: '../chooseAddress/index?type=' + type
				})

			},
			// 获取当前经纬度
			initPosition() {
				let that = this
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						console.log(res);
						that.longitude = res.longitude
						that.latitude = res.latitude
						that.mapCenter = {
							longitude: res.longitude,
							latitude: res.latitude
						}
						that.myPosition()
					}
				})
			},
			//绘制路线
			go() {
				this.step = 2
				var _this = this;
				//调用距离计算接口
				qqmapsdk.direction({
					mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
					//from参数不填默认当前地址

					from: `${_this.form.startLocation.lat},${_this.form.startLocation.lng}`,
					to: `${_this.form.endLocation.lat},${_this.form.endLocation.lng}`,
					success: function(res) {
						console.log('地图绘制',res);
						_this.form.taxi_fare = res.result.routes[0].taxi_fare.fare
						var ret = res;
						var coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						var kr = 1000000;
						for (var i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						}
						//将解压后的坐标放入点串数组pl中
						for (var i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						}
						//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
						_this.latitude = pl[0].latitude
						_this.longitude = pl[0].longitude

						_this.map.addMarkers({
							markers: [{
									latitude: _this.form.startLocation.lat,
									longitude: _this.form.startLocation.lng,
									width: '82rpx',
									height: '95rpx',
									iconPath: '/static/start.png',
									callout:{
										content:_this.form.start,
										bgColor:'#fff',
										color:'#222',
										borderRadius:'50%',
										fontSize: '28rpx',
										padding:'16rpx',
										display:'ALWAYS'
									}
								},
								{
									latitude: _this.form.endLocation.lat,
									longitude: _this.form.endLocation.lng,
									width: '82rpx',
									height: '95rpx',
									iconPath: '/static/end.png',
									callout:{
										content:_this.form.end,
										bgColor:'#fff',
										color:'#222',
										borderRadius:'50%',
										fontSize: '28rpx',
										padding:'16rpx',
										display:'ALWAYS'
									}
								}
							]
						})
						_this.polyline = [{
							points: pl,
							color: '#39B0FF',
							borderColor: '#0071BC',
							arrowLine:true,
							width: 4
						}]
						setTimeout(() => {
							let includePoints = []
							includePoints.push({
								latitude: pl[0].latitude+0.01,
								longitude: pl[0].longitude+0.01
							})
							includePoints.push({
								latitude: pl[pl.length - 1].latitude - 0.01,
								longitude: pl[pl.length - 1].longitude- 0.01
							})
							_this.includePoints = includePoints
						}, 500)


					},
					fail: function(error) {
						console.error(error);
					},
					complete: function(res) {
						console.log(res);
					}
				});
			}
		},
		onReady() {
			this.map = uni.createMapContext('Map', this)
			this.initPosition()

		},
		onLoad(option) {
			let that = this
			// 获取地址选择页面传来的数据
			const eventChannel = this.getOpenerEventChannel();
			if(JSON.stringify(eventChannel) !=='{}'){
				eventChannel.on('address', function(data) {
					if(uni.getStorageSync('form')){
						that.form = JSON.parse(uni.getStorageSync('form'))
					}
					that.form[option.type] = data.address
					that.latitude = data.latitude
					that.longitude = data.longitude
					that.form[option.type + 'Location'].lat = data.latitude
					that.form[option.type + 'Location'].lng = data.longitude

					// 如果起点和终点都设置，绘制出路线
					if(that.form.start&& that.form.end){
						that.go()
					}
				})
				}
					
		},
		created() {

		}
	}
</script>

<style lang="scss" scoped>
	.trip {
		display: flex;
		flex-direction: column;
		height: 100vh;

		.map {
			height: 600rpx;
			flex: 1;
			position: relative;

			.current {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, calc(-50% - 40rpx));
				width: 40rpx;
				height: 68rpx;
			}

			.btn {
				position: absolute;
				bottom: 20rpx;
				right: 20rpx;
				width: 60rpx;
				height: 60rpx;
			}
		}

		.content {
			width: 100%;
			height: 476rpx;
			border-radius: 16rpx 16rpx 0 0;
			position: relative;

			.title {
				font-weight: 400;
				color: #FFFFFF;
				font-size: 40rpx;
				position: absolute;
				font-weight: bold;
				top: 32rpx;
				left: 32rpx;
			}

			.desc {
				color: #FFFFFF;
				font-size: 28rpx;
				position: absolute;
				top: 104rpx;
				left: 32rpx;
			}

			.bg {
				width: 100%;
				height: 476rpx;
				border-radius: 16rpx 16rpx 0 0;
			}

			.operation {
				width: 686rpx;
				height: 240rpx;
				background: #FFFFFF;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				position: absolute;
				bottom: 40rpx;
				left: 50%;
				transform: translateX(-50%);
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				align-items: center;

				.start-box {
					display: flex;
					align-items: center;
					width: 630rpx;
					height: 80rpx;
					line-height: 80rpx;
					margin-top: 30rpx;

					.point {
						width: 16rpx;
						height: 16rpx;
						background: #07AC82;
						border-radius: 50%;
					}

					.start {
						font-weight: bold;
						color: #222222;
						font-size: 28rpx;
						margin-left: 20rpx;
						display: flex;
						.green {
							color: #07AC82;
							max-width: 400rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							display: inline-block;
						}
					}
				}

				.end {
					width: 630rpx;
					height: 80rpx;
					line-height: 80rpx;
					text-indent: 36rpx;
					background: #F0F0F0;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					font-weight: bold;
					color: #222222;
					font-size: 36rpx;
					margin-top: 20rpx;
				}
			}

			.charging-box {
				width: 100%;
				height: 100%;
				background: linear-gradient(180deg, #FF7365 0%, #F9F9F9 70%,#FFF 100%);
				border-radius: 40rpx 40rpx 0rpx 0rpx;
				box-sizing: border-box;
				padding: 40rpx 32rpx;

				.box {
					padding: 30rpx;
					background: #fff;
					border-radius: 20rpx 20rpx 20rpx 20rpx;

					.item {
						font-weight: bold;
						color: #222222;
						font-size: 28rpx;
						position: relative;
						// padding: 14rpx 0;
						line-height: 70rpx;
						height: 70rpx;
						padding-left: 32rpx;
						.jiantou{
							width: 20rpx;
							height: 20rpx;
							position: absolute;
							top: 50%;
							right: 0%;
							transform: translateY(-50%);
						}
						&::before {
							content: '';
							position: absolute;
							top: 50%;
							left: 0;
							transform: translateY(-50%);
							width: 16rpx;
							height: 16rpx;
							border-radius: 50%;
							background: #07AC82;
						}
					}

					.end.item {
						border-bottom: 2rpx solid #F0F0F0;

						&::before {
							background: #FF4A39;
						}
					}

					.price {
						font-size: 28rpx;
						color: #FF4A39;
						margin: 22rpx auto 0;
						text-align: center;
						position: relative;
						.num {
							font-weight: bold;
							font-size: 30rpx;
						}
						.jiantou{
							width: 20rpx;
							height: 20rpx;
							position: absolute;
							top: 50%;
							right: 0%;
							transform: translateY(-50%);
						}
					}
				}

				.btn {
					width: 100%;
					line-height: 80rpx;
					text-align: center;
					background: #FF4A39;
					border-radius: 40rpx 40rpx 40rpx 40rpx;
					margin-top: 28rpx;
					font-weight: bold;
					color: #FFFFFF;

					font-size: 28rpx;
				}
			}
		}
	}
</style>