<template>
	<view class="refuelDetail">
		<zs-header :background="background"></zs-header>
		<image class="banner" :src="info.logo" mode=""></image>
		<view class="content">
			<view class="title">
				{{info.storeName}}
			</view>
			<view class="time">
				营业时间 周一至周日  {{info.openTimeHourStart}}：00 - {{info.openTimeHourEnd}}：00
			</view>
			<view class="distance">
				距离您{{(distance/1000).toFixed(2)}}公里
			</view>
			<view class="address-box">
				<view class="address">
					{{info.address}}
				</view>
				
				<view class="btn-box">
					<view class="btn" @click="handleNavigation">
						导航
					</view>
					<view class="btn" @click="handleCall">
						电话
					</view>
				</view>
			</view>
			
			<view class="price-box">
				<view class="price">
					优惠加油 ¥{{price.vipPrice?(price.vipPrice/100).toFixed(2):'--'}}/L
				</view>
				<view class="right-box">
					<view class="old-price">
						油站价¥{{price.cityPrice?(price.storePrice/100).toFixed(2):'--'}}/L
					</view>
					<view class="old-price">
						国标价¥{{price.cityPrice?(price.cityPrice/100).toFixed(2):'--'}}/L
					</view>
				</view>
			</view>
			
			<view class="choose-box">
				<view class="item" :class="[num?'active':'']" @click="hanleChoose">
					 {{num||"请选择油号"}}
					<image class="icon" src="../static/shop-desc.png" mode=""></image>
				</view>
				<view class="item" :class="[gun?'active':'']" @click="hanleChoose">
					{{gun ? (gun + '号枪'):"请选择油枪"}}
					<image class="icon" src="../static/shop-desc.png" mode=""></image>
				</view>
			</view>
			<input class="price-input" type="digit" v-model="amount" placeholder-style="color:#AAAAAA;font-weight: 500;" placeholder="请输入加油金额，优惠价格计算" />
			<view class="order-box">
				<view class="item">
					<view class="label">
						订单金额
					</view>
					<view class="value-box">
						<view class="num">
							约{{(payInfo.litre/1000).toFixed(2)}}升
						</view>
						<view class="value">
							{{'￥'+ (payInfo.totalPrice/100).toFixed(2) }}
						</view>
					</view>
				</view>
				<view class="item">
					<view class="label">
						服务费
					</view>
					<view class="value" :class="[!payInfo.totalPrice?'gray':'']">
						{{payInfo.totalPrice?'￥'+(payInfo.serviceFee/100).toFixed(2) : '输入金额后查看服务费'}}
					</view>
				</view>
				<view class="item">
					<view class="label">
						优惠券减免金额
					</view>
					<view class="value" :class="[!payInfo.totalPrice?'gray':'']">
						{{payInfo.totalPrice?'￥'+(payInfo.promotionAmount/100).toFixed(2) : '输入金额后查看优惠金额'}}
					</view>
				</view>
				<view class="item">
					<view class="label">
						优惠券
					</view>
					<view class="value gray">
						{{payInfo.totalPrice?'暂无可用' : '输入金额后查看优惠券'}}
						
					</view>
				</view>
			</view>
			
		</view>

		<view class="buy-box">
			<view class="total-price">
				<view class="label">
					合计:
				</view>
				<view class="price">
					¥ {{(payInfo.realPrice/100).toFixed(2)}}
				</view>
			</view>
		
			<button class="btn" :class="[btnDisabled?'disabled':'']" type="default" :loading="loading" :disabled="btnDisabled" @click="handlePay">立即支付</button>
		</view>
		
		<u-popup :show="show" round="16rpx" mode="bottom" @close="close">
			<view class="popup-title">
				选择油号/油枪
			</view>
			<view class="item-box">
				<view class="sub-title">
					选择油号
				</view>
				<view class="box">
					<view class="item"  :class="[numIndex === index ?'active':'']" v-for="(item,index) in info.itemInfoList" :key="item.itemId" @click="handleTab(item,'',index)">
						{{item.itemName}}
					</view>
				</view>
			</view>
			
			<view class="item-box">
				<view class="sub-title">
					选择油枪 
					<view class="notice">
						请与加油员确认油枪号
					</view>
				</view>
				<view class="box">
					<view class="item" :class="[gun == item ?'active':'',(index+1)%4 == 0?'m0':'']" v-for="(item,index) in gunList" :key="item" @click="handleTab(item,'gun')">
						{{item}}号
					</view>
					
				</view>
			</view>
			
		</u-popup>
		
		<map class="map" id="map"></map>
		
	</view>
</template>

<script>
	import { queryStoreDetail,queryCalPrice,queryNewOrder } from '@/api/refuel.js';
	import {debounce} from '@/utils/tool.js'
	// 腾讯地图
	var QQMapWX = require('@/libs/qqmap-wx-jssdk.min.js');
	var qqmapsdk = new QQMapWX({key:'KX5BZ-B64RC-RO62W-AMWAZ-VVTC3-YAFXF'});
	export default {
		data() {
			return {
				type:1,
				background:false,
				map:null,
				show:false,
				loading:false,
				info:null,
				distance:0,
				itemId:'',//油号id
				num:'',//油号
				numIndex:undefined,//选择油号的index
				gun:'',//油枪
				price:{//选择的油号价格
					cityPrice:0,
					vipPrice:0,
					storePrice:0
				},
				storeId:'',
				amount:'',//输入金额
				payInfo:{//计算出来的金额
					discountPrice: 0,
					itemName: "",
					litre: 0,
					priceDetailVo: {deductionDetail: null, gunCoupon: null},
					promotionAmount: 0,
					realPrice: 0,
					serviceFee: 0,
					storeId: "",
					totalPrice: 0,
				},
				epId:'',//店铺id
			}
		},
		watch: {
			amount:debounce(function(val){
				if(!val){
					this.payInfo = {//计算出来的金额
						discountPrice: 0,
						itemName: "",
						litre: 0,
						priceDetailVo: {deductionDetail: null, gunCoupon: null},
						promotionAmount: 0,
						realPrice: 0,
						serviceFee: 0,
						storeId: "",
						totalPrice: 0,
					}
				}
				this.queryCalPrice()
				// else if(!this.num||!this.gun){
				// 	uni.showToast({
				// 		title:'请选择油号/油枪',
				// 		icon:'none'
				// 	})
				// }else if(val<10){
				// 	uni.showToast({
				// 		title:'加油金额不能小于10',
				// 		icon:'none'
				// 	})
				// }
			})
		},
		computed: {
			btnDisabled(){
				if(!this.payInfo.realPrice || !this.num || !this.gun || this.loading || this.amount<10){
					return true
				}else{
					return false
				}
			},
			gunList() {
				if(this.numIndex == undefined){
					return []
				}else{
					return this.info.itemInfoList[this.numIndex].gunNoList
				}
			},
			query(){
				return {
					amount:this.amount*100,
					itemName :this.num,
					storeId:this.storeId,
				}
			},
			notice(){
				if(this.amount&&this.amount<10){
					return uni.showToast({
							title:'加油金额不能小于10',
							icon:'none'
						})
				}else if(!this.num||!this.gun){
					return uni.showToast({
								title:'请选择油号/油枪',
								icon:'none'
							})
				}else if(!this.amount){
					return uni.showToast({
								title:'请输入加油金额',
								icon:'none'
							})
				}
				else if(this.amount>999){
					this.amount = 999
					return uni.showToast({
								title:'加油最大金额999',
								icon:'none'
							})
				}
			}
		},
		methods: {
			handleTab(item,type,index){
				if(type == 'gun'){
					this.gun = item
					this.show = false
				}else{
					this.gun = ''
					this.numIndex = index
					this.itemId = item.itemId
					this.num = item.itemName
					this.price.cityPrice = item.cityPrice
					this.price.vipPrice = item.vipPrice
					this.price.storePrice = item.storePrice
				}
				this.queryCalPrice()
					
			},
			handleNavigation() {
				uni.openLocation({
							latitude: this.info.lat,
							longitude: this.info.lon,
							name:this.info.storeName,
							address:this.info.address,
							success: function () {
								console.log('success');
							}
						});
				// this.map.openMapApp({
				// 	longitude:this.info.lon,
				// 	latitude:this.info.lat,
				// 	destination:this.info.storeName,
				// 	success(res){
				// 		console.log(res);
				// 	}
				// }) 
			},
			handleCall() {
				if(this.info.tel){
					uni.makePhoneCall({
						phoneNumber: this.info.tel //仅为示例
					});
				}else{
					uni.showToast({
						title:'商家没有预留电话',
						icon:'none'
					})
				}
			},
			hanleChoose(){
				this.show = true
			},
			close(){
				this.show = false
			},
			// 加油站详情
			queryStoreDetail(storeId){
				queryStoreDetail(storeId).then(res=>{
					this.info = res.content
					this.getDistance()
					this.info.itemInfoList.map((item,index)=>{
						if(item.itemName == '92#'){
							this.numIndex = index
							this.itemId = item.itemId
							this.num = item.itemName
							this.price.cityPrice = item.cityPrice
							this.price.vipPrice = item.vipPrice
							this.price.storePrice = item.storePrice
						}
					})
				})
			},
			queryCalPrice(){
				if(this.num&&this.gun&&this.amount>=10){
					uni.showLoading({
						title:'计算中'
					})
					queryCalPrice(this.query).then(res=>{
						uni.hideLoading()
						if(res.state == 'Success'){
							this.payInfo = res.content
						}
					})
				}
			},
			getDistance(){
				let location = JSON.parse(uni.getStorageSync('location'))
				qqmapsdk.calculateDistance({from:{latitude:location.latitude,longitude:location.longitude},to:[{latitude:this.info.location[1],longitude:this.info.location[0]}],success:(res)=>{
					console.log(res);
					this.distance = res.result.elements[0].distance
				}})
			
			},
			getRad(d) {
			    return d * Math.PI / 180.0;
			},
			/*参数：两地的经纬度数值*/
			getFlatternDistance(lat1, lng1, lat2, lng2) {
			    var radLat1 = this.getRad(lat1);
			    var radLat2 = this.getRad(lat2);
			    var a = radLat1 - radLat2;
			    var b = this.getRad(lng1) - this.getRad(lng2);
			    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			    s = s * 6378137.0;//地球半径 单位米;
			    s = Math.round(s * 10000) / 10000; //输出为米
			    s = s.toFixed(0)
			    return s
			},
			handlePay(){
				let that = this
				let location = JSON.parse(uni.getStorageSync('location'))
				console.log('不能超过（米）：',this.amount*1000,'距离加油站（米）：',this.getFlatternDistance(location.latitude,location.longitude,this.info.lat,this.info.lon))
				if(this.getFlatternDistance(location.latitude,location.longitude,this.info.lat,this.info.lon)>1000){
					return uni.showModal({
						title:'提示',
						content:'您当前距离加油站较远，请到达加油站后与加油员确定信息',
						confirmText:'刷新位置',
						success: function (res) {
							if (res.confirm) {
								uni.showLoading({
									title:'刷新中'
								})
								uni.getLocation({
										type: 'gcj02',
										success: (res) => {
											// 存储经纬度
											uni.setStorageSync('location',JSON.stringify({latitude:res.latitude,longitude:res.longitude}))
											uni.hideLoading()
											that.getDistance()
										}
								})
							}
						}
					})
				}
				this.loading = true
				let query = {
					"channel":'ZhongShu',
					  "epId": this.epId,
					  "itemName":this.num,
					  "gunNo": this.gun,
					  "itemId": this.itemId,
					  "litre": this.payInfo.litre,
					  "openExtra": "",
					  "originalAmount": this.payInfo.totalPrice,
					  "outNewUserFlag": "",
					  "paymentAmount":  this.payInfo.realPrice,
					  "promotionInfo": [
					    {
					      "allowanceId": "string",
					      "allowanceType": 0
					    }
					  ],
					  "serviceFee": this.payInfo.serviceFee,
					  "storeId":this.storeId,
					  "storePrice": this.price.storePrice,
					  "vipPrice": this.price.vipPrice
				}
				queryNewOrder(query).then(res=>{
					this.loading = false
					if(res.state == 'Success'){
						uni.navigateToMiniProgram({
							 appId:"wx0d252f6ed9755862", // 滴滴加油小程序appId
							   path: `packageA/pages/open-energy-pay/index?orderId=${res.content.xjOrderId}&tradeId=${res.content.tradeId}`, // 滴滴加油收银台页面地址，需要拼接orderId和tradeId
							   envVersion: 'release' // 固定release
						})
					}
				})
			}
		},
		onPageScroll(e) {
				if (e.scrollTop >= 50) {
					this.background = true
				} else {
					this.background = false
				}
		},
		onReady() {
			this.map = uni.createMapContext("map", this);
		},
		onShow() {
			if(!this.btnDisabled){
				uni.reLaunch({
					url:'/my/order/index'
				})
			}
		},
		onLoad(options) {
			this.epId = options.epId
			// '5154031457384536897'
			this.storeId = options.id
			this.queryStoreDetail(options.id)
			
		}
	}
</script>

<style lang="scss" >
.refuelDetail{
	.banner{
		width: 100%;
		height: 382rpx;
	}
	.content{
		margin-top: -20rpx;
		min-height: 500rpx;
		border-radius: 16rpx 16rpx 0 0;
		position: relative;
		z-index: 2;
		background: #fff;
		padding: 28rpx 24rpx;
		.title{
			font-weight: 600;
			font-size: 32rpx;
			color: #222222;
		}
		.time{
			font-weight: 300;
			font-size: 24rpx;
			color: #AAAAAA;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #F0F0F0;
		}
		.distance{
			font-weight: 300;
			font-size: 24rpx;
			color: #AAAAAA;
			padding: 20rpx 0;
		}
		.address-box{
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 702rpx;
			height: 140rpx;
			background-image: url('@/static/white-map.png');
			background-repeat: repeat;
			background-size: 100% 140rpx;
			box-sizing: border-box;
			padding: 36rpx 24rpx;
			.address{
				font-weight: 600;
				font-size: 24rpx;
				color: #222222;
				line-height: 40rpx;
				overflow: hidden;
				padding-right: 20rpx;
				text-overflow: ellipsis;
				/* 弹性伸缩盒子模型显示 */
				display: -webkit-box;
				/* 限制在一个块元素显示的文本的行数 */
				-webkit-line-clamp: 2;
				/* 设置或检索伸缩盒对象的子元素的排列方式 */
				-webkit-box-orient: vertical;
			}
			.btn-box{
				display: flex;
				.btn+.btn{
					margin-left: 16rpx;
				}
				.btn{
					width: 120rpx;
					height: 52rpx;
					line-height: 52rpx;
					text-align: center;
					background: #E2ECFF;
					border-radius: 26rpx 26rpx 26rpx 26rpx;
					font-weight: 300;
					font-size: 28rpx;
					color: #3879F9;
				}
			}
		}
		.price-box{
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0;
			.price{
				font-weight: 600;
				font-size: 28rpx;
				color: #222222;
			}
			.right-box{
				display: flex;
				align-items: center;
				.old-price{
					font-weight: 300;
					font-size: 24rpx;
					color: #AAAAAA;
					margin-left: 20rpx;
				}
			}
		}
		.choose-box{
			display: flex;
			justify-content: space-between;
			.item{
				width: 340rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background: #F0F0F0;
				border-radius: 8rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #222222;
				position: relative;
				.icon{
					width: 32rpx;
					height: 32rpx;
					position: absolute;
					top: 50%;
					right: 24rpx;
					transform: translateY(-50%);
				}
			}
			.item.active{
				background: #FFF6F5;
				color: #FF4D3A;
			}
		}
		.price-input{
			width: 702rpx;
			height: 120rpx;
			line-height: 120rpx;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			border: 2rpx solid #AAAAAA;
			font-weight: bold;
			font-size: 32rpx;
			color: #222;
			padding: 28rpx;
			box-sizing: border-box;
			margin-top: 20rpx;
		}
		
		.order-box{
			.item{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #F0F0F0;
				.label{
					font-weight: 300;
					font-size: 28rpx;
					color: #222222;
				}
				.value-box{
					display: flex;
					align-items: center;
					.num{
						font-weight: 300;
						font-size: 28rpx;
						color: #AAAAAA;
					}
				}
				.value{
					font-weight: 300;
					font-size: 28rpx;
					color: #222222;
					margin-left: 20rpx;
				}
				.gray{
					color: #AAAAAA!important;
				}
			}
		}
		
	}
	.buy-box {
		position: fixed;
		bottom: 0%;
		left: 0%;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 10rpx 30rpx env(safe-area-inset-bottom);
		border-top: 1rpx solid #EEEEEE;
	
		.total-price {
			display: flex;
			align-items: center;
	
			.label {
				color: #181818;
				font-size: 28rpx;
			}
	
			.price {
				font-size: 36rpx;
				font-weight: 800;
				color: #222222;
				margin-left: 10rpx;
			}
		}
	
		.btn {
			width: 280rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: $uni-color-primary;
			box-shadow: inset 0rpx 6rpx 12rpx 2rpx rgba(255, 255, 255, 0.16);
			border-radius: 46rpx 46rpx 46rpx 46rpx;
			font-weight: 800;
			color: #FFFFFF;
			font-size: 28rpx;
			margin: 0;
		}
		.btn.disabled{
			filter: grayscale(1);
		}
	}
	
	.map{
		position: absolute;
		top: -9999rpx;
		left: -9999rpx;
	}
	
	.u-popup__content{
		padding: 28rpx 24rpx;
		background: #F9F9F9 !important;
		.popup-title{
			font-weight: 600;
			font-size: 32rpx;
			color: #222222;
		}
		.item-box{
			width: 100%;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin-top: 20rpx;
			padding: 24rpx;
			box-sizing: border-box;
			
			.sub-title{
				font-weight: 600;
				font-size: 28rpx;
				color: #222222;
				margin-bottom: 20rpx;
				display: flex;
				align-items: flex-end;
				.notice{
					font-weight: 300;
					font-size: 24rpx;
					color: #AAAAAA;
					margin-left: 20rpx;
				}
			}
			.box{
				display: flex;
				flex-wrap: wrap;
				max-height: 600rpx;
				overflow: auto;
				.item{
					width: 148rpx;
					height: 52rpx;
					line-height: 52rpx;
					text-align: center;
					background: #F0F0F0;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #222222;
					margin-bottom: 20rpx;
					margin-right: 20rpx;
				}
				.item.active{
					background: #FFF6F5;
					color: #EE4320;
				}
				.item.m0{
					margin-right: 0!important;
				}
			}
		}
	}
}
</style>