<template>
	<view class="orderDetails">
		<view class="content" v-if="details">
			<view class="address">
				<view class="add">{{details.address}} {{details.name}} {{details.atlasAdd}} </view>
				<view class="name">
					<view class="name_left">
						{{details.cName}} <text>{{details.cPhone}}</text>
					</view>
					<view class="toggle" @click="changeAddress(details.cId)">
						更换地址
					</view>
				</view>
			</view>
			<view class="list_content">
				<view class="list_title">
					<view class="title_left">
						<text></text>体验项目
					</view>
					<view class="js">商户：{{ details.js ? details.js.cNickName : '' }}</view>
				</view>
				<view class="lists" v-for="(item,index) in details.cGoods" :key="index">
					<view class="imgs">
						<image :src="$globalData.publicUrl + item.cCover" mode="" />
					</view>
					<view class="right">
						<view class="list_title">
							<view class="title">{{item.cTitle}}</view>
							<view class="time">服务时长：{{item.nMinute}}分钟</view>
						</view>

						<view class="price">
							<view class="counter">份数：{{item.number}} </view>
							<view class="money">￥{{item.dPrice}}</view>
						</view>
					</view>
				</view>
				<view class="total">
					<text style="font-size: 28rpx;">总计</text>
					<view class="total_price" v-if="orderType ==2">
						￥<text class="price">{{priceDifference}}</text>
					</view>
					<view class="total_price" v-else>
						￥<text class="price">{{dTotalMoney}}</text>
					</view>
				</view>
				<view class="time_coupon">
					<view class="select_coupon" @click="onSelectTime">
						<text>预约时间 <text class="red">*</text> </text>
						<view class="right" v-if="reachTime !== ''">{{reachTime}}
							<image src="/static/identify/more.png" mode="" />
						</view>
						<view class="right" v-else>请选择上门时间
							<image src="/static/identify/more.png" mode="" />
						</view>
					</view>
					<view class="select_coupon" @click="selectCoupon">
						<text>优惠券</text>
						<view class="right" v-if="preferential>0">-{{preferential}}元
							<image src="/static/identify/more.png" mode="" />
						</view>
						<view class="right" v-else>{{couponNum}}张可用
							<image src="/static/identify/more.png" mode="" />
						</view>
					</view>
				</view>

			</view>
			<view class="face" v-if="!details.parentNo">
				<view class="face_one">
					<view class="title_left"> <text></text>出行方式</view>
					<view class="btn">滴滴/出租</view>
				</view>
				<view class="face_one">
					<view>车费</view>
					<view class="price"> 预估：{{details.fare || 0}}元</view>
				</view>
				<view class="face_three">
					<text>车费共计￥{{details.fare || 0}}，全程 {{details.distance}} 公里，</text>
					<text>起步价{{baseDistance || 3}}公里{{baseFare || 9.3}}元，</text>
					<text>超出{{baseDistance || 3}}公里后，</text>
					<text>每公里{{additionalFarePer || 2.4}}元。</text>
				</view>
			</view>
			<view class="pay_type">
				<view class="pay_title"> <text></text>支付方式</view>
				<view class="pay_box">
					<u-radio-group
						placement="column"
						v-model="selectedPayment"
					>
						<view class="paytype">
							<image src="/static/identify/weixin.png" mode="" />
							<text>微信支付</text>
							<u-radio name="1" />
						</view>
						<view class="paytype">
							<image src="/static/identify/qianbao.png" mode="" />
							<text>账户余额（{{dBalance}}）</text>
							<u-radio name="2" />
						</view>
						<view class="paytype" v-if="orderType == 2">
							<image src="/static/identify/rmb.png" mode="" />
							<text>现金支付</text>
							<u-radio name="3" />
						</view>
					</u-radio-group>
				</view>
			</view>
		</view>

		<view class="footer-bar">
			<view class="prices">合计：
				<text v-if="orderType == 2">{{priceDifference}}</text>
				<text v-else>{{totalPrice}}</text>
			</view>
			<view class="btn" @click="goPay" v-if="remainingTime>0">
				<view class="">
					立即支付
				</view>
				<view class="remaining_time">
					剩余 <u-count-down :time="remainingTime" @finish="onRefresh"></u-count-down>
				</view>
			</view>
			<view class="btn" v-else>
        <view>{{ remainingTime }}</view>
				<view class="">
					已过期
				</view>
			</view>
		</view>

		<ServiceTimePicker
            ref="stp"
            startHour="00:00"
            endHour="24:00"
            :duration="120"
            :bookedTimes="bookedTimes"
            @confirm="onTimeConfirm"
        ></ServiceTimePicker>
	</view>
</template>

<script>
import wx from 'weixin-js-sdk';
import { h5Url } from '@/common/config.js';
import ServiceTimePicker from '@/components/picker/service-time.vue';
import {
	getInfo,
	payoff,
	pay,
	getSignature,
	getCoupon,
	getFareSetting,
	verification
} from '@/api/index.js';
import {
	orderDeatails,
	getStaffServiceTime
} from '@/api/order.js';
export default {
	components: {
		ServiceTimePicker
	},
	data() {
		return {
			form: {
				dMoney: 0,
				cOpenId: uni.getStorageSync('wx_copenid'),
			},
			query: {},
			details: {},
			// 变量
			orderType: '',
			dBalance: 0, //账户余额
			dTotalMoney: 0,
			totalPrice: '', //总金额
			preferential: '', //优惠金额
      reachTime: '', //上门时间
			priceDifference: '', //升级差价
			// 交通费
			baseFare: '', //起步价
			baseDistance: '', //起步距离
			additionalFarePer: '', //超出费用
			// 优惠劵
			couponId: '',
			couponNum: 0,
			couponReceiveId: '', //优惠券id
			// 服务时间
			bookedTimes: [
				// { start: '2026-01-03 19:00', end: '2026-01-03 20:00' }
			],
			// 支付计时
			remainingTime: '',
			// 支付方式
			selectedPayment: null,
			couponSelected: {}
		}
	},
	onLoad(query) {
		this.query = query;
		wx.checkJsApi({
			jsApiList: ['chooseImage'],
			success: (res) => {
				// 以键值对的形式返回，可用的api值true，不可用为false
				// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
			}
		});
		if(getApp().globalData.couponSelected) {
			this.couponSelected = getApp().globalData.couponSelected
		}
	},
	onShow() {
		this.getInfo()
		this.getOrder()
		this.getCoupon()

		let couponData = uni.getStorageSync('couponData');
		if (couponData) {
			this.couponId = couponData.id
			this.verification()
		}
	},
	methods: {
		getInfo() {
			getInfo().then(res => {
				this.dBalance = res.data.data.dBalance.toFixed(2)
			})
		},
		getCoupon() {
			let params = {
				openid: uni.getStorageSync('wx_copenid')
			}
			getCoupon(params).then(res => {
				if (res.data.data?.length > 0) {
					this.couponNum = res.data.data.length
				} else {
					this.couponNum = 0
				}
			})
		},
		getOrder() {
			let params = {
				orderNo: this.query.orderNo,
				couponReceiveId: this.couponId
			}
			orderDeatails(params).then(res => {
				console.log('orderDeatails', res)
				if (res.data.code === 200) {
					this.details = {
						...res.data.data.records[0],
						distance: res.data.data.records[0].distance.toFixed(2)
					}
					// 这四个值相关 orderType 2: 现金
					this.orderType = this.details.orderType;
					this.totalPrice = this.details.totalPrice;
					this.dTotalMoney = this.details.dTotalMoney;
					this.priceDifference = this.details.priceDifference;
					// 支付倒计时
          this.$set(this, 'remainingTime', res.data.data.records[0].remainingTime * 1000);
					// 获取部门车费
					this.fareSetting(res.data.data.records[0].deptId);
					// 获取服务时间
					this.getServiceTime();
				}
			})
		},
		// 获取服务时间
		getServiceTime() {
			getStaffServiceTime({
				technicianId: this.details.cJsId
			}).then(res => {

			});
		},
		// 获取部门车费
		fareSetting(id) {
			let params = {
				deptId: id,
				enable: 1
			}
			getFareSetting(params).then(res => {
        if(res.data.data.records && res.data.data.records.length > 0){
				  this.baseFare = res.data.data.records[0].baseFare || ''
				  this.baseDistance = res.data.data.records[0].baseDistance
				  this.additionalFarePer = res.data.data.records[0].additionalFarePer
        }
			})
		},
		// 服务时间
		onSelectTime() {
      this.$refs.stp.show = true;
		},
		onTimeConfirm(e) {
      this.reachTime = e[0];
		},
		onRefresh() {
			this.remainingTime = 0
		},
		selectCoupon() {
			if (this.remainingTime > 0) {
				uni.navigateTo({
					url: '/pages/my/coupon?title=select'
				})
			} else {
				uni.showToast({
					title: '已过期，请重新下单',
					icon: 'none'
				})
			}
		},
		changeAddress(id) {
			let str = uni.$u.queryParams({
				name: '支付订单',
				orderNo: id
			});
			uni.navigateTo({
				url: `/pages/address/index${str}`
			})
		},
		//选择支付方式
		onRadioChange(e) {
			this.selectedPayment = e.target.value
		},
		// 支付
		goPay() {
			this.form.dMoney = this.totalPrice
			if (this.remainingTime == 0) {
				uni.showToast({
					title: '订单已过期',
					icon: 'none'
				})
				return;
			}
			if (this.selectedPayment == null) {
				uni.showToast({
					title: '请选择支付方式',
					icon: 'none'
				})
			} else if (this.selectedPayment == 1) {
				//微信支付
				this.weixinPay()
			} else if (this.selectedPayment == 2) {
				//余额支付
				this.nowYuyue()
			} else if (this.selectedPayment == 3){
				this.rmbPay()
			}
		},
		//微信支付
		weixinPay() {
			let params = {
				cId: this.details.cId,
				payType: this.selectedPayment,
				couponReceiveId: this.couponReceiveId,
				preferential: this.preferential, //优惠金额
				totalPrice: this.totalPrice, //总金额
			}
      let url = `${h5Url}/`
			payoff(params).then(res => {
				let payConfig = JSON.parse(res.data.data)
				getSignature(url).then(res => {
					this.wxconfig = res.data
					wx.config({
						beta: true,
						debug: false,
						appId: this.wxconfig.appId, // 公众号ID
						// appId: uni.getAppBaseInfo().host.appId, // 公众号ID
						timestamp: this.wxconfig.timestamp, // 时间戳，自1970年以来的秒数
						nonceStr: this.wxconfig.nonceStr, // 随机串
						signature: this.wxconfig.sign, // 微信签名方式
						jsApiList: ['getBrandWCPayRequest']
					});
					var vm = this
					wx.invoke(
						'getBrandWCPayRequest',
						// 下面参数内容都是后台返回的
						{
							'appId': payConfig.appid, // 公众号名称，由商户传入
							'timeStamp': payConfig.timeStamp, // 时间戳
							'nonceStr': payConfig.nonceStr, // 随机串
							'package': payConfig.package, // 预支付id
							'signType': payConfig.signType, // 微信签名方式
							'paySign': payConfig.paySign, // 微信签名
						},
						function(res) {
							// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。

							// JSON.stringify(res);
							if (res.err_msg == "get_brand_wcpay_request:ok") {
                uni.showToast({
                  title: '支付成功！',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  uni.switchTab({
                    url: '../order/order',
                  })
                }, 500)
                //使用vm弹窗导致界面报错 不跳转 - xueyh
								// vm.$message.success(
								// 	"支付成功") // 使用alert来弹窗 支付成功  是没有反应的。所以这里改为框架页面的弹窗就好了。注意必须要上这个微信浏览器内置事件外 转this指向才能弹窗
								// // vm.isDisabledSubmitBtn = false;
								// uni.switchTab({
								// 	url: '../order/order',
								// })
							} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
								uni.showToast({
									title: '已取消支付',
									icon: 'none'
								})
								// alert('支付取消');
								// vm.isDisabledSubmitBtn = false;

							} else {
								alert('付款失败');
								// vm.isDisabledSubmitBtn = false;
							}
						}
					)
				})
			})
		},
		//拉取微信支付的方法
		pullWchatPay(data) {
			var that = this;
			let onBridgeReady = () => {
				if (WeixinJSBridge && appId) {
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: data.appId,
							nonceStr: data.nonceStr,
							package: data.package,
							paySign: data.paySign,
							signType: data.signType,
							timeStamp: data.timeStamp
						},
						function(res) {
							console.log('调起支付时的警告');
							if (res.err_msg === 'get_brand_wcpay_request:ok') {
								_this.payType = 0;
								console.log('支付成功回调')
							} else {
								console.log('支付失败')
							}
						}
					)
				}
			}
			// 检测支付环境中的 WeixinJSBridge
			if (typeof WeixinJSBridge == "undefined") {
				if (document.addEventListener) {
					//android机型，调取支付支付环境偶尔有延迟，这里增加延时器处理
					var timev = setTimeout(() => {
						clearTimeout(timev)
						document.addEventListener('WeixinJSBridgeReady', onBridgeReady(),
							false);
					}, 1000)
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady());
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady());
				}
			} else {
				onBridgeReady();
			}
		},
		//账号余额支付
		nowYuyue() {
			if (parseInt(this.dBalance) < parseInt(this.totalPrice)) {
				uni.showModal({
					title: '账户余额不足',
					content: '请充值',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '../my/pay?name=充值'
							})
						} else if (res.cancel) {}
					}
				});
			} else {
				var data = {
					cId: this.details.cId,
					payType: this.selectedPayment,
					couponReceiveId: this.couponReceiveId,
					preferential: this.preferential, //优惠金额
					totalPrice: this.totalPrice, //总金额
				}
				payoff(data).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							title: '支付成功！',
						})
						setTimeout(() => {
							uni.switchTab({
								url: '../order/order',
							})
						}, 2000)
					} else {
						uni.showToast({
							icon: 'error',
							title: res.data.msg,
						})
					}

				})
			}
		},
		//现金支付
		rmbPay(){
			let params = {
				cId: this.details.cId,
				payType: this.selectedPayment,
				couponReceiveId: this.couponReceiveId,
				preferential: this.preferential, //优惠金额
				totalPrice: this.totalPrice, //总金额
			}
			payoff(params).then(res => {
				if (res.data.code == 200) {
					uni.showToast({
						title: '支付成功！',
					})
					setTimeout(() => {
						uni.switchTab({
							url: '../order/order',
						})
					}, 2000)
				} else {
					uni.showToast({
						icon: 'error',
						title: res.data.msg,
					})
				}

			})
		},
		verification() {
			let params = {
				cId: this.details.cId,
				couponReceiveId: this.couponId
			}
			verification(params).then(res => {
				if (res.data.msg == '不满足优惠券门槛金额') {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
				this.couponReceiveId = res.data.data.couponReceiveId
				this.preferential = res.data.data.preferential
				this.totalPrice = res.data.data.totalPrice
			})
		},
	}
}
</script>

<style lang="scss" scoped>
.orderDetails {
	min-height: 100vh;
	padding: 30rpx 40rpx 130rpx;
	background-color: #e8f2f4;
	background: linear-gradient(152deg, #DCFFF8 0%, #F1FEFF 100%);

	.content {
		overflow-y: auto;

		.address {
			background-color: #fff;
			border-radius: 20rpx;
			padding: 24rpx;
			color: #000;
			position: relative;
			margin-bottom: 24rpx;

			.add {
				font-weight: 600;
				font-size: 30rpx;
				color: #2F3437;
				line-height: 35rpx;
				margin-bottom: 12rpx;
			}

			.name {
				width: 100%;
				color: #666;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.name_left {
					font-size: 26rpx;
					color: #333333;

					text {
						font-size: 26rpx;
						color: #999999;
						margin-left: 20rpx;
					}
				}

				.toggle {
					width: 152rpx;
					height: 52rpx;
					background: linear-gradient(135deg, #1AD8CF 0%, #21C8C0 100%);
					border-radius: 98rpx;
					font-size: 26rpx;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.back {
				position: absolute;
				top: 50%;
				right: 30rpx;
				margin-top: -16rpx;

				image {
					width: 16rpx;
					transform: rotate(180deg);
				}
			}
		}
	}

	.list_content {
		width: 100%;
		background: #FFFFFF;
		box-shadow: 0px 4px 12px 0px rgba(88, 209, 187, 0.2);
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		padding: 24rpx;

		.list_title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 24rpx;

			.title_left {
				font-weight: 600;
				font-size: 28rpx;
				color: #2F3437;
				display: flex;
				align-items: center;

				text {
					display: inline-block;
					width: 6rpx;
					height: 28rpx;
					background: #20CBC2;
					margin-right: 12rpx;
				}
			}

			.js {
				width: 188rpx;
				height: 52rpx;
				background: #DEFFFD;
				border-radius: 4rpx;
				padding: 8rpx 16rpx;
				font-size: 26rpx;
				color: #00B8B0;
				box-sizing: border-box;
			}
		}

		.total {
			width: 100%;
			display: flex;
			justify-content: space-between;

			.total_price {
				font-size: 28rpx;
				color: #F53E54;

				.price {
					font-weight: 600;
					font-size: 36rpx;
					color: #F53E54;
				}
			}
		}

		.time_coupon {
			border-top: 1px solid #eeeeee;
			// padding-top: 24rpx;
			margin-top: 24rpx;

			.select_coupon {
				display: flex;
				justify-content: space-between;
				margin-top: 26rpx;

				text {
					font-size: 28rpx;
					color: #333333;

					.red {
						font-weight: 600;
						font-size: 28rpx;
						color: #F53E54;
						margin-left: 10rpx;
					}
				}

				.right {
					font-size: 26rpx;
					display: flex;
					align-items: center;

					image {
						width: 28rpx;
						height: 28rpx;
						margin-left: 8rpx;
					}
				}
			}
		}
	}

	.lists {
		width: 100%;
		// height: 160rpx;
		display: flex;
		justify-content: space-between;
		border-radius: 24rpx;
		margin-bottom: 28rpx;

		.imgs {
			width: 160rpx;
			height: 160rpx;
			border-radius: 20rpx;
			overflow: hidden;

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

		.right {
			flex: 1;
			padding-left: 30rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.list_title {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					font-size: 34rpx;
					font-weight: bold;
				}

				.time {
					font-size: 24rpx;
				}
			}

			.js {
				color: #8f9394;
			}

			.price {
				// padding-top: 50rpx;
				display: flex;
				justify-content: space-between;

				.counter {
					color: #c8caca;
				}

				.money {
					font-size: 24rpx;
					color: #333333;
				}

				.counter {
					display: flex;

					view {
						width: 60rpx;
						height: 60rpx;
						line-height: 60rpx;
						background-color: #f7f8fa;
						text-align: center;
						border-radius: 60rpx;
						font-size: 50rpx;
					}

					text {
						width: 100rpx;
						text-align: center;
						line-height: 60rpx;
					}
				}
			}
		}
	}

	.face {
		width: 100%;
		background-color: #fff;
		// margin: 0 30rpx;
		border-radius: 20rpx;
		padding: 24rpx;
		box-shadow: 0px 4rpx 12rpx 0px rgba(88, 209, 187, 0.05);
		box-sizing: border-box;

		.face_one {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			margin-bottom: 12rpx;

			.title_left {
				font-weight: 600;
				font-size: 28rpx;
				color: #2F3437;
				display: flex;
				align-items: center;

				text {
					display: inline-block;
					width: 6rpx;
					height: 28rpx;
					background: #20CBC2;
					margin-right: 12rpx;
				}
			}

			.btn {
				font-size: 28rpx;
				color: #00B8B0;
			}

			.price {
				color: #999999;
			}
		}

		.face_three {
			font-size: 26rpx;
			color: #999999;
		}
	}

	.pay_type {
		background: #FFFFFF;
		box-shadow: 0px 4rpx 12rpx 0px rgba(88, 209, 187, 0.1);
		border-radius: 20rpx;
		margin-top: 24rpx;
		padding: 24rpx;
		box-sizing: border-box;

		.pay_title {
			width: 100%;
			margin-bottom: 24rpx;
			font-weight: 600;
			font-size: 32rpx;
			color: #2F3437;
			font-weight: 600;
			font-size: 28rpx;
			color: #2F3437;
			display: flex;
			align-items: center;

			text {
				display: inline-block;
				width: 6rpx;
				height: 28rpx;
				background: #20CBC2;
				margin-right: 12rpx;
			}
		}

		.paytype {
			width: 100%;
			margin-bottom: 16rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			image {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			text {
				flex: 1;
				font-size: 30rpx;
				color: #333333;
			}
		}
	}

	.footer-bar {
		.prices {
			font-size: 28rpx;
			color: #b0b5b7;

			text {
				color: #d3362b;
			}
		}

		.btn {
			color: #fff;
			width: 300rpx;
			padding: 10rpx 0;
			background: linear-gradient(to right, #53aebc, #12d4f4);
			border-radius: 10rpx;
			text-align: center;
			display: flex;
			flex-direction: column;

			.remaining_time {
        display: flex;
        justify-content: center;
        align-items: center;
				height: 35rpx;
				margin-top: 5rpx;
				font-size: 24rpx;

				::v-deep.u-countdown-time {
					font-size: 24rpx !important;
				}
			}
		}
	}
}

::v-deep .u-count-down {
  margin-left: 10rpx !important;
}
</style>

