<template>
	<view class="box">
		<map  :latitude="latitude" 
		:longitude="longitude" :markers="covers"
		 @poitap="tapfn" class="mapbox"
		 :include-points="points" ></map><!-- @regionchange="regionchangefn" :style="{height:mapHeight + 'px'}" -->

		<view class="contBox" >
			<view class="tab">
				<view class="tabLine" :class="{tabActive:tabIndex==0}" @click="tabClick(0)">现在</view>
				<view class="tabLine" :class="{tabActive:tabIndex==1}" @click="tabClick(1)">预约</view>
			</view>

			<view class="timeBox" v-if="tabIndex==1" @click="openDatetimePicker">
				<view class="time">{{yytime?yytime:'预约救援时间'}}</view>
				<image src="../../static/img/little_rightArrow.png" mode="" style="width: 30rpx;height: 30rpx;"></image>
			</view>


			<view class="typeBox">
				<view class="box2" v-if="setting.indexOf(1)!=-1" @click="typeClick(1)" :class="{typeActive:typeIndex==1}">
					<image src="../../static/img/icon_dadian_N.png" mode="" class="typeImg"></image>
					<view class="title">搭电</view>
				</view>
				<view class="box2" v-if="setting.indexOf(2)!=-1" @click="typeClick(2)" :class="{typeActive:typeIndex==2}">
					<image src="../../static/img/icon_tuoche_N.png" mode="" class="typeImg"></image>
					<view class="title">拖车</view>
				</view>
				<view class="box2" v-if="setting.indexOf(3)!=-1"  @click="typeClick(3)" :class="{typeActive:typeIndex==3}">
					<image src="../../static/img/icon_luntai_N.png" mode="" class="typeImg"></image>
					<view class="title">换胎</view>
				</view>
				<view class="box2" v-if="setting.indexOf(4)!=-1" @click="typeClick(4)" :class="{typeActive:typeIndex==4}">
					<image src="../../static/timg/icon_luntai_def.png" mode="" class="typeImg"></image>
					<view class="title">未知原因</view>
				</view>
			</view>

			<view class="price">服务费用 {{helpPrice}}</view>

			<!-- <view class="shopBox">
				<view class="left">
					<view class="graypoint"></view>
					<view class="leftTitle">门店</view>
					<view class="content">{{shopInfo.shopName}}</view>
				</view>
				<image src="../../static/img/little_rightArrow.png" mode="" style="width: 30rpx;height: 30rpx;"></image>

			</view> -->

			<view class="shopBox" @click="startBtn">
				<view class="left">
					<view class="graypoint"></view>
					<view class="leftTitle">位置</view>
					<view class="content">{{currentAddress}}</view>
				</view>
				<image src="../../static/img/little_rightArrow.png" mode="" style="width: 30rpx;height: 30rpx;"></image>
			
			</view>
			
			<view class="shopBox" @click="endBtn" v-if="typeIndex==2">
				<view class="left">
					<view class="graypoint"></view>
					<view class="leftTitle">终点</view>
					<view class="content" v-if="endAddress">{{endAddress}}</view>
					<view class="Nocontent" v-else>请选择</view>
				</view>
				<image src="../../static/img/little_rightArrow.png" mode="" style="width: 30rpx;height: 30rpx;"></image>
			
			</view>
			
		</view>

		<view class="bottomView">
			<view class="sure" @click="sure">确定</view>
		</view>
      <w-picker
			  :visible.sync="visible"
			  mode="date" 
			  startYear="2024" 
			  endYear="2029"
			  value=""
			  :current="true"
			  fields="minute"
			  @confirm="onConfirm($event,'date')"
			  @cancel="onCancel"
			  :disabled-after="false"
			  ref="picker" 
		  ></w-picker>
		  
		  
		  <!-- 手机号授权 -->
		  	<view class="authorizBox" v-if="authorizShow" @click="authorizShow=false">
		  		<view class="authorizCont" @click.stop="">
		  			<view class="authorizName">{{wxOpenData.miniAppName}}</view>
		  			<view class="authorizMs">您好，欢迎访问本店，授权手机号登录能获取我们最新的促销活动哦~</view>
		  			<view class="sqLine">
		  				<button class="authorizContbutton" type="default" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">授权</button>
		  			    <view class="sqRefuse" @click="authorizShowHide">拒绝</view>
		  			</view>
		  		</view>
		  		<view style="text-align: center;padding-top: 56rpx;">
		  			<image src="../../static/timg/icon_guanbi@2x.png" mode="" class="authorizCloseImg"></image>
		  		</view>
		  	</view>
		  	
	</view>
</template>

<script>
	import wPicker from "@/components/w-picker/w-picker.vue";
	import QQMapWX from '@/utils/qqmap-wx-jssdk.js'
	export default {
		components: {
			wPicker
		},
		data() {
			return {
				latitude: '',
				longitude: '',
				covers: [
					// {
					// latitude: 39.909,
					// longitude: 116.39742,
					// iconPath: '../../static/img/icon_qidian.png'
				 //  }, {
					// latitude: 39.90,
					// longitude: 116.39,
				 //  	iconPath: '../../static/img/icon_zhongdian.png'
				 //   },
				],
				tabIndex: 0,
				tMap:'',
				mapHeight:200,
				currentAddress:'',
				endAddress:'',
				points: [],
				endLat:'',
				endLng:'',
				distance:'',
				time:'',
				typeIndex:1,
				shopInfo:'',
				shopList:'',
				visible:false,
				yytime:'',
				userInfo:'',
				ext:'',
				wxOpenData:'',
				authorizShow:false,
				shopid:'',
				msg:'',
				helpPrice:'',
				helptime:'',
				setting:'',
			}
		},
		onLoad() {
			var that = this;
			this.userInfo=this.$store.state.userInfo;
			this.ext=this.$common.getExtStoreId();
			if(this.userInfo){
				this.getsetting()
			}else{
				this.$common.automaticlogin().then(val => {
					this.userInfo=this.$store.state.userInfo;
					this.wxOpenData=this.$store.state.wxOpenData;
					if(!this.userInfo){
						this.authorizShow=true
					}
				})
			}
			//this.queryRescue()
			//return false;
			const tMap = new QQMapWX({
				key: 'L2GBZ-CIS6J-HRFFV-K5LO6-QROT7-BQFXZ' //开发者密钥 //这里要换成自己的key
			});
			this.tMap=tMap
			// uni.getSystemInfo({
			// 	success: (res) => {
			// 		this.mapHeight = res.windowHeight  *2 - 664 - 120
			// 	}
			// })
			
			 uni.getLocation({
				type: 'gcj02',
				success: function (res) {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					that.latitude=res.latitude;
					that.longitude=res.longitude;
					//that.getShopInfo()
					var obj={
						 latitude: that.latitude,
						 longitude: that.longitude,
						 iconPath: '../../static/img/icon_qidian.png',
						 width:25,
						 height:39
					}
					that.covers.push(obj);
					that.points.push({
						longitude: that.longitude,  
						latitude:that.latitude 
					})
					//that.calculateDistance()
					//that.queryhelpshopList()
					that.tMap.reverseGeocoder({
						location: {
							latitude: that.latitude,
							longitude: that.longitude
						},
						success: function(res) {
							console.log(res)
							that.currentAddress=res.result.formatted_addresses.recommend
						},
						 fail: function(res) {
						    console.log(res);
						},
					})
				}
			}); 
			
		},
		
		methods: {
			getsetting(){
				this.$http('openShopHelpSheetOrder/help-type-setting', {
				 
				 },'POST').then(res => {
					this.setting=res.data
					if(!this.setting){
						uni.showModal({
						    title: '提示',
						    content: '门店不支持救援服务',
							confirmText:'我知道了',
							showCancel:false,
						    success: function (res) {
																	
						        if (res.confirm) {
								   uni.switchTab({
								   	url:'index'
								   })
						        } /* else if (res.cancel) {
															// uni.hideLoading();
						          uni.redirectTo({
						          		url:'../subPack/rescueOrderOrderDetail?id='+id
						          }) 
								   
						        } */
						    }
						});
					}
				 })
			},
			decryptPhoneNumber: function(e) {
			  console.log(e);
			  this.code=e.detail.code
			  this.wxPhoneLogin()
			  this.authorizShow=false;
			},
			wxPhoneLogin(){
					 var that=this;
					 this.$http('miniApp2/sys/wxPhoneLogin', {
					   appId:this.ext.appId,
					   unionId:this.ext.unionId,
					   code:this.code,
					   openId:this.wxOpenData.openid
					  },'POST').then(res => {
						var data = res.data;
						if(data.loginInfo){
							this.userInfo=data.loginInfo.openUser;
							this.wxOpenData=data.loginInfo;
							this.$store.commit('mutationswxOpenData', data)
							this.$store.commit('mutationsuserInfo', this.userInfo)
						    //this.getData()
						}	
					  })
			},
			getShopInfo(){
				this.$http('openShopHelpSheetOrder/getShopInfo', {
					lat:this.latitude,
					lng:this.longitude
				}, 'GET').then(res => {
					this.shopInfo=res.data.shopInfo;
					this.helpPrice=res.data.shopHelpSetting.helpPrice;
					this.msg=res.msg
				})
			},
			onConfirm(e){
				console.log(e)
				this.yytime=e.result
				this.helptime=e.obj.hour+':'+e.obj.minute
			},
			openDatetimePicker() {
			     this.$refs.picker.show()
			 },
			    // 关闭picker
			onCancel() {
			    this.$refs.picker.hide()
			},
			queryRescue(){
				uni.showLoading({
					title: '加载中'
				})
				this.$http('openEmergencyRescue/queryRescue', {}, 'GET').then(res => {
					uni.hideLoading();
					//this.shopList = res.data
					
				})
			},
			queryhelpshopList(){
				uni.showLoading({
					title: '加载中'
				})
				this.$http('openEmergencyRescue/queryhelpshopList', {}, 'GET').then(res => {
					uni.hideLoading();
					this.shopList = res.data
					
				})
			},
			sure(){
				if (this.userInfo) {
					
				} else {
					this.authorizShow = true;
					return false;
				}
				if(this.tabIndex==0){
					const yy = new Date().getFullYear()
					  const MM = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
					  const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
					  const HH = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
					  const mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
					  //const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
					  var time= yy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm //+ ':' + ss
					  console.log(time) 
					  this.helptime=HH + ':' + mm
					  //return false;
					
				}else{
					if(this.yytime==''){
						uni.showToast({
							 title: '请选择预约时间',
							 icon:'none',
							 duration: 3000
						});
						return false;
					}
					var time=this.yytime
				}
				
				if(this.typeIndex==2){
					if(this.endAddress==''){
						uni.showToast({
							 title: '请选择终点',
							 icon:'none',
							 duration: 3000
						});
						return false;
					}
				}
				//console.log(time)
				
				this.$http('openShopHelpSheetOrder/getShopInfo', {
					lat:this.latitude,
					lng:this.longitude,
					type:this.typeIndex,
					helptime:this.helptime
				}, 'GET').then(res => {
					if(res.code==0){
						this.shopInfo=res.data.shopInfo;
						this.helpPrice=res.data.shopHelpSetting.helpPrice;
						this.msg=res.msg
					}else{
						this.shopInfo=''
					}
					
				
				/* uni.redirectTo({
						url:'../subPack/rescueOrderOrderDetail?id='
				}) */
				 if(!this.shopInfo){
					uni.showToast({
						 title: res.data.msg,
						 icon:'none',
						 duration: 3000
					});
					return false
				} 
			     var orderType=1;
				 if(this.tabIndex==1){
					 orderType=2
				 }
				
				uni.navigateTo({
					url:'confirmRescue?lat='+this.latitude+"&lng="+this.longitude+"&shopId="+this.shopInfo.ID+'&shopName='+this.shopInfo.ShopName+'&type='+this.typeIndex+'&time='+time+'&currentAddress='+this.currentAddress+'&endAddress='+this.endAddress+'&endLat='+this.endLat+'&endLng='+this.endLng+'&orderType='+orderType
				})
				
				})
			},
			startBtn(){
				var that=this;
				uni.chooseLocation({
					success: function (res) {
						console.log(res);
						that.currentAddress=res.name
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
						that.longitude=res.longitude
						that.latitude=res.latitude//.toFixed(5)
						var obj={
							 latitude: that.latitude,
							 longitude: that.longitude,
							 iconPath: '../../static/img/icon_qidian.png',
							 width:25,
							 height:39
						}
						var obj2 = {
							longitude: that.longitude,  
							latitude:that.latitude 
						}
						that.covers[0]=obj;
						that.points[0]=obj2;
						//that.getShopInfo()
						//that.calculateDistance()
						console.log(that.covers)
					},
					fail(err){
						console.log(err)
					}
				})
			},
			endBtn(){
				
				var that=this;
				 uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success() {
									that.chooseLocation()
									return;
								}
							})
						}else{
							that.chooseLocation()
							return;
						}
					}
				})
				
			},
			chooseLocation(){
				var that=this;
				uni.chooseLocation({
					success: function (res) {
						console.log(res);
						that.endAddress=res.name
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
						var longitude=res.longitude
						var latitude=res.latitude
						var obj={
							 latitude: latitude,
							 longitude: longitude,
							 iconPath: '../../static/img/icon_zhongdian.png',
							 width:25,
							 height:39,
							 // label:{
								//  content:'文本'
							 // },
							callout: { //自定义标记点上方的气泡窗口 点击有效  
								content: '拖到这里', //文本
								color: '#ffffff', //文字颜色
								fontSize: 15, //文本大小
								borderRadius: 15, //边框圆角
								padding: '10',
								bgColor: '#FF0000', //背景颜色
								display: 'ALWAYS', //常显
							}
							
						}
						var obj2={
							longitude: longitude,
							latitude:latitude 
						}
						that.endLat=latitude;
						that.endLng=longitude
						if(that.covers.length>1){
							that.covers[1]=obj;
							that.points[1]=obj2;
						}else{
							that.covers.push(obj);
							that.points.push(obj2)
						}
						//console.log(that.covers)
						//that.calculateDistance()
					},
					fail(err){
						console.log(err)
					}
				})
			},
			//计算距离
			calculateDistance(){
				//调用距离计算接口
				    var that=this;
				    this.tMap.calculateDistance({
				        mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
				        //from参数不填默认当前地址
				        //获取表单提交的经纬度并设置from和to参数（示例为string格式）
				        from: {
							latitude:  that.shopInfo.lat,
							longitude: that.shopInfo.lng,
						}, //若起点有数据则采用起点坐标，若为空默认当前地址
				        to:[
						{
							latitude: that.latitude,
							longitude: that.longitude
						}	
						] , //终点坐标
				        success: function(res) {//成功后的回调
				          console.log(res);
				          that.distance=res.result.elements[0].distance;
						  that.time = res.result.elements[0].duration/60;
						  that.time=Math.ceil(that.time)
						  that.setTime()
				        },
				        fail: function(error) {
				          console.error(error);
				        },
				        complete: function(res) {
				          console.log(res);
				        }
				    });
			},
			setTime(){
				var obj={
					 latitude: this.latitude,
					 longitude: this.longitude,
					 iconPath: '../../static/img/icon_qidian.png',
					 width:25,
					 height:39,
					 callout: { //自定义标记点上方的气泡窗口 点击有效
					 	content: '约'+this.time+'分钟到达', //文本
					 	color: '#ffffff', //文字颜色
					 	fontSize: 15, //文本大小
					 	borderRadius: 15, //边框圆角
					 	padding: '10',
					 	bgColor: '#3F90F7', //背景颜色
					 	display: 'ALWAYS', //常显
					 }
				}
				
				this.covers[0]=obj;
			},
			regionchangefn(e){
			 console.log(e)
			 var that=this;
			 if(e.detail.centerLocation){
				var latitude=e.detail.centerLocation.latitude;
				var longitude=e.detail.centerLocation.longitude;
				 var obj={
				 	 latitude: latitude,
				 	 longitude: longitude,
				 	 iconPath: '../../static/img/icon_qidian.png',
					 width:25,
					 height:39
				 }
				this.covers=[];
				this.covers.push(obj)
			 }
			
			},
			tapfn(e){
				//点击获取位置
				 return false;
				 console.log(e);
				 var that=this;
				 var latitude=e.detail.latitude;
				 var longitude=e.detail.longitude;
				  var obj={
				  	 latitude: latitude,
				  	 longitude: longitude,
				  	 iconPath: '../../static/img/icon_qidian.png',
					 width:25,
					 height:39
				  }
				  this.covers=[];
				  this.covers.push(obj)
				  this.tMap.reverseGeocoder({
				  	location: {
				  		latitude: latitude,
				  		longitude: longitude
				  	},
				  	success: function(res) {
				  		//console.log(res)
						
				  		that.currentAddress=res.result.formatted_addresses.recommend;
						//console.log(this.currentAddress)
						//this.$set(this, 'currentAddress', this.currentAddress)
				  	},
				  	 fail: function(res) {
				  	    console.log(res);
				  	},
				  })
			},
			tabClick(num) {
				this.tabIndex = num;
			},
			typeClick(num){
				this.typeIndex=num;
				if(num!=2){
					this.endLat='';
					this.endLng='';
					this.endAddress='';
					this.covers.splice(1,1);
				}
			}
		}
	}
</script>

<style scoped>
	.box {
		width: 100vw;
		min-height: 100vh;
		background-color: #FFFFFF;
	}

	map {
		width: 750rpx;
		height: calc(100vh - 664rpx - 120rpx);
	}

	.contBox {
		width: 100%;
		height: 664rpx;
	}

	.tab {
		background: #FFFFFF;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 230rpx;
		padding-right: 230rpx;
		height: 92rpx;
		line-height: 60rpx;
	}

	.tabLine {

		font-size: 30rpx;
		color: #333333;
		text-align: center;
        padding: 0 10rpx;
	}

	.tabActive {

		color: #FF0000;
		font-weight: bold;
		border-bottom: 4rpx solid #FF0000;

	}

	.timeBox {
		padding-top: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.time {

		color: #959595;
		font-size: 24rpx;

	}

	.typeBox {
		padding: 30rpx 30rpx;
		display: flex;
		justify-content: space-between;
	}

	.box2 {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background: #FFFFFF;
		height: 32rpx;
		border-radius: 10rpx;
		border: 2rpx solid #CCCCCC;
	}

	.typeImg {
		width: 34rpx;
		height: 34rpx;
		margin-right: 10rpx;
	}

	.title {
		height: 40rpx;
		font-size: 28rpx;
		font-weight: 400;
		color: #666666;
		line-height: 40rpx;
	}


	.price {
		padding-bottom: 30rpx;
		font-size: 24rpx;
		font-weight: 400;
		color: #D53533;
		text-align: center;
	}

	.shopBox {
		padding: 30rpx 24rpx;
		border-top: 1rpx solid #EEEEEE;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.left {
		display: flex;
		align-items: center;
	}
	.leftTitle{
		width: 56rpx;
		font-size: 28rpx;
		font-weight: 400;
		color: #666666;
		line-height: 40rpx;
		margin-left: 16rpx;
		margin-right: 30rpx;
	}

	.graypoint {
		width: 14rpx;
		height: 14rpx;
		background: #DDDDDD;
		border-radius: 7rpx;
	}

	.bluepoint {
		width: 14rpx;
		height: 14rpx;

		background: #3F90F7;
		border-radius: 7rpx;
	}

	.redpoint {
		width: 14rpx;
		height: 14rpx;

		background: #FF0000;
		border-radius: 7rpx;
	}
  .typeActive{
	
	  background: #FF0000;
  }
.typeActive .title{
	    color: #FFFFFF !important;
  }

	.bottomView {
		border-top: 1rpx solid #EEEEEE;
		background-color: #FFFFFF;
		width: 100%;
		height: 120rpx;
		position: fixed;
		bottom: 0rpx;
		/* padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom); */
	}
    .content{
		width: 540rpx;
		font-size: 30rpx;
		word-wrap: break-word; /*强制换行*/
		  overflow: hidden; /*超出隐藏*/
		  text-overflow: ellipsis;/*隐藏后添加省略号*/
		  white-space: nowrap;/*强制不换行*/
	}
	.Nocontent{
		font-size: 30rpx;
		color: #999999;
	}
	.sure {

		background-color: #D53533;
		margin: 23rpx 30rpx;
		height: 74rpx;

		border-radius: 37rpx;
		color: #FFFFFF;
		font-size: 30rpx;
		font-weight: bold;

		text-align: center;
		line-height: 74rpx;
	}
	.authorizBox{
				width: 100vw;
				height: 100vh;
				background: rgba(0, 0, 0, 0.5);
				position: fixed;
				top: 0;
				left: 0;
			}
			.authorizCont{
				margin-top: 30vh;
				width: 564rpx;
				height: 408rpx;
				background: #FFFFFF;
				border-radius: 24rpx;
				margin-left: 93rpx;
				position: relative;
			}
			.authorizCloseImg{
				width: 62rpx;
				height: 62rpx;
			}
			.sqLogoBox{
				width: 180rpx;
				height: 180rpx;
				background: #FFFFFF;
				border-radius: 90rpx;
				text-align: center;
				position: absolute;
				top: -50rpx;
				left: 192rpx;
			}
			.authorizName{
				color: #333333;
				line-height: 42rpx;
				font-size: 30rpx;
				text-align: center;
				padding-top: 58rpx;
			}
			.authorizMs{
				color: #999999;
				line-height: 36rpx;
				font-size: 26rpx;
				width: 452rpx;
				padding-top: 24rpx;
				text-align: center;
				margin-left: 56rpx;
			}
			.authorizContbutton{
				width: 210rpx;
				height: 66rpx;
				background: #D53533;
				border-radius: 44rpx;
				line-height: 66rpx;
				text-align: center;
				font-size:30rpx;
				color: #FFFFFF;
				
				margin-left:40rpx;
			}
			.sqRefuse{
				width: 210rpx;
				height: 66rpx;
				border: 1px solid #eaeaea;
				line-height: 66rpx;
				border-radius: 36rpx;
				text-align: center;
				font-size:30rpx;
				margin-right:40rpx;
				color: #999999;
			}
			.sqLine{
					margin-top: 62rpx;
				display: flex;
				justify-content: space-between;
			}
</style>
