<template>
	<view class="container">
		<!-- deBug信息 -->
		<view v-if="merchant" class="web-debug web-text-success" style="display: none">
			场馆ID：{{ merchant.merchantId }} 场馆编号：{{ merchant.merchantCode }} 场馆名称：{{ merchant.merchantName }} 日期：{{ dateTime }} 星期：{{ week }} 订单总金额：{{
				totalPrice
			}}
			类型：{{ type }} 实付金额：{{ payPrice }} 场地信息：{{ orderInfo }}
		</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">
				<block v-for="(item, index) in payment" :key="index">
					<uv-cell
						:title="`${item.name}`"
						:icon="`${item.image}`"
						:cellStyle="{ padding: '20rpx 10rpx', borderRadius: '8rpx', backgroundColor: item.type == payType ? '#f6fff1' : '' }"
						:border="false"
						@click="onPayType(item.type)"
					>
						<template v-slot:right-icon>
							<uv-icon v-if="item.type == payType" size="30rpx" name="checkbox-mark"></uv-icon>
						</template>
					</uv-cell>
				</block>
			</uv-cell-group>
			<view slot="actions" class="card-actions">
				<view class="card-actions-item">
					<span class="web-text-danger">已优惠￥{{ reducePrice }}</span>
					<span class="web-text-heading">￥{{ payPrice || 0.0 }}</span>
				</view>
			</view>
		</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 decimals="2" duration="30" color="#ebcf00" bold :endVal="payPrice"></uv-count-to>
			</view>
			<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" dot :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 * as PaymentApi from '@/api/system/payment';
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 { merchantId, orderInfo, totalPrice, reducePrice, payPrice, carNum, merchant, type, dateTime } = storeToRefs(carStore);

export default {
	data() {
		return {
			orderId: 0,
			userInfo: {},
			// 表单信息
			form: {
				cardId: 0
			},
			// 支付方式
			payment: [],
			// 场馆信息
			merchant,
			merchantId,
			orderInfo,
			carNum,
			week: 0,
			totalPrice,
			reducePrice: 0,
			payPrice: 0,
			cardId: 0,
			getWeek,
			payType: 1,
			isLogin: false,
			disabled: false,
			cardList: [],
			userCard: {},
			isRefresh: true,
			// 支付密码是否正确
			isPayPasswordCorrect: false,
			disabledPayPayPassword: false,
			payPassword: '',
			// 折扣率
			discount: 1
		};
	},
	onLoad(option) {
		if (option.id) {
			this.orderId = option.id;
			this.form.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 { form, orderId, merchant, totalPrice, orderInfo } = this;

			// 当前登录用户信息
			app.userInfo = await userStore.fetchUserInfo();

			// 整理订单信息
			form.type = 1; // 订单类型 0商城订单 1预定订单
			form.payPrice = totalPrice;
			form.orderInfo = orderInfo;
			if (merchant) {
				app.merchantId = merchant.merchantId;
				form.merchantId = merchant.merchantId;
				form.merchantName = merchant.merchantName;
				form.merchantCode = merchant.merchantCode;
				form.comments = merchant.merchantName + ' ' + orderInfo[0].fieldName + ' ' + orderInfo[0].dateTime;
			}

			// 重新赋值订单信息
			if (orderId > 0) {
				Api.getOrder(orderId).then((data) => {
					app.form = data;
					app.orderInfo = data.orderInfo;
					app.totalPrice = data.totalPrice;
					app.reducePrice = data.reducePrice;
					app.payPrice = data.payPrice;
					app.merchantId = data.merchantId;
				});
			}

			// 请求数据
			Promise.all([app.getUserCard(), app.getPayment()]).then((res) => {
				const userCard = res[0];
				const payment = res[1];
				// 当前可用会员卡
				app.userCard = userCard;
				// 支付方式列表
				app.payment = payment.map((d) => {
					if (d.type == 0) {
						d.name = `${d.name} (余额￥${app.userInfo.balance})`;
					}
					if (d.type == 2 && userCard) {
						d.name = `${userCard.name}（￥${userCard.remainingMoney}）`;
					}
					return d;
				});

				if (userCard) {
					// 整理表单字段
					form.cardId = userCard.id;
					form.payType = 2;
					app.payType = 2;

					// 1年卡
					if (userCard.type == 1) {
					}

					// 2次卡
					if (userCard.type == 2) {
					}

					// 3月卡
					if (userCard.type == 3) {
					}

					// 4会员IC卡
					if (userCard.type == 2) {
					}
					// 5充值卡
					if (userCard.type == 5) {
						// 折扣率
						app.discount = cal.cheng(userCard.discount, 0.1);

						// 订单金额
						const orderPrice = totalPrice || form.totalPrice;
						if (orderPrice) {
							console.log('orderPrice: ', orderPrice);
							// 折后金额
							const lastTotalPrice = cal.cheng(orderPrice, app.discount);
							console.log('折后金额: ', lastTotalPrice);
							// 减少的金额
							app.reducePrice = cal.jian(orderPrice, lastTotalPrice);
							console.log('减少的金额: ', app.reducePrice);
							// 实付额
							app.payPrice = orderPrice * app.discount;
							console.log('实付额: ', app.payPrice);
						}
					}
				}
			});
		},
		// 读取可用的会员卡
		async getUserCard() {
			const app = this;
			return new Promise((resolve, reject) => {
				const { merchantId } = this;
				UserCardApi.findUseCard({
					sid: merchantId
				})
					.then((result) => {
						resolve(result);
					})
					.catch(reject);
			});
		},
		// 读取支付方式列表
		getPayment() {
			const app = this;
			return new Promise((resolve, reject) => {
				PaymentApi.select({ status: true })
					.then((result) => {
						resolve(result);
					})
					.catch(reject);
			});
		},
		onDisabled() {
			this.disabled = !this.disabled;
		},
		navTo(url) {
			uni.navigateTo({
				url
			});
		},
		// 切换支付方式
		onPayType(index) {
			const app = this;
			const { form, totalPrice } = this;
			app.payType = index;
			app.form.payType = index;
			app.form.cardId = 0;
			console.log('index: ',index);
			if (index == 2) {
				app.isRefresh = true;
				app.reload();
			} else {
				app.isRefresh = false;
				app.reducePrice = 0;
				app.payPrice = totalPrice;
			}
		},
		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, merchant, orderInfo, totalPrice, payPrice } = this;
			if (!this.disabled) {
				uni.showToast({
					title: '请先阅读并同意服务协议',
					icon: 'none'
				});
				return false;
			}
			if (orderInfo.length == 0) {
				uni.showToast({
					title: '订单信息不存在',
					icon: 'none'
				});
				return false;
			}
			if (form.payType == 2 && !app.userCard){
				uni.showToast({
					title: '没有找到可用的会员卡',
					icon: 'none'
				});
				return false;
			}

			if (form.payType == 0 && !this.isPayPasswordCorrect) {
				app.$refs.payPasswordForm.open('center');
				return false;
			}
			uni.showLoading({
				title: '订单提交中.'
			});

			form.payPrice = app.payPrice;
			form.totalPrice = app.totalPrice;
			form.reducePrice = app.reducePrice;

			Api.addOrder({
				type: 1,
				orderId: form.orderId,
				merchantId: form.merchantId,
				merchantName: form.merchantName,
				merchantCode: form.merchantCode,
				// 订单金额
				totalPrice: form.totalPrice,
				// 实付金额
				payPrice: form.payPrice,
				// 预定场地信息
				orderInfo: form.orderInfo,
				comments: form.comments,
				// 微信支付
				payType: form.payType,
				// 下单日期
				dateTime: form.dateTime,
				// 会员卡ID
				cardId: form.cardId
			})
				.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;
								app.$refs.payPasswordForm.close()
								uni.reLaunch({
									url: '/pages/order/order',
									success: function (e) {
										var page = getCurrentPages()[0];
										if (page == undefined || page == null) return;
										page.onLoad();
									}
								});
							}, 1500);
						}
					}

					// 使用会员卡支付
					if (form.payType == 2) {
						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;
	min-height: 300rpx;
	margin: 30rpx auto;
	background-color: #ffffff;
	text-align: center;
	display: flex;
	justify-content: center;
	flex-direction: column;
	align-items: center;
	.web-text-primary {
		line-height: 2rem;
		padding: 20rpx 0;
	}
}
.to-pay-btn {
	width: 400rpx !important;
	margin: 40rpx auto;
}
</style>
