<template>
	<div class='guidecar'>
		<scroll-view
			
			 :scroll-y="true"
			@scroll="scrollHandler"
			@scrolltoupper="scrollTopHandler"
			style="min-height: 100vh;">
				<view 
				:style="{ 'background-image': 'url(' + (info.Background ? info.Background : '') + ')', backgroundSize: '100% 500rpx' }"
				
				 class="topbox">
					<view class="headStatus" :style="[headStyle]" >
					  <view class="arrow" @click="redirectPrev">
						<u-icon name="arrow-left" size="48" color="#fff"></u-icon>
					  </view>
					  <view class="title" >司导专区</view>
					  <view class="arrow" ></view>
					</view>
				</view>
				<view class="content">
					<view class="content_box">
						<view class="c_row">
							<view class="topB" v-if="info.IsShowCity==1" @click="gocity">
								<span class='titext'>城市</span>
								<view style="display: flex;flex-direction: row;align-items: center;">
									<span class='ztext'>{{Pickcar}}</span><u-icon name="arrow-down" size="28" color="#C8C8C8"></u-icon>
								</view>
							</view>
							<view class="topB" style="width: 150px;align-items: flex-start;" v-if="info.IsShowAddress==1" @click="openmap">
								<span class='titext'>接送位置</span>
								<span class='ztext' style='width: 100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' v-if="address!=''">{{address}}</span>
								<span class='ztext' style='color: #E2E2E2;' v-if="address==''">请选择</span>
							</view>
							<view class="topB" v-if="info.IsShowCarpooling==1&& msg.CarType==5" style="align-items: center;">
								<span class='titext'>是否拼车</span>
								<u-switch v-model="Ischecked" size='30' @change='goIsSpell'></u-switch>
							</view>
						</view>
						<view class="c_row">
							<view class="topB" v-if="info.IsShowGuideCarGoodsType==1" @click="show2 = true">
								<span class='titext'>出行类型</span>
								<view style="display: flex;flex-direction: row;align-items: center;">
									<span class='ztext' :style="{'color':msg.CarType==''?'#E2E2E2':'#1C1E1F'}">{{EnumName}}</span><u-icon name="arrow-down" size="28" color="#C8C8C8"></u-icon>
								</view>
							</view>
							<view class="topB" v-if="info.IsShowCarClass==1" @click="show=true">
								<span class='titext'>车辆类型</span>
								<view style="display: flex;flex-direction: row;align-items: center;">
									<span class='ztext' style='color: #1C1E1F;'>{{carName}}</span><u-icon name="arrow-down" size="28" color="#C8C8C8"></u-icon>
								</view>
							</view>
							<view class="topB" v-if="info.IsShowTravelGuestNum==1" style="align-items: center;">
								<span class='titext'>出行人数</span>
								<input class="uni-input" v-model="msg.RideNum" style="width: 50px;text-align: center;"/>
							</view>
						</view>
						<view class="c_row"  v-if="msg.CarType==5">
							<view class="topB"  >
								<span class='titext'>线路名称</span>
								<input class="uni-input" v-model="msg.LineName" style="width: 80px;" placeholder="请输入"/>
							</view>
							<view class="topB" >
								<span class='titext'>关联城市或景点</span>
								<input class="uni-input" v-model="msg.LineDescription" style="width: 80px;" placeholder="请输入"/>
							</view>
							<view class="topB" style="width: 50px;"></view>
						</view>
						<view class="c_row" v-if="info.IsShowDate==1">
							<view class="topB" @click="showStart=true,timeType=1,defaultTime = msg.StartTime">
								<span class='ztext'>{{STime.month}}月{{STime.day}}日</span>
								<span class='titext'>{{STime.week+' '+STime.hour+':'+STime.minute}}</span>
							</view>
							<view class="topB" style="height: 20px;align-items: center;">
								<span style='font-size: 11px;color: #1C1E1F;'>{{intervalDay}}</span>
								<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/sanjiao.png" mode="aspectFill" style="width: 55px;height: 4px;"></image>
								
							</view>
							<view class="topB" @click="showStart=true,timeType=2,defaultTime = msg.EndTime">
								<span class='ztext'>{{ETime.month}}月{{ETime.day}}日</span>
								<span class='titext'>{{ETime.week+' '+ETime.hour+':'+ETime.minute}}</span>
							</view>
						</view>
						<view class="c_row_t">
							<image :src="info.TipsIco" mode="aspectFill" style="width: 15px;height: 13px;"></image>
							<span style='font-size: 12px;color: #121212;margin-left: 5px;'>{{info.Tips}}</span>
						</view>
						<view class="btnstyle" :style="{'color':info.ButtonTextColor,'background':info.ButtonColor,'border-radius':info.ButtonFilletPX+'px'}" @click="goList">
							{{info.ButtonText?info.ButtonText:''}}
						</view>
					</view>
				</view>
			</scroll-view>
			<u-popup v-model="show"
					mode="bottom"
					border-radius="16"
					>
				<view class="popupBox">
					<view class="popup_top">
						<view></view>
						<Text>车辆类型</Text>
						<u-icon name="cross" color='#9F9F9F' @click='show=false' size="40"></u-icon>
					</view>
					<scroll-view
					:scroll-y="true"
					style="max-height: 420px;">
						<view class="txtype">
							<view class="typeitem" v-for="(item, index) in classList" :key="index" @click="radioChange(item)">
									<Text>{{item.Name}}</Text>
									<u-radio-group  v-model="carName">
										<u-radio 
											v-model = 'item.checked'
											active-color="#EE4454"
											shape="circle"
											:name="item.Name"
										>
										</u-radio>
									</u-radio-group>
								</view>
						</view>
					</scroll-view>
					
				</view>
			</u-popup>
			<u-popup v-model="show2"
					mode="bottom"
					border-radius="16"
					>
				<view class="popupBox">
					<view class="popup_top">
						<view></view>
						<Text>出行类型</Text>
						<u-icon name="cross" color='#9F9F9F' @click='show2=false' size="40"></u-icon>
					</view>
					<scroll-view
					:scroll-y="true"
					style="max-height: 420px;">
						<view class="txtype">
							<view class="typeitem" v-for="(item, index) in EnumList" :key="index" @click="radioChange2(item)">
									<Text>{{item.Name}}</Text>
									<u-radio-group  v-model="EnumName">
										<u-radio 
											v-model = 'item.Id'
											active-color="#EE4454"
											shape="circle"
											:name="item.Name"
										>
										</u-radio>
									</u-radio-group>
								</view>
						</view>
					</scroll-view>
				</view>
			</u-popup>
			<u-picker v-model="showStart" mode="time" :params="params" @confirm='btnStart' :default-time='defaultTime'></u-picker>
	</div>
</template>

<script>
	import AddressParse from '../address/zh-address-parse.min.js'
	import amap from './components/amap-wx.js'
	export default{
		data(){
			return{
				info:{},
				contentHeight: 0,
				mainColor:'',
				scrollTop:0,
				headStyle:{},
				nav:0,
				iscarpool:false,
				classList:[],
				EnumList:[],
				EnumName:'请选择',
				show:false,
				show2:false,
				carName:"请选择",
				value:'',
				defaultTime:'',
				showStart:false,
				Pickcar:'成都',//取车城市
				STime:{},//显示的出行时间
				ETime:{},//显示的结束时间
				intervalDay:'',//间隔天数
				address:'',//详情地址
				Ischecked:false,
				msg:{
					StartTime:'',//取车时间
					EndTime:'',//还车时间
					CarType:0,//服务类型
					LineName:'',//线路名称
					LineDescription:'',//关联城市/景点
					RideNum:1,//出行人数
					CarClass:0,//车辆类型
					RegionIds:0,//地区（省市区：1,2,3）
					IsSpell:2,//是否拼座 1是 2否
				},
				params: {//时间的配置
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
				},
				amapPlugin:null,
				key: 'c785085c46d1eb41b1ebe8d1ec7fd945',
				latitude:'',
				longitude:'',
				
			}
		},
		created() {
		  this.contentHeight = this.$utils.calcContentHeight(-40) + "px";
		  this.mainColor = this.$uiConfig.mainColor;
		  this.nav = uni.getMenuButtonBoundingClientRect().top;
		  this.headStyle.paddingTop = this.nav +'px';
		  let myDate = new Date();
		  myDate=myDate.setDate(myDate.getDate()+1);
		   myDate=new Date(myDate);
		  let obj = {}
		   obj.year = myDate.getFullYear(); //年
			obj.month = myDate.getMonth() + 1; //月
			obj.day = myDate.getDate(); //日
			obj.hour =  (myDate.getHours()<10)?"0"+myDate.getHours() : myDate.getHours(); //时
			obj.minute = (myDate.getMinutes()<10)?"0"+myDate.getMinutes() : myDate.getMinutes(); //分
			let day = myDate.getDay();
			obj.week = this.getweek(day)//星期几
			this.STime = obj;
			this.ETime = obj;
			this.msg.StartTime = obj.year+'/'+obj.month+'/'+obj.day+' '+obj.hour+':'+obj.minute+':00';
			this.msg.EndTime = obj.year+'/'+obj.month+'/'+obj.day+' '+obj.hour+':'+obj.minute+':10';
			
			let startTime = new Date(this.msg.StartTime); // 开始时间
			let endTime = new Date(this.msg.EndTime); // 结束时间
			let usedTime = endTime - startTime; // 相差的毫秒数
			let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
			let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
			let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
			if(days>0){
				if(leavel>0){
					this.intervalDay=days+1+'天'
				}else{
					this.intervalDay=days+'天'
				}
			}else{
				if(hours>=6){
					this.intervalDay='1天'
				}else{
					this.intervalDay='半天'
				}
			}
		},
		onLoad(options){
			this.init()//获取司导首页配置
			this.getCarClassList()//车辆分类下拉
			this.getOrderListExportEnumList()//获取出行类型
			this.amapPlugin = new amap.AMapWX({  
				key: this.key  
			});  
			// this.getRegeo()
		},
		methods:{
			 getRegeo() {  //进入页面获取当前地址位置
				// uni.showLoading({  
				// 	title: '获取信息中'  
				// });  
				this.amapPlugin.getRegeo({  
					
					success: (data) => {  
					   this.Pickcar = data[0].regeocodeData.addressComponent.city;
					}  
				});  
			} ,
			init(){
				uni.showLoading({
				  title: "加载中",
				});
				this.request2(
				  {
				    url: "/api/AppletGuideCar/GetGuideCarSearchInfo",
				    data: {},
				  },
				  (res) => {
				    uni.hideLoading();
					this.info = res.data
				  }
				);
			},
			getCarClassList(){
				this.request2(
				  {
				    url: "/api/AppletGuideCar/GetCarClassList",
				    data: {},
				  },
				  (res) => {
					this.classList = res.data
					let obj = {Name: "不限", Id: 0}
					this.classList.unshift(obj)
					this.classList.forEach(x=>{
						x.checked = false
					})
					this.carName = this.classList[0].Name;
					this.msg.CarClass = this.classList[0].Id;	
					this.classList[0].checked = true
				  }
				);
			},
			getOrderListExportEnumList(){
				this.request2(
				  {
				    url: "/api/AppletGuideCar/GetOrderListExportEnumList",
				    data: {},
				  },
				  (res) => {
					this.EnumList = res.data
					this.EnumList.forEach(x=>{
						x.checked = false
					})
					this.EnumName = this.EnumList[0].Name;
					this.msg.CarType = this.EnumList[0].Id;
					this.EnumList[0].checked = true
				  }
				);
			},
			getPickcar(Name){//选择取消地址
				this.Pickcar = Name
				// this.request2(
				//   {
				//     url: "/api/AppletGuideCar/GetLngAndLat",
				//     data: {Address:Name},
				//   },
				//   (res) => {
				// 	this.latitude = res.data.lng;
				// 	this.longitude = res.data.lat;
				//   }
				// );
			},
			radioChange(item){//车辆类型
				this.carName = item.Name;
				this.msg.CarClass = item.Id;	
				this.show=false
			},
			radioChange2(item){//出行类型
				this.EnumName = item.Name;
				this.msg.CarType = item.Id;	
				this.show2=false
			},
			scrollHandler(e) {
			  this.scrollTop = e.detail.scrollTop;
			  //this.$forceUpdate();
			},
			scrollTopHandler() {
			  this.scrollTop = 0;
			},
			redirectPrev() {
				uni.navigateBack({
			      delta: 1,
			   });
			},
			goIsSpell(val){
				if(val==true){
					this.msg.IsSpell=1
				}else{
					this.msg.IsSpell=2
				}
			},
			btnStart(val){
				if(this.timeType ==1){//出行时间的选择
					this.msg.StartTime = val.year+'/'+val.month+'/'+val.day+' '+val.hour+':'+val.minute+':00';
					this.STime = val
					let myDate = new Date(this.msg.StartTime);
					let days = myDate.getDay();
				    this.STime.week = this.getweek(days)
				}else{//结束时间的选择
					this.msg.EndTime = val.year+'/'+val.month+'/'+val.day+' '+val.hour+':'+val.minute+':10';
					this.ETime = val
					let myDate = new Date(this.msg.EndTime);
					let days = myDate.getDay();	
					this.ETime.week = this.getweek(days)
				}
				let startTime = new Date(this.msg.StartTime); // 开始时间
				let endTime = new Date(this.msg.EndTime); // 结束时间
				console.log(startTime.getTime(),endTime.getTime())
				if(startTime.getTime()>endTime.getTime()){//如果开始时间大于结束时间吧结束时间赋值和开始时间一样
					this.msg.StartTime=  val.year+'/'+val.month+'/'+val.day+' '+val.hour+':'+val.minute+':00';
					this.msg.EndTime=  val.year+'/'+val.month+'/'+val.day+' '+val.hour+':'+val.minute+':10';
					this.STime = val
					this.ETime = val
					let myDate = new Date(this.msg.EndTime);
					let days = myDate.getDay();
					this.STime.week = this.getweek(days)
					this.ETime.week = this.getweek(days)
					this.intervalDay ='半天'
				}else{
					let usedTime = endTime - startTime; // 相差的毫秒数
					let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
					let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
					let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数

					if(days>0){
						if(leavel>0){
							this.intervalDay=days+1+'天'
						}else{
							this.intervalDay=days+'天'
						}
					}else{
						if(hours>=6){
							this.intervalDay='1天'
						}else{
							this.intervalDay='半天'
						}
					}
				}
				
				
			},
			getweek(day){//根据值返回当前时间的星期几
				if(day==1){
					return '星期一'
				}else if(day==2){
					return '星期二'
				}else if(day==3){
					return '星期三'
				}else if(day==4){
					return '星期四'
				}else if(day==5){
					return '星期五'
				}else if(day==6){
					return '星期六'
				}else if(day==0){
					return '星期日'
				}
			},
			openmap(){//打开地图选择详情地址
			let that = this
			wx.getSetting({
			        success(res) {
			          console.log('res是否开启授权', res)
			          if (!res.authSetting['scope.userLocation']) { 
			            wx.authorize({
			              scope: 'scope.userLocation',  
			              success() {
			                // console.log('前用户发起授权请求')
							if(that.latitude!='' && that.longitude!=''){
								that.getYLocation()
							}else{
								that.getNLocation()
							}
			                
			              },
			              fail() {
			                // 用户点击不允许引导重新获取授权
							console.log('111')
			                that.fetchAgainLocation()
			              }
			            })
			          } else {
			             // 已经授权了就会直接进入地图
						
						  if(that.latitude!='' && that.longitude!=''){
							that.getYLocation()
						  }else{
							that.getNLocation()
						  }
			          }
			        }
			      })
			
		
			},
			fetchAgainLocation(){
				
				let that = this
				   wx.getSetting({
				     success: (res) => {
									  console.log(res)
				       var statu = res.authSetting;
				       if (!statu['scope.userLocation']) {
				         wx.showModal({
				           title: '是否授权当前位置',
				           content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
				           success: (tip) => {
				             if (tip.confirm) {
				               wx.openSetting({
				                 success: (data) => {
				                   if (data.authSetting["scope.userLocation"] === true) {
				                     wx.showToast({
				                       title: '授权成功',
				                       icon: 'success',
				                       duration: 1000
				                     })
				                     	if(that.latitude!='' && that.longitude!=''){
				                     		that.getYLocation()
				                     	}else{
				                     		that.getNLocation()
				                     	}
				                   } else {
				                     wx.showToast({
				                       title: '授权失败',
				                       icon: 'success',
				                       duration: 1000
				                     })
				                   }
				                 },
				                 fail: () => {},
				                 complete: () => {}
				               });
				             }
				           }
				         })
				       }
				     },
				     fail: ()=>{},
				     complete: ()=>{}
				   })
			},
			getYLocation(){
				console.log('you')
				let that = this
				uni.chooseLocation({
					longitude:that.longitude,
					latitude:that.latitude,
				    success: function (res) {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						that.address  = res.address
						let parseResult = AddressParse(that.address, 0)
						let nameList = [parseResult.province, parseResult.city, parseResult.area];
						that.getDestination(nameList);
				    }
				});
			},
			getNLocation(){
				console.log('no')
				let that = this
				uni.chooseLocation({
				    success: function (res) {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						that.address  = res.address
						let parseResult = AddressParse(that.address, 0)
						let nameList = [parseResult.province, parseResult.city, parseResult.area];
						that.getDestination(nameList);
				    }
				});
			},
			getDestination(nameList) {
				this.request2(
					{
						url: '/api/AppletGuideCar/GetDestinationListByNames',
						data: {
							area: nameList
						}
					},
			
					res => {
						if(res.data.length==3){
							this.msg.RegionIds = res.data[0].ID+','+res.data[1].ID+','+res.data[2].ID
						}else{
							this.msg.RegionIds = res.data[0].ID+','+res.data[1].ID+',0'
						}
					}
				);
			},
			gocity(){
				uni.navigateTo({
					url:'/pages/guidecar/pickcarcity'
				})
			},
			
			goList(){
				
				let that = this
				let msg = that.msg
				if(msg.RegionIds==0){
					uni.showToast({
						title: "接送地址不能为空",
						icon: "none"
					  });
					return false
				}
				let tic= 0;
				that.classList.forEach((x,i)=>{
					if(x.Id == msg.CarClass){
						tic = i
					}
				})
				uni.navigateTo({
				  url: "/pages/guidecar/guidecarList?item=" + encodeURIComponent(JSON.stringify(msg))+'&tic='+tic+'&address='+that.address+'&Pickcar='+that.Pickcar
				});
			}
		}
	}
</script>

<style>
	.guidecar {
	  width: 100%;
	  height: 100%;
	  background: #FFFFFF;
	}
	.guidecar .headStatus {
		  overflow: hidden;
		  position: relative;
		  width: 140vw;
		  padding-right: 40vw;
		  padding-bottom: 10px;
		  position: fixed;
		  left: 0;
		  right: 0;
		  top: 0;
		  display: flex;
		  flex-direction: row;
		  align-items: center;
		  justify-content: space-between;
		 
	}
	.guidecar .arrow {
	  height: 24px;
	  margin: 5px 10px;
	  width: 24px;
	}
	.guidecar .headStatus .title {
	  font-size: 16px;
	  color: #FFF;
	  line-height: 34px;
	}
	.guidecar .topbox{
		width: 100%;
		height: 500rpx;
	}
	.guidecar .content{
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: -50px;
		padding: 10px 0;
		
	}
	.guidecar .content_box{
		width: 92%;
		border-radius: 7px;
		background: #FFFFFF;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 15px;
		box-shadow:0 2px 2px 2px #FBF4F2;
		
	}
	.guidecar .c_row{
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 15px 0;
		border-bottom: 1px solid rgba(0, 0, 0, 0.03);
		
	}
	.guidecar .c_row_t{
		width: 100%;
		display: flex;
		flex-direction: row;
		
		padding: 15px 0;
	}
	.guidecar .topB{
		display: flex;
		flex-direction: column;
		height: 45px;
		justify-content: space-between;
		/* align-items: center; */
	}
	.guidecar .titext{
		font-size: 22rpx;
		color: #929292;
	}
	.guidecar .ztext{
		font-size: 28rpx;
		color: #1C1E1F;
		font-weight: bold;
	}
	.guidecar .btnstyle{
		width: 100%;
		height: 44px;
		margin-top: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow:0 2px 2px 2px #FBCED2;
	}
	.guidecar .popupBox{
		width: 100%;
		padding-bottom: 15px;
		max-height: 500px;
	}
	.popupBox .popup_top{
		width: 100%;
		height: 45px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		
	}
	.popupBox .txtype{
		
	}
	.guidecar .typeitem{
		padding: 15px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		border-top:1px solid #f5f5f5
	}
</style>
