<template>
	<view class="login-main">
		<view style="width: 100%">
			<view style="width: 100%; height: 270rpx">
				<image class="img" src="../../static/images/payBack.png" style="width: 100%; height: 100%"></image>
			</view>
		</view>
		<view class="main">
			<view class="login-main-content">
				<image class="img" :src="shopInfo.shopLogoUrl ? shopInfo.shopLogoUrl : '/static/images/error.jpeg'"
					mode=""></image>
				<h4 class="shopName">{{ shopInfo ? shopInfo.shopName : "" }}</h4>
			</view>

			<view class="login-contont">
				<view class="uInput">
					<u-input placeholder="请输入金额" border="bottom" :fontSize="40" type="digit" v-model="price"
						:customStyle="inpustyle" @input="handlePriceChange">
						<span slot="prefix" style="font-size: 30px">￥</span>
					</u-input>
				</view>

				<view class="pay-info" v-if="voucherRadio">
					<text>抵扣代金券后，实付金额</text>
					<text class="price"> {{ payment }}</text>
				</view>

				<view class="login-contont-button">
					<button class="btn" @tap="Pay">立即支付</button>

					<view style="padding: 0 30rpx">
						<view class="cell-item">
							<u-cell-group :border="false">
								<u-cell title="代金券折扣" :border="false" isLink @tap="voucher">
									<template slot="value">
										<text style="color: orange;">{{ CellText }}</text>
									</template>
								</u-cell>
							</u-cell-group>
						</view>

						<view class="tip">
							支付成功后，次日将有随机奖励红包以及店铺代金券，可抵现金花，AI天枢云小程序领取
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 绑定手机号弹窗 -->
		<u-popup :show="showPhone" mode="center" round="20">
			<view class="popup">
				<view class="header">
					<h4>绑定手机号</h4>
					<p class="tip">提示：首次登录请绑定手机号</p>
				</view>

				<view class="main">
					<view class="input-item">
						<u-input placeholder="请输入手机号" type="number" v-model="phone" :adjustPosition="true" />
					</view>
					<view class="input-item">
						<u-input placeholder="验证码" v-model="yzm" :adjustPosition="true">
							<template slot="suffix">
								<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
								<text class="yzm-btn" @tap="getCode">{{ tips ? tips : "发送验证码" }}</text>
							</template>
						</u-input>
					</view>
				</view>

				<view class="footer">
					<u-button type="primary" class="btn" text="确定" @tap="submitOk"></u-button>
				</view>
			</view>
		</u-popup>

		<u-popup :show="showPopup" mode="bottom" :round="20">
			<view class="coupon-popup">
				<view class="popup-header">
					<text class="title">店铺代金券</text>
					<u-icon name="close" size="22" @tap="showPopup = false" />
				</view>

				<view class="coupon-list">
					<u-radio-group v-model="voucherRadio" placement="column" @change="groupChange" iconSize="30"
						size="40">
						<view class="coupon-item" :class="item.status === 0 ? 'disabled' : 'active'"
							v-for="(item, index) in couponList" :key="index" @tap="selectCoupon(index)">
							<view class="left">
								<view class="tag" :class="item.voucherType === 1 ? 'independent' : 'chain'">
									{{ item.voucherType === 1 ? '独立券' : item.voucherType === 2 ? '连锁券' : '联合券' }}
								</view>
								<view class="price">
									<text class="yen">¥</text>
									<text class="num">{{ item.amount }}</text>
									<text class="tip">{{ item.voucherRule == 1 ? '无门槛' : '满' + item.minOrderAmount + '减'
										+
										item.discountAmount }}</text>
								</view>
								<view class="info">
									<text>{{ item.createTime }}</text>
									<!-- <text>{{ item.scope }}</text> -->
								</view>
							</view>
							<view class="right">
								<u-radio :name="item.id" iconSize="30" />
							</view>
						</view>
					</u-radio-group>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import api from "@/api/index.js";
import { requestConfig } from "@/app.config.js";
export default {
	data() {
		return {
			showPhone: false,
			showPopup: false,

			requestConfig: requestConfig,
			code: "",
			userInfo: {},
			inpustyle: {
				fontWeight: "bold",
				fontSize: "40px",
			},
			phone: "",
			yzm: "",
			tips: null,
			price: "",
			shopId: "",
			storeId: "",
			shopInfo: {},
			zfbInfo: {},
			localUserInfo: null,
			couponList: [],
			couponId: "",
			CellText: "暂无代金券",
			payment: "",
			voucherRadio: false,
		};
	},
	onLoad(options) {
		this.zfbInfo = options;
		this.uid = options.uid || "";
		this.shopId = options.shopId || "";
		this.storeId = options.storeId || "";
		// 读取本地支付宝用户信息
		let info = uni.getStorageSync("aliPayUserInfo");
		if (info) {
			this.localUserInfo = JSON.parse(info);
		}
		// 登录逻辑
		if (this.localUserInfo) {
			this.getShopInfo();
			this.getVoucher();
			this.getPhoneBind();
		} else {
			if (this.zfbInfo.auth_code) {
				this.getInfo();
			} else {
				uni.$u.toast("授权信息失效，请重新进入");
			}
		}
	},
	methods: {
		// 输入金额时自动重置代金券计算
		handlePriceChange() {
			this.payment = "";
			this.couponId = "";
			this.voucherRadio = false;
			this.CellText = this.couponList.length
				? `可使用${this.couponList.length}个`
				: "暂无代金券";
		},

		// 选择代金券
		groupChange(e) {
			this.showPopup = false;
			let target = this.couponList.find((item) => item.id === e);
			if (!target) return;

			if (target.voucherRule === 1) {
				this.CellText = `- ￥${target.amount}`;
			} else {
				this.CellText = `满${target.minOrderAmount}减${target.discountAmount}`;
			}

			let pay = Number(this.price) - Number(target.amount || 0);
			this.payment = pay > 0 ? pay.toFixed(2) : "0.01";
			this.voucherRadio = true;
		},

		// 获取可用代金券
		getVoucher() {
			if (!this.storeId) return;
			api.availableList({
				storeId: this.storeId,
			}).then((res) => {
				if (res.code == 200) {
					this.couponList = res.data.filter((item) => item.applyAllProducts !== 0);
					if (this.couponList.length > 0) {
						this.CellText = `可使用${this.couponList.length}个`;
					} else {
						this.CellText = "暂无代金券";
					}
				}
			});
		},

		// 打开代金券选择
		voucher() {
			if (!this.price || Number(this.price) <= 0) {
				return uni.$u.toast("请输入正确的支付金额！");
			}
			if (this.couponList.length === 0) {
				return uni.$u.toast("暂无可用代金券");
			}
			this.showPopup = true;
		},

		// 检查是否绑定手机号
		getPhoneBind() {
			api.checkBindPhone().then((res1) => {
				// this.showPhone = res1.code !== 200 || res1.data.bindPhoneStatus === 0;
			}).catch(() => {
				this.showPhone = true;
			});
		},

		// 支付宝授权登录
		getInfo() {
			uni.showLoading({ title: "登录中..." });
			api.weChatH5Login({
				code: this.zfbInfo.auth_code,
				grant_type: "ali",
			}).then((res) => {
				uni.hideLoading();
				if (res.code == 200) {
					this.userInfo = res.data;
					uni.setStorageSync("token", this.userInfo.access_token)
					uni.setStorageSync("aliPayUserInfo", JSON.stringify(this.userInfo))
					// localStorage.setItem("token", this.userInfo.access_token);
					// localStorage.setItem("aliPayUserInfo", JSON.stringify(this.userInfo));
					this.getShopInfo();
					this.getVoucher();
					this.getPhoneBind();
					uni.hideLoading();
				} else {
					uni.$u.toast("登录失败，请重试");
					uni.hideLoading();
				}
			}).catch(() => {
				uni.hideLoading();
				uni.$u.toast("登录异常");
			});
		},

		// 支付
		Pay() {
			if (!this.price || Number(this.price) <= 0) {
				return uni.$u.toast("请输入支付金额");
			}
			if (!this.shopInfo || !this.shopInfo.shopId) {
				return uni.$u.toast("店铺信息异常");
			}
			uni.showLoading({ title: "支付中..." });
			let payAmount = this.payment || this.price;
			api.payOrder({
				shopType: this.shopInfo.shopType,
				shopUserId: this.shopInfo.shopUserId,
				shopId: this.shopInfo.shopId,
				payAmount: Number(payAmount).toFixed(2),
				payWay: 7,
			}).then((pay) => {
				uni.hideLoading();
				if (pay.code == 200) {
					let url = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(pay.data.result)}`;
					window.location.href = url;
				} else {
					uni.$u.toast(pay.msg);
				}
			}).catch((err) => {
				uni.hideLoading();
				uni.$u.toast("支付请求失败");
			});
		},

		// 获取店铺信息
		getShopInfo() {
			if (!this.shopId) return;
			api.getStoreInfoByScan({
				shopId: this.shopId,
			}).then((res) => {
				if (res.code == 200) {
					this.shopInfo = res.data;
				} else {
					uni.$u.toast(res.msg);
				}
			});
		},

		restLogin() {
			api.weChatH5Login({
				grant_type: "pwd",
				phone: this.phone,
				password: 123456,
			}).then((res) => {
				if (res.code == 200) {
					this.userInfo = res.data;
					uni.setStorageSync("token", this.userInfo.access_token)
					uni.setStorageSync("aliPayUserInfo", JSON.stringify(this.userInfo));
					this.getPhoneBind()
				}
			})
		},
		// 绑定手机号提交（支付宝浏览器完美修复版）
		submitOk() {
			// 防重复提交
			if (this.isSubmitting) return;
			this.isSubmitting = true;

			if (!this.phone) return uni.$u.toast("请输入手机号");
			if (!this.yzm) return uni.$u.toast("请输入验证码");

			// 支付宝浏览器核心修复：延迟请求
			setTimeout(() => {
				uni.showLoading({ title: "正在绑定中..." });
				let params = {
					mobile: this.phone,
					code: this.yzm,
					password: "123456",
					confirmPassword: "123456",
					type: 0,
				};

				api.bindH5Phone(params).then((res) => {
					uni.hideLoading();
					this.isSubmitting = false;
					if (res.code == 200) {
						uni.$u.toast("绑定成功");
						this.showPhone = false;
						this.restLogin();
					} else {
						uni.$u.toast(res.msg || "绑定失败");
					}
				}).catch((err) => {
					uni.hideLoading();
					this.isSubmitting = false;
					console.error("绑定错误：", err);
					uni.$u.toast("绑定失败，请重试");
				});
			}, 200);
		},
		codeChange(text) {
			this.tips = text;
		},
		// 获取验证码（支付宝终极修复版）
		async getCode() {
			if (!this.$refs.uCode.canGetCode) return;
			if (!this.phone) return uni.$u.toast("请输入手机号");
			api.sendSms({ phone: this.phone, type: 0 }).then((res) => {
				if (res.code == 200) {
					uni.$u.toast("验证码已发送");
					this.$refs.uCode.start();
				} else {
					uni.$u.toast(res.msg || "发送失败");
				}
			}).catch((err) => {
				alert(JSON.stringify(err));
				uni.hideLoading();
				uni.$u.toast("发送失败");
			});
		},
	}
};
</script>

<style lang="scss" scoped>
.info {
	font-size: 24rpx;
	color: #999;
	line-height: 1.6;
}

.right {
	padding-left: 20rpx;
}

.tag {
	font-size: 22rpx;
	color: #fff;
	padding: 4rpx 12rpx;
	border-radius: 6rpx;
	margin-bottom: 12rpx;
}

.login-main {
	background: url("../../static/images/payBack.png");
	background-size: cover;
	width: 100%;
	height: 100vh;
}

.main {
	width: 100%;
	background: #fff;
	height: calc(100% - 270rpx);
	border-radius: 40rpx 40rpx 0 0;
}

.login-main-content {
	display: flex;
	align-items: center;
	padding: 30rpx 30rpx 0;

	.img {
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.shopName {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
}

.login-contont {
	padding: 40rpx 30rpx;
}

.uInput {
	border-bottom: 0.5px solid #eee;
	padding: 10rpx 0;
}

.pay-info {
	padding: 20rpx 0;
	font-size: 26rpx;
	color: #666;

	.price {
		color: orange;
		font-size: 40rpx;
		margin-left: 10rpx;
	}
}

.yen {
	font-size: 28rpx;
	color: #ff4d4f;
}

.num {
	font-size: 44rpx;
	font-weight: bold;
	color: #ff4d4f;
	margin: 0 10rpx;
}

.login-contont-button {
	text-align: center;

	.btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(152deg, #6f9dfd 0%, #1b71f2 100%);
		border-radius: 44rpx;
		color: #fff;
		font-size: 32rpx;
		border: none;
		margin-top: 30rpx;
	}
}

.cell-item {
	background: #fff7f6;
	margin-top: 40rpx;
	border-radius: 12rpx;
}

.tip {
	margin-top: 20rpx;
	font-size: 26rpx;
	color: #999;
	line-height: 1.5;
}

.popup {
	padding: 30rpx;

	.header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.input-item {
		margin-bottom: 30rpx;
	}

	.footer {
		margin-top: 60rpx;
	}

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

.independent {
	width: 70rpx;
	background: #5c8dff;
}

.chain {
	width: 70rpx;
	background: #ff7d00;
}

.left {
	flex: 1;
}

.coupon-popup {
	padding: 30rpx;
	height: 1000rpx;
	box-sizing: border-box;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 30rpx;
}



.coupon-list {
	height: calc(100% - 100rpx);
	overflow-y: auto;
}

.coupon-item {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border: 2rpx solid #eee;
}

.coupon-item.active {
	// border-color: #ff4d4f;
	background: #fffbf4;
}

.coupon-item.disabled {
	opacity: 0.5;
}

::v-deep .u-cell__title {
	flex: none !important;
}
</style>