<template>
	<view class="container">
		<!-- deBug信息 -->
		<view v-if="merchant" class="web-debug web-text-success" style="display: ">
			场馆ID：{{ merchant.merchantId }} 
			场馆编号：{{ merchant.merchantCode }} 
			场馆名称：{{ merchant.merchantName }} 
			日期：{{ dateTime }} 
			星期：{{ week }} 
			订单总金额：{{ totalPrice }} 
			类型：{{
				type
			}}
			场地信息：{{ orderInfo }}
			表单信息：{{ form }}
		</view>
		<uni-card title="预约人信息" :border="false" :is-shadow="false">
			<uv-cell-group :customStyle="{ backgroundColor: '#ffffff' }" :border="false">
				<uv-cell title="真实姓名" :cellStyle="{ padding: '10px 5px' }" :value="userInfo.realName" :border="false" />
				<uv-cell title="手机号码" :cellStyle="{ padding: '10px 5px' }" :value="userInfo.phone" :border="false" />
			</uv-cell-group>
		</uni-card>

		<uni-card title="订单信息" :border="false" :is-shadow="false">
			<uv-cell-group :customStyle="{ backgroundColor: '#ffffff' }" :border="false">
				<block v-if="orderInfo.length == 0">
					<span class="web-text-secondary">订单不存在</span>
				</block>
				<block v-if="orderInfo">
					<uv-cell :title="`场馆`" :label="form.merchantName" :cellStyle="{ padding: '10px 5px' }" :border="false" />
					<block v-for="(item, index) in orderInfo" :key="index">
						<uv-cell
							:title="`${item.fieldName}`"
							:label="`${item.dateTime} ${getWeek(this.week)} ${item.timePeriod}`"
							:value="`￥${item.price}`" 
							:cellStyle="{ padding: '10px 5px' }"
							:border="false"
						/>
					</block>
				</block>
			</uv-cell-group>
		</uni-card>
		<!-- <uni-card title="选择优惠券" :border="false" :is-shadow="false">
			<uv-cell-group :customStyle="{ backgroundColor: '#ffffff' }" :border="false">
				<uv-cell
					title="可用优惠券"
					icon="https://oss.wsdns.cn/20240502/b13bb4162f44473eb2e05052f7c26b0e.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px' }"
					isLink
					:value="`0 张`"
					:border="false"
				/>
				<uv-cell
					title="可用会员卡"
					icon="https://oss.wsdns.cn/20240502/1017dc754cde4d108cebcca147a4ce9d.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px' }"
					isLink
					:value="`${cardList.length} 张`"
					:border="false"
				/>
				<uv-cell
					title="可用IC卡"
					icon="https://oss.wsdns.cn/20240502/6ee5122fd32440c996ed86154d656e04.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px' }"
					isLink
					:value="`0 张`"
					:border="false"
				/>
			</uv-cell-group>
			<view slot="actions" class="card-actions">
				<view class="card-actions-item" @click="actionsClick('分享')">
					<span class="web-text-danger">已优惠￥{{ reducePrice }}</span>
					<span class="web-text-heading">￥{{ totalPrice || 0.0 }}</span>
				</view>
			</view>
		</uni-card> -->
		<uni-card title="选择支付方式" :border="false" :is-shadow="false">
			<uv-cell-group :customStyle="{ backgroundColor: '#ffffff' }" :border="false">
				<block v-for="(item, index) in payment" :key="index"></block>
				<uv-cell
					title="微信支付"
					icon="https://oss.wsdns.cn/20240511/8d7af0f0374040cb9b9255eff5fb812d.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '20rpx 10rpx', borderRadius: '8rpx', backgroundColor: form.payType == 1 ? '#f6fff1' : '' }"
					:border="false"
					@click="onPayType(1)"
				>
					<template v-slot:right-icon>
						<uv-icon v-if="form.payType == 1" size="30rpx" name="checkbox-mark"></uv-icon>
					</template>
				</uv-cell>
				<uv-cell
					:title="`余额支付(${userInfo.balance})`"
					icon="https://oss.wsdns.cn/20240511/fae57a94fa0042b9bceb721421304db1.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px', borderRadius: '8rpx', backgroundColor: form.payType == 0 ? '#f6fff1' : '' }"
					:border="false"
					@click="onPayType(0)"
				>
					<template v-slot:right-icon>
						<uv-icon v-if="form.payType == 0" size="30rpx" name="checkbox-mark"></uv-icon>
					</template>
				</uv-cell>
				<uv-cell
					title="优惠券"
					icon="https://oss.wsdns.cn/20240502/b13bb4162f44473eb2e05052f7c26b0e.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px' }"
					isLink
					:value="`0 张`"
					:border="false"
				/>
				<uv-cell
					:title="`会员卡`"
					icon="https://oss.wsdns.cn/20240502/1017dc754cde4d108cebcca147a4ce9d.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px', borderRadius: '8rpx', backgroundColor: form.payType == 6 || form.payType == 7 || form.payType == 8 ? '#f6fff1' : '' }"
					:border="false"
					isLink
					:value="`${currentCard.name ? currentCard.name : '0 张'}`"
					@click="onPayType(7)"
				>
				</uv-cell>
				<uv-cell
					title="IC卡"
					icon="https://oss.wsdns.cn/20240502/6ee5122fd32440c996ed86154d656e04.png?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90"
					:cellStyle="{ padding: '10px 5px' }"
					isLink
					:value="`0 张`"
					:border="false"
				/>
				<view slot="actions" class="card-actions">
					<view class="card-actions-item" @click="actionsClick('分享')">
						<span class="web-text-danger">已优惠￥{{ form.reducePrice }}</span>
						<span class="web-text-heading">￥{{ form.payPrice || 0.0 }}</span>
					</view>
				</view>
			</uv-cell-group>
		</uni-card>

		<view class="xieyi web-cell web-text-secondary web-cell-align-top">
			<view class="web-cell web-cell-content web-cell-align-top">
				<uni-icons type="circle" size="20" color="#a4a5a7" v-if="!disabled" @click="onDisabled"></uni-icons>
				<uni-icons type="checkbox" size="20" color="#11a954" v-else @click="onDisabled"></uni-icons>
				<view class="text" @click="onDisabled">
					<text>同意以下服务条款</text>
					<text class="link" @click.stop="navTo('/package/article-detail/article-detail?articleId=501')">《广西体育中心预定条款》</text>
					<text class="link" @click.stop="navTo('/package/article-detail/article-detail?articleId=502')">《用户服务协议和隐私政策》</text>
				</view>
			</view>
		</view>

		<!-- 支付按钮 -->
		<uv-gap height="50"></uv-gap>
		<view class="checkout-car">
			<view class="car-total">
				<text style="color: #ebcf00">合计￥</text>
				<uv-count-to :startVal="0" decimals="2" duration="100" color="#ebcf00" bold :endVal="form.payPrice"></uv-count-to>
			</view>
			 <!--:disabled="!disabled || orderInfo.length == 0" -->
			<uv-button
				class="save-btn"
				:disabled="!disabled"
				:customStyle="{ background: 'linear-gradient(to right, #70b915, #008e04)', borderRadius: '0 30px 30px 0', color: '#ffffff', border: 'none', padding: '22px 30px' }"
				text="提交订单"
				@click="save"
			></uv-button>
		</view>
	</view>
	<!-- 登录组件 -->
	<ws-login ref="login" :logo="logo" @done="reload" />
	<!-- 支付密码弹窗 -->
	<uni-popup ref="payPasswordForm" type="center" border-radius="10px 10px 0 0">
		<uni-card title="请输入支付密码" :border="false" :is-shadow="false" :padding="0">
			<view class="pay-password-card">
				<uni-forms ref="form" :label-width="80">
					<uni-forms-item label="支付密码" name="payPassword" required>
						<uv-code-input mode="box" :space="0" :maxlength="6" hairline v-model="payPassword"></uv-code-input>
					</uni-forms-item>
					<uv-button class="to-pay-btn"
						:customStyle="{background: 'linear-gradient(to right, #70b915, #008e04)',borderRadius: '30px',color: '#ffffff'}"
						text="确定支付" :disabled="disabledPayPayPassword" @click="onPayPassword"></uv-button>
				</uni-forms>
				<text @click="navTo(`/package/user/pay-password`)" class="web-text-primary">忘记支付密码？</text>
			</view>
		</uni-card>
	</uni-popup>
</template>

<script>
import * as Api from '@/api/shop/order';
import * as UserCardApi from '@/api/booking/userCard';
import { checkPayPassword } from '@/api/passport/login';
import { storeToRefs } from 'pinia';
import { cal } from '@/utils/decimal'
import { getWeek, getKey } from '@/utils/common';
import { useCarStore } from '@/store/modules/car';
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const carStore = useCarStore();
const { orderInfo, totalPrice, carNum, merchant, type, dateTime } = storeToRefs(carStore);

export default {
	data() {
		return {
			orderId: 0,
			userInfo: {},
			// 表单信息
			form: {},
			// 场馆信息
			merchant,
			orderInfo,
			totalPrice,
			carNum,
			week: 0,
			reducePrice: 0,
			payPrice: 0,
			cardId: 0,
			getWeek,
			// payType: 1,
			isLogin: false,
			disabled: false,
			cardList: [],
			currentCard: {},
			// 支付密码是否正确
			isPayPasswordCorrect: false,
			disabledPayPayPassword: false,
			payPassword: ''
		};
	},
	onLoad(option) {
		this.orderId = option.id;
		this.reload();
		// this.getUserCard();
	},
	onShow() {
		// 登录状态
		if (uni.getStorageSync('user_id') && uni.getStorageSync('access_token')) {
			this.isLogin = true;
		}
		this.openLogin();
	},
	methods: {
		async reload() {
			const app = this;
			const { orderId, merchant, orderInfo } = this;

			// 当前登录用户信息
			const userInfo = await userStore.fetchUserInfo();
			app.userInfo = userInfo;
			
			// 整理订单信息
			app.form = Object.assign({}, app.form, carStore);
			
			if(orderInfo.length > 0){
				app.form.orderInfo = orderInfo
				app.form.merchantId = merchant.merchantId
				app.form.merchantName = merchant.merchantName
				app.form.merchantCode = merchant.merchantCode
				app.form.comments = merchant.merchantName + ' ' + orderInfo[0].fieldName + ' ' + orderInfo[0].dateTime;
				app.form.payPrice = totalPrice
				app.form.type = 1  		// 订单类型 0商城订单 1预定订单
				app.form.payType = 1 	// 支付方式 0余额支付 2微信支付
			}

			if (orderId > 0) {
				Api.getOrder(orderId).then((data) => {
					app.form = Object.assign({}, app.form, data);
				});
			}
			
		},
		// 读取会员卡信息
		getUserCard(){
			const app = this
			const { form } = this
			const { userId } = userInfo
			UserCardApi.pageUserCard({userId,sid: app.merchantId}).then(res => {
				app.cardList = res.list
				const item = res.list[0]
				app.currentCard = item
				
				// 年卡
				if(item.type == 1){
					// 支付方式
					app.form.payType = 7
					app.form.cardId = item.cardId
					// 折扣率
					const discount = cal.cheng(item.discount,0.1)
					// 折后金额
					const lastTotalPrice = cal.cheng(form.totalPrice,discount)
					// 减少的金额
					app.form.reducePrice = cal.jian(form.totalPrice,lastTotalPrice)
					// 实付额
					app.form.payPrice = lastTotalPrice
				}
				
			})
		},
		onDisabled() {
			this.disabled = !this.disabled;
		},
		navTo(url) {
			uni.navigateTo({
				url
			});
		},
		// 切换支付方式
		onPayType(index) {
			this.form.payType = index;
		},
		openUrl(url) {
			if (!this.isLogin) {
				this.$refs.login.open('bottom');
				return false;
			} else {
				uni.navigateTo({
					url
				});
			}
		},
		// 弹出登录提示框
		openLogin() {
			if (!this.isLogin) {
				this.$refs.login.open('bottom');
				return false;
			}
		},
		// 验证支付密码
		onPayPassword(){
			if(this.payPassword == '' || !this.payPassword){
				uni.showToast({
					title: '请输入支付密码',
					icon: 'none'
				});
				return false;
			}
			this.disabledPayPayPassword = true
			const { payPassword } = this
			checkPayPassword({payPassword}).then(res => {
				this.disabledPayPayPassword = false
				this.isPayPasswordCorrect = true
				this.save()
			}).catch(err => {
				uni.showToast({
					title: err.message,
					icon: 'none'
				});
				this.disabledPayPayPassword = false
			})
			
		},
		save() {
			const app = this;
			const { form } = this
			if (!this.disabled) {
				uni.showToast({
					title: '请先阅读并同意服务协议',
					icon: 'none'
				});
				return false;
			}
			// if (carStore.orderInfo.length == 0) {
			// 	uni.showToast({
			// 		title: '订单信息不存在',
			// 		icon: 'none'
			// 	});
			// 	return false;
			// }
			
			if(form.payType == 0 && !this.isPayPasswordCorrect){
				this.$refs.payPasswordForm.open('center');
				return false;
			}
			uni.showLoading({
				title: '订单提交中.'
			});

			Api.addOrder(form)
				.then((data) => {
					const orderInfo = data;

					// 调起微信支付
					if (form.payType == 1) {
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							provider: orderInfo.provider, // 服务提供商
							timeStamp: orderInfo.timeStamp, // 时间戳
							nonceStr: orderInfo.nonceStr, // 随机字符串
							package: orderInfo.package,
							signType: orderInfo.signType, // 签名算法
							paySign: orderInfo.paySign, // 签名
							success: function (res) {
								// 业务逻辑。。。
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
								setTimeout(function () {
									app.disabled = false;
									uni.reLaunch({
										url: '/pages/order/order',
										success: function (e) {
											var page = getCurrentPages()[0];
											if (page == undefined || page == null) return;
											page.onLoad();
										}
									});
								}, 1500);
							},
							fail: function (err) {
								console.log('支付失败', err);
								app.disabled = false;
								uni.reLaunch({
									url: '/pages/order/order',
									success: function (e) {
										var page = getCurrentPages()[0];
										if (page == undefined || page == null) return;
										page.onLoad();
									}
								});
								// uni.switchTab({
								// 	url: '/pages/order/order'
								// })
							}
						});
						// #endif
					}
					// 使用余额支付
					if (form.payType == 0) {
						if (!orderInfo) {
							return uni.showToast({
								title: '支付失败',
								icon: 'error'
							});
						}
						if (orderInfo) {
							uni.showToast({
								title: '支付成功',
								icon: 'success'
							});
							setTimeout(function () {
								app.disabled = false;
								uni.reLaunch({
									url: '/pages/order/order',
									success: function (e) {
										var page = getCurrentPages()[0];
										if (page == undefined || page == null) return;
										page.onLoad();
									}
								});
							}, 1500);
						}
					}

					uni.hideLoading();
				})
				.catch((res) => {
					uni.showToast({
						title: res.message || '请检查您的网络.',
						icon: 'none'
					});
					uni.hideLoading();
				});
		}
	}
};
</script>
<style>
page {
	background-size: 100%;
	background-repeat: no-repeat;
	background-color: #f0f2f5;
	width: 750rpx;
	overflow-x: hidden;
}
</style>
<style lang="scss" scoped>
.container {
}

.checkout-car {
	width: 700rpx;
	left: 25rpx;
	position: fixed;
	bottom: 30rpx;
	display: flex;
	justify-content: space-between;
	background-color: #000000;
	border-radius: 100px;
	align-items: center;

	.car-selected {
		color: #ccc;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
	}

	.car-total {
		display: flex;
		color: #ebcf00;
		align-items: center;
		padding-left: 40rpx;

		.save-btn {
		}
	}
}

.card-actions {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	height: 45px;
	border-top: 1px #eee solid;
}

.card-actions-item {
	display: flex;
	flex-direction: row;
	align-items: center;

	.web-text-heading {
		font-size: 38rpx;
		margin-left: 28rpx;
	}
}

.card-actions-item-text {
	font-size: 12px;
	color: #666;
	margin-left: 5px;
}

.xieyi {
	margin-bottom: 80rpx;
	padding: 0 30rpx;

	.text {
		margin-left: 5rpx;

		.link {
			color: #0f80ff;
		}
	}
}
.pay-password-card{
	width: 600rpx;
	height: 400rpx;
	margin: 30rpx auto;
	line-height: 2rem;
	background-color: #ffffff;
	text-align: center;
	display: flex;
	justify-content: center;
	flex-direction: column;
	align-items: center;
}
.to-pay-btn {
	width: 500rpx !important;
	margin: 40rpx auto;
}
</style>
