<template>
	<uni-popup ref="authPopup" type="bottom" :mask-click="false">
		<view class="auth-popup">
			<view class="close-icon" @tap="closePopup">
				<uni-icons type="close" size="24" color="#999"></uni-icons>
			</view>
			<view>
				<button class="login-btn" @tap="handleLoginClick">授权登录</button>
				<view class="agreement-wrapper">
					<view class="checkbox-wrapper" @tap="toggleAgreement">
						<view class="zen-checkbox" :class="{ 'checked': isAgree }">
							<view class="zen-circle-inner" v-if="isAgree"></view>
						</view>
					</view>
					<view class="agreement-text">
						登录即代表您已同意
						<text class="agreement-link" @tap.stop="goToPrivacy">《隐私政策》</text>
						和
						<text class="agreement-link" @tap.stop="goToService">《服务协议》</text>
					</view>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		wxLogin
	} from '@/config/api.js';

	export default {
		name: 'AuthLoginPopup',
		data() {
			return {
				// 默认用户信息
				defaultUser: {

				},
				// 是否同意协议
				isAgree: false
			};
		},
		methods: {
			// 切换协议同意状态
			toggleAgreement() {
				this.isAgree = !this.isAgree;
			},

			// 处理登录按钮点击
			handleLoginClick() {
				if (!this.isAgree) {
					// 未勾选协议，弹出确认框
					let that = this;
					uni.showModal({
						title: '提示',
						content: '登录需要您同意《隐私政策》和《服务协议》，是否同意？',
						confirmText: '同意',
						cancelText: '取消',
						success: function(res) {
							if (res.confirm) {
								// 用户点击同意，自动勾选协议并执行登录
								that.isAgree = true;
								that.handleLogin();
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					// 已勾选协议，直接登录
					this.handleLogin();
				}
			},
			// 打开弹窗
			open() {
				this.$refs.authPopup.open();
			},

			// 关闭弹窗
			close() {
				this.$refs.authPopup.close();
			},

			// 关闭授权弹窗
			closePopup() {
				this.close();
				this.$emit('close');
			},

			// 处理微信授权登录
			async handleLogin() {
				uni.showLoading({
					title: '登录中...',
					mask: true
				});

				try {
					// 获取用户信息
					const profileRes = await this.getUserProfilePromise();
					console.log('用户信息:', profileRes);

					// 获取登录凭证
					const loginRes = await this.wxLoginPromise();
					console.log('登录凭证code:', loginRes.code);

					// 调用后端登录接口
					const loginData = await wxLogin({
						code: loginRes.code
					});
					console.log('登录响应:', loginData);

					// 检查登录是否成功
					if (loginData.openid || loginData.code === 200 || loginData.message === "登录成功") {
						// 如果用户信息为空，使用默认用户信息
						if (!loginData.user || loginData.user === null) {
							console.log('用户信息为空，使用默认用户信息');
							loginData.user = this.defaultUser;
						}

						// 保存 token
						const token = loginData.token || loginData.access_token;
						if (token) {
							uni.setStorageSync('access_token', token);
							uni.setStorageSync('token', token);
						}

						// 保存 refresh_token
						if (loginData.refresh_token) {
							uni.setStorageSync('refresh_token', loginData.refresh_token);
						}

						// 保存完整的登录数据
						uni.setStorageSync('loginData', loginData);

						// 保存用户信息
						uni.setStorageSync('user', loginData.user);

						// 保存 openid
						if (loginData.openid) {
							uni.setStorageSync('openid', loginData.openid);
						}

						// 更新 store 状态
						this.$store.commit('isLogin', true);
						if (loginData.refresh_token) {
							this.$store.commit('refresh_token', loginData.refresh_token);
						}

						uni.hideLoading();

						// 关闭授权弹窗
						this.close();

						// 显示登录成功提示
						uni.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 1500
						});

						// 触发登录成功事件，传递用户信息
						this.$emit('success', loginData.user);

					} else {
						uni.hideLoading();
						uni.showToast({
							title: loginData.msg || loginData.message || '登录失败',
							icon: 'none'
						});
						this.$emit('fail', loginData);
					}
				} catch (error) {
					console.error('登录错误:', error);
					uni.hideLoading();
					uni.showToast({
						title: error.message || '登录失败，请重试',
						icon: 'none'
					});
					this.$emit('error', error);
				}
			},

			// 获取用户信息 Promise 封装
			getUserProfilePromise() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						desc: '用于完善会员资料',
						success: (res) => resolve(res),
						fail: (err) => {
							if (err.errMsg.includes('cancel')) {
								reject(new Error('用户取消授权'));
							} else {
								reject(new Error('获取用户信息失败'));
							}
						}
					});
				});
			},

			// 微信登录 Promise 封装
			wxLoginPromise() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: (res) => resolve(res),
						fail: (err) => reject(new Error('获取登录凭证失败'))
					});
				});
			},

			// 跳转到隐私政策
			goToPrivacy() {
				uni.navigateTo({
					url: '/pagesA/public/richtext'
				});
			},

			// 跳转到服务协议
			goToService() {
				uni.navigateTo({
					url: '/pagesA/public/richtext'
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	// 确保 uni-popup 组件的 z-index 足够高
	::v-deep .uni-popup {
		z-index: 9999 !important;
	}

	::v-deep .uni-popup__wrapper {
		z-index: 9999 !important;
	}

	.auth-popup {
		width: 100%;
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 60rpx 40rpx 50rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		position: relative;
		z-index: 10000;
	}

	.close-icon {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		z-index: 10001;

		&:active {
			opacity: 0.6;
		}
	}

	.login-btn {
		width: 100%;
		height: 88rpx;
		background-color: #FF5B05;
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 600;
		margin-bottom: 40rpx;
	}

	.login-btn:after {
		border: none;
	}

	.agreement-wrapper {
		display: flex;
		align-items: flex-start;
		justify-content: center;
		gap: 16rpx;
		padding: 0 20rpx;
	}

	.checkbox-wrapper {
		flex-shrink: 0;
		padding-top: 4rpx;
	}

	.zen-checkbox {
		width: 36rpx;
		height: 36rpx;
		border: 2rpx solid rgba(255, 91, 5, 0.4);
		border-radius: 18rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		background: rgba(255, 255, 255, 0.9);

		&.checked {
			background: #FF5B05;
			border-color: #FF5B05;
		}

		.zen-circle-inner {
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background: #fff;
		}
	}

	.agreement-text {
		font-size: 24rpx;
		color: rgba(41, 44, 53, 0.6);
		line-height: 36rpx;
		flex: 1;
		text-align: left;
	}

	.agreement-link {
		color: #FF5B05;
		text-decoration: none;
	}
</style>
