<template>
	<view class="payOrder">
		<mNavbar title="确认订单" :leftClick="leftClick" />

		<view class="bac"></view>

		<view class="box">
			<view class="server-item">
				
				<view class="img-box">
					<image :src="projectDetail.image" mode="aspectFill"></image>
				</view>
				
				<view class="server-info">
					
					<view class="server-title">{{ projectDetail.title }}</view>
					
					<view class="time-coupon">
						<image src="@/static/home/time-icon.png"></image>
						<view class="time">{{ projectDetail.times }}分钟</view>
					</view>
					
					<!-- <view class="price">
						<view class="current-price">
							<text class="unit">￥</text>299
						</view>
						<view class="original-price">
							<text class="unit">￥</text>399
						</view>
					</view> -->
					<!-- <view class="coupon">{{ projectDetail.subTitle }}</view> -->
					<view class="sales-volume">
						<image src="@/static/icons/icon1.png"></image>
						<view class="desc">已售出 {{ projectDetail.payNum }}+ 单</view>
					</view>
					
				</view>
			</view>

			<van-cell-group>
				<van-cell title="请选择地址" is-Link @click="selectAddressPopupShow = true"
					:value="(address.name + address.phone + address.addressDetail) || ''">
					<template #icon>
						<image class="icon" src="../../static/payOrder/7.png" mode="aspectFill"></image>
					</template>
				</van-cell>

				<van-cell title="服务技师">

					<text style="color: #4899a6;">{{ technicianDetail.title }}</text>

					<template #icon>
						<image class="icon" src="../../static/payOrder/1.png" mode="aspectFill"></image>
					</template>
					
				</van-cell>

				<van-cell title="服务时间" is-Link @click="onServiceTime">
					
					<text style="color: #4899a6;">
						{{ time.timeName ? (dateObj.format('MM-DD') + ' ' + time.timeName) : '' }}
					</text>
					
					<template #icon>
						<image class="icon" src="../../static/payOrder/3.png" mode="aspectFill"></image>
					</template>
					
				</van-cell>

				<van-cell title="出行方式">
					<text style="color: #fff;
					background-color: #6fc6ad;
					padding: 5px 10px;
					border-radius: 5px;
					font-size: 12px;">出租车</text>
					<template #icon>
						<image class="icon" src="../../static/payOrder/2.png" mode=""></image>
					</template>
				</van-cell>
				
			<!-- 	<van-cell title="出行费用">
					<text>￥{{ temp }}</text>
					<template #icon>
						<image class="icon" src="../../static/payOrder/2.png" mode="aspectFill"></image>
					</template>
				</van-cell> -->

				<view class="mileage">
					<view class="top">
						全程共
						<text style="color: #4899a6;
						font-size: 16px;">{{ distance || 0}}</text>
						公里
					</view>
					<view class="info">
						2公里内免费 超过2公里每公里{{ travelMoney }}元
					</view>
				</view>

				<van-cell title="订单备注" is-Link @click="remarkShow = true">
					<text>{{ remark || '选填' }}</text>
					<template #icon>
						<image class="icon" src="../../static/payOrder/4.png" mode=""></image>
					</template>
				</van-cell>
			</van-cell-group>

			<van-cell-group style="margin-top: 10px;">
				<van-radio-group v-model="payMethod">

					<van-cell>
						<template #title>
							<text>账户余额</text>
							<text style="color: #888;">（余额：￥{{ userInfo.price }}）</text>
						</template>
						<template #icon>
							<image class="icon" src="../../static/payOrder/5.png" mode=""></image>
						</template>
						<template #right-icon>
							<van-radio :name="1"></van-radio>
						</template>
					</van-cell>

					<van-cell title="微信支付">

						<template #icon>
							<image class="icon" src="../../static/payOrder/9.png" mode=""></image>
						</template>
						
						<template #right-icon>
							<van-radio :name="0"></van-radio>
						</template>
						
					</van-cell>

				</van-radio-group>

			</van-cell-group>

			<van-cell-group style="margin-top: 10px;">
				
				<van-cell title="优惠劵" is-Link @click="selectCouponPopupShow = true">
					
					<text v-if="coupon.money" style="color: #4899a6;">优惠 {{ coupon.money }}￥</text>
					<text v-else style="color: #4899a6;">{{ couponNum == 0 ? '无' : `${couponNum}张` }}</text>
					
					<template #icon>
						<image class="icon" src="../../static/payOrder/5.png" mode=""></image>
					</template>
					
				</van-cell>

			</van-cell-group>

			<view style="color: #888;font-size: 12px;padding: 10px 0;;">
				温馨提示：下单前请仔细查看下单须知
			</view>

			<view class="agreement">
				<van-checkbox v-model="agreement"></van-checkbox>
				本人已同意<text @click="configPopupShow = true" style="color: #6FDFBE;">《用户使用协议》</text>
			</view>

		</view>

		<view class="submit">
			<view class="price">
				<view>
					<text style="color: #000;">合计</text>
					￥<text style="font-size: 18px;
					font-weight: 600;">{{ count }}</text>元
				</view>
				<view style="font-size: 10px;margin-top: 5px;">
					已优惠￥{{ coupon.money || 0 }}元
				</view>
			</view>
			<view class="btn" @click="submit">
				立即支付
			</view>
		</view>

		<selectTime :show="selectTimeShow" @select="selectTime" :dateList="dateList" :timeList="timeList"
			:loading="timeLoading" @selectDate="getVipTenOrderList" @close="selectTimeShow = false"
			:title="selectTimeTitle" />

		<selectTechnician :serviceId="projectDetail.id" @select="selectTechnician" :show="selectTechnicianShow"
			@close="selectTechnicianShow = false" />

		<selectCouponPopup :show="selectCouponPopupShow" @selectCoupon="selectCoupon" @countCouponNum="countCouponNum"
			@close="selectCouponPopupShow = false" />

		<selectAddressPopup :show="selectAddressPopupShow" @select="selectAddress"
			@close="selectAddressPopupShow = false" />

		<van-popup v-model:show="remarkShow" round position="bottom" @close="remarkShow = false"
			:style="{ height: '160px' }">
			<van-field v-model="remark" rows="4" autosize type="textarea" maxlength="50" placeholder="请输入留言"
				show-word-limit />
		</van-popup>

		<configPopup :keyValue="keyValue" :show="configPopupShow" :list="config" @close="configPopupShow = false" />

	</view>
</template>

<script>
	import mNavbar from '@/components/base/m-navbar.vue'
	import selectTime from '@/components/payOrder/selectTime.vue'
	import selectTechnician from '@/components/payOrder/selectTechnicianPopup.vue'
	import selectAddressPopup from '@/components/payOrder/selectAddressPopup.vue'
	import selectCouponPopup from '@/components/payOrder/selectCouponPopup.vue'
	import configPopup from '@/components/configPopup'
	import Position from '@/utils/position.js'
	import { showDialog } from 'vant';
	import { showNotify } from 'vant'

	export default {
		components: {
			mNavbar,
			selectTime,
			selectTechnician,
			selectAddressPopup,
			selectCouponPopup,
			configPopup
		},
		data() {
			return {
				payMethod: 1,
				remark: '',
				agreement: false,
				selectTimeShow: false,
				selectTechnicianShow: false,
				selectCouponPopupShow: false,
				selectAddressPopupShow: false,
				remarkShow: false,
				selectTimeTitle: '',

				technicianDetail: {},
				projectDetail: {},
				time: {},
				address: {},
				coupon: {},
				userInfo: {},
				order: [],

				dateList: [],
				timeList: [],
				timeLoading: false,
				dateObj: '',
				price: 0, //用于保存商品原价
				temp: 0,//路费
				count: 0, //计算出的价格
				configPopupShow: false,
				config: [],
				keyValue: 'protocol',
				distance : 0,
				travelMoney : 0,
				selectDay : '',		//用户选择的日期
				couponNum : 0
			}
		},
		onShow() {
			this.getOrderDetail()
			this.getUserInfo()
			this.getConfig()
			let today = this.dayjs()

			this.dateList.push(today)

			for (let i = 1; i < 7; i++) {
				this.dateList.push(today.add(i, 'day'))
			}
		},
		methods: {
			
			//获取订单详情
			getOrderDetail() {
				this.$api('getOrderVipDetail', {
					id: this.$route.query.orderId
				}, res => {
					if (res.code == 200) {
						this.projectDetail = res.result.shop
						this.technicianDetail = res.result.technician
						this.order = res.result.order

						this.getVipTenOrderList(this.dayjs())
						this.initPrice()
					}
				})
			},
			
			//获取技师上钟时间
			getVipTenOrderList(item) {
				this.selectDay = item
				this.timeLoading = true
				this.$api('getVipTenOrderList', {
					tenId: this.technicianDetail.id,
					name: item.format('dddd')
				}, res => {
					if (res.code == 200) {
						this.timeList = res.result
					}
					this.timeLoading = false
				})
			},
			
			//获取用户信息
			getUserInfo() {
				this.$api('getUserInfo', {}, res => {
					if (res.code == 200) {
						this.userInfo = res.result;
					}
				})
			},
			
			//点击返回箭
			leftClick() {
				let {current,id,distance,orderId} = this.$route.query
				if (current == 'technicianDetail') { //返回技师详情
					return uni.navigateTo({
						url: `/pages/technician/technicianDetail?id=${id}&distance=${distance}`
					})
				}
				if (current == 'orderDetail') {		//返回订单详情
					return uni.navigateTo({
						url: `/pages/order/orderDetail?id=${orderId}`
					})
				}
				uni.navigateTo({ //返回技师选择列表
					url: `/pages/technician/selectTechnician?serviceId=${this.projectDetail.id}`
				})
			},
			
			//支付
			submit() {
				if (!this.address.id) {
					return this.selectAddressPopupShow = true
				}
				if (!this.time.id) {
					return this.selectTimeShow = true
				}
				if (!this.agreement) {
					return uni.showToast({
						title: '请勾选用户使用协议协议',
						icon: 'none'
					})
				}
				let data = {
					addressId: this.address.id, //地址id
					orderId: this.order.id, //订单id
					payType: this.payMethod, // 支付类型
					remark: this.remark, //备注
					serviceTime: this.time.id, //服务时间
					travelType: 1, //出行方式
					travelDistance: this.distance, //技师距离
					serviceDate : this.selectDay.format('YYYY-MM-DD')//服务时间
				}

				if (this.coupon.id) {
					data.couponId = this.coupon.id //优惠劵id
				}

				this.$api('payVipOrder', data, res => {
					if (res.code == 200) {
						if (this.payMethod == 1) {		//余额支付
							showDialog({
								title: '支付成功',
								message: '订单支付成功!请前往订单查看',
							}).then(() => {
								this.paySusscess()
							});
						} else if (this.payMethod == 0) {		//微信支付
							this.$wxPay(res,this.paySusscess,this.paySusscess)
						}
					}else{		//不管订单是否支付成功，直接跳订单页面
						this.paySusscess()
					}
				})
			},
			
			//显示选择技师上钟时间弹框
			onServiceTime() {
				this.selectTimeShow = true
				this.selectTimeTitle = '请选择服务时间'
			},
			
			//选择技师上钟时间
			selectTime(obj) {
				this.selectTimeShow = false
				this.time = obj.time
				this.dateObj = obj.date
			},
			
			//选择技师
			selectTechnician(item) {
				this.selectTechnicianShow = false
				this.technicianDetail = item
			},
			
			//选择优惠券
			selectCoupon(item) {
				if (item.useMoney > this.price) { //判断优惠券使用条件(满多少可用)
					this.selectCouponPopupShow = false
					return uni.showToast({icon: 'none',title: `此券需满${item.useMoney}可用`});
				}
				this.count = this.price //先恢复商品价格，防止多次选择优惠券前端多次减金额
				this.selectCouponPopupShow = false
				this.coupon = item
				this.count = this.price - item.money
			},
			
			//显示选择地址弹框
			selectAddress(item) {
				if(!item.latitude && !item.longitude){		//判断地址信息有没有经纬度信息，避免出现距离计算出现问题
					this.selectAddressPopupShow = false
					return uni.showToast({icon: 'none',title: '选择的地址异常,请选择其他地址或重新添加'});
				}
				this.selectAddressPopupShow = false
				this.address = item
				this.calculatedDistance();		//计算两地距离
			},
			
			wxPay() {
				this.$api('createOrderWXPay', {}, res => {
					if (res.code == 200) {
						this.$wxPay(res,this.paySusscess,this.paySusscess)
					}
				})
			},
			
			//获取配置信息
			getConfig() {
				this.$api('getConfig', {}, res => {
					if (res.code == 200) {
						this.config = res.result
						res.result.forEach(item => {
							if(item.keyValue == 'travel_money'){
								this.travelMoney = item.content
							}
						})
					}
				})
			},
			
			//计算距离
			calculatedDistance(){		//计算距离
				// Position.getLocation(result => {
				// 	this.distance = Position.calculateDistance(result.latitude, result.longitude, this.technicianDetail.latitude, this.technicianDetail.longitude)
				// 	//计算路费
				// 	if (this.distance < 2) {
				// 		this.temp = 0
				// 	}else{
				// 		this.temp = Number((this.distance * this.travelMoney).toFixed(2));
				// 		this.initPrice()
				// 	}
				// })
				if(this.$route.query.setKmOpen=='Y'){		//是否打开了假距离
					this.distance = this.$route.query.distance
				}else{
					this.distance = Position.calculateDistance(this.address.latitude, this.address.longitude, this.technicianDetail.latitude, this.technicianDetail.longitude)
				}
				//计算路费
				if (this.distance < 2) {
					this.temp = 0
				}else{
					this.temp = Number((this.distance * this.travelMoney).toFixed(2));
					this.initPrice()
				}
			},
			
			//初始化金额数据(用于前端计算)
			initPrice(){
				this.price = Number(this.order.money + this.temp).toFixed(2)
				this.count = Number(this.order.money + this.temp).toFixed(2)
			},
			
			//支付成功(跳转订单)
			paySusscess(){
				uni.reLaunch({
				  url: '/pages/index/order?active=2'
				})
			},
			
			//获取优惠券数量
			countCouponNum(num){
				this.couponNum = num
			}
		}
	}
</script>

<style scoped lang="scss">
	body {
		background-color: #f3f3f3;
	}

	.payOrder {
		.bac {
			position: absolute;
			width: 100%;
			height: 100px;
			background: linear-gradient(to right, #4899a6, #6fc6ad);
		}

		.box {
			position: relative;
			width: calc(100% - 30px);
			margin: 15px;
			margin-top: 30rpx;
			min-height: 500px;
			border-radius: 10px;
			padding-bottom: 80px;

			.server-item {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				background: white;
				border-radius: 15rpx;
				box-sizing: border-box;
				padding: 25rpx;
				margin: 20rpx 0rpx;

				.img-box {
					width: 150rpx;
					height: 150rpx;
					background: #ccc;
					border-radius: 10rpx;
					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.server-info {
					width: calc(100% - 150rpx);
					box-sizing: border-box;
					padding: 10rpx 15rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-around;

					.server-title {
						font-size: 15px;
					}

					.time-coupon,
					.price {
						display: flex;
						flex-wrap: wrap;
						align-items: center;
					}

					.time-coupon {
						margin: 10rpx 0rpx;
						font-size: 26rpx;

						image {
							width: 25rpx;
							height: 25rpx;
						}

						.time {
							color: #B8B8B8;
							margin-left: 6rpx;
						}
					}

					.coupon {
						display: flex;
						justify-content: center;
						align-items: center;
						background: #F29E45;
						color: white;
						width: 140rpx;
						height: 45rpx;
						border-radius: 10rpx;
						margin-left: 10rpx;
					}

					// 			.price {
					// 				font-size: 26rpx;
					// 				color: #B8B8B8;
					// 				.current-price {
					// 					font-size: 30rpx;
					// 					font-weight: 600;
					// 					color: #D34430;
					// 				}
					// 				.unit{
					// 					font-size: 20rpx;
					// 				}
					// 			}

					.sales-volume {
						display: flex;
						align-items: center;
						color: #B8B8B8;
						font-size: 26rpx;

						image {
							width: 25rpx;
							height: 25rpx;
						}

					}

				}
			}

			.icon {
				width: 14px;
				height: 14px;
				vertical-align: middle;
				padding: 6rpx;
			}

			.mileage {
				display: flex;
				flex-direction: column;
				padding: 10px;

				.top {
					padding: 5px 10px;
					padding-left: 25px;
					background-color: #A1D9CC99;
					font-size: 12px;
					position: relative;
				}

				.top::after {
					content: '';
					position: absolute;
					display: block;
					width: 8px;
					height: 8px;
					background-color: #6fc6ad;
					top: 50%;
					left: 10px;
					transform: translate(0, -40%);
					border-radius: 4px;
				}

				.info {
					padding: 10px;
					background-color: #ECFFFB;
					color: #888;
					font-size: 11px;
					line-height: 20px;
				}
			}

			.agreement {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10px 0;
				
				.van-checkbox{
					margin-right: 5rpx;
				}
			}
		}

		.submit {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 60px;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.price {
				color: #F39637;
				padding: 0 20px;
			}

			.btn {
				background: linear-gradient(178deg, #4FD3BC, #60C285);
				color: white;
				width: 120px;
				height: 45px;
				border-radius: 23px;
				font-size: 16px;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>