<template>
	<view class="login-bg">
		<view class="login-box">
			<view class="login-title">欢迎登录</view>
			<view class="login-tabs">
				<view :class="['tab', loginType === 'phone' ? 'active' : '']" @click="loginType = 'phone'">手机号登录</view>
				<view :class="['tab', loginType === 'account' ? 'active' : '']" @click="loginType = 'account'">账号密码登录</view>
			</view>
			<view v-if="loginType === 'phone'" class="login-form">
				<input class="login-input" type="text" placeholder="请输入手机号" v-model="phone" />
				<view class="code-row">
					<input class="login-input code-input" type="text" placeholder="请输入验证码" v-model="code" />
					<button class="code-btn" @click="sendCode" :disabled="loginCodeTimer > 0 || isSendingLoginCode">
						{{ loginCodeTimer > 0 ? loginCodeTimer + 's' : '获取验证码' }}
					</button>
				</view>
			</view>
			<view v-else class="login-form">
				<input class="login-input" type="text" placeholder="请输入账号" v-model="username" />
				<input class="login-input" type="password" password placeholder="请输入密码" v-model="password" />
				<view class="form-actions">
					<text class="login-link" @click="toRegister">去注册</text>
					<text class="forgot-password-link" @click="toForgot">忘记密码？</text>
				</view>
			</view>
			<button class="login-btn" :disabled="!agreed" @click="doLogin">登录</button>
			<view class="login-agree">
				<checkbox :checked="agreed" @click="agreed = !agreed" />
				<text>我已阅读并同意</text>
				<text class="link" @click="openAgreement">《服务协议》</text>
				<text>和</text>
				<text class="link" @click="openPrivacy">《隐私政策》</text>
			</view>
			<view class="login-divider">第三方账号登录</view>
			<button class="wechat-btn" @click="oneClickLogin">
				<image src="/static/yx-icon.png" class="icon" /> 邮箱登录
			</button>
			
		</view>
	</view>

	<!-- 注册弹窗 -->
	<view v-if="showRegisterPopup" class="popup-overlay">
		<view class="register-popup-content">
			<view class="popup-title">注册账号</view>
			<view class="register-form">
				<input class="login-input" type="text" placeholder="请输入手机号" v-model="regPhone" />
				<view class="code-row">
					<input class="login-input code-input" type="text" placeholder="请输入验证码" v-model="regCode" />
					<button class="code-btn" @click="sendRegCode" :disabled="regCodeTimer > 0 || isSendingRegCode">
						{{ regCodeTimer > 0 ? regCodeTimer + 's' : '获取验证码' }}
					</button>
				</view>
				<input class="login-input" type="text" placeholder="请输入账号" v-model="regUsername" />
				<input class="login-input" type="password" password placeholder="请输入密码" v-model="regPassword" />
			</view>

			<button class="login-btn" @click="doRegister">注册</button>

			<view class="close-btn" @click="showRegisterPopup = false">
					<image src="/static/cw.png" class="icon"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginType: 'phone', // 'phone' or 'account'
				phone: '',
				code: '',
				username: '',
				password: '',
				agreed: false,

				showRegisterPopup: false,
				regPhone: '',
				regCode: '',
				regUsername: '',
				regPassword: '',
				regCodeTimer: 0, // Countdown timer for registration code
				isSendingRegCode: false, // Flag to prevent multiple requests
				loginCodeTimer: 0, // Countdown timer for login code
				isSendingLoginCode: false, // Flag to prevent multiple requests
			}
		},
		methods: {
			// 处理微信登录
			async oneClickLogin() {
				console.log('WeChat login button clicked');
				// 1. 先获取用户信息
					uni.getUserProfile({
						desc: '用于完善用户资料',
						lang: 'zh_CN',
						success: (userRes) => {
							console.log(userRes)
							// 2. 获取微信登录凭证
							uni.showLoading({ title: '登录中...', mask: true })
							uni.login({
								provider: 'weixin',
								success: wx_res => {
									// 3. 发送登录请求，参数按后端WeLogin类
									console.log('uni.getUserProfile success:', userRes);
									console.log('uni.login success, got code:', wx_res.code);
									uni.request({
										url: 'http://localhost:8081/WeChart/login',
										method: 'POST',
										data: {
											code: wx_res.code,
											weChatLoginDto: userRes.userInfo,
											
										},
										header: { 'content-type': 'application/json' },
										success: (res) => {
											uni.hideLoading()
											if (res.statusCode === 200 && res.data) {
												console.log('Backend login success:', res.data);
												uni.showToast({ title: '登录成功', icon: 'success' });
												setTimeout(() => {
													uni.switchTab({ url: '/pages/home/index' })
												}, 1500)
											} else {
												console.error('Backend login failed:', res);
												uni.showToast({ title: res.data?.message || '登录失败', icon: 'none' })
											}
										},
										fail: (err) => {
											uni.hideLoading()
											console.error('Backend request failed:', err);
											uni.showToast({ title: '微信登录失败', icon: 'none' })
										}
									})
								},
								fail: (err) => {
									uni.hideLoading()
									console.error('uni.login failed:', err);
									uni.showToast({ title: '微信登录失败', icon: 'none' })
								}
							})
						},
						fail: (err) => {
							console.error('uni.getUserProfile failed:', err);
							uni.showToast({ title: '获取用户信息失败', icon: 'none' })
						}
					})	
			},
			async sendCode() {
				if (this.isSendingLoginCode || this.loginCodeTimer > 0) {
					return;
				}
				if (!this.phone) {
					uni.showToast({ title: '请输入手机号', icon: 'none' });
					return;
				}

				this.isSendingLoginCode = true;
				uni.showLoading({ title: '发送中...', mask: true });

				try {
					const res = await uni.request({
						url: 'http://localhost:8081/user/code',
						method: 'POST',
						data: {
							phone: this.phone
						},
						header: { 'content-type': 'application/json' }
					});

					uni.hideLoading();
					this.isSendingLoginCode = false;

					if (res.statusCode === 200 && res.data) {
						console.log('Send login code success:', res.data);
						uni.showToast({ title: '验证码已发送', icon: 'success' });

						// Start countdown
						this.loginCodeTimer = 60;
						const timerInterval = setInterval(() => {
							this.loginCodeTimer--;
							if (this.loginCodeTimer <= 0) {
								clearInterval(timerInterval);
								this.loginCodeTimer = 0;
							}
						}, 1000);

					} else {
						console.error('Send login code failed:', res);
						uni.showToast({ title: res.data?.message || '发送失败', icon: 'none' });
					}
				} catch (err) {
					uni.hideLoading();
					this.isSendingLoginCode = false;
					console.error('Send login code request failed:', err);
					uni.showToast({ title: '登录失败', icon: 'none' });
				}
			},
			async doLogin() {
				if (!this.agreed) {
					uni.showToast({ title: '请先同意协议', icon: 'none' });
					return;
				}

				if (this.loginType === 'phone') {
					// 手机号+验证码登录
					if (!this.phone || !this.code) {
						uni.showToast({ title: '请填写手机号和验证码', icon: 'none' });
						return;
					}
					uni.showLoading({ title: '登录中...', mask: true });
					try {
						const res = await uni.request({
							url: 'http://localhost:8081/user/login',
							method: 'POST',
							data: {
								phone: this.phone,
								code: this.code
							},
							header: { 'content-type': 'application/json' }
						});
						uni.hideLoading();
						if (res.statusCode === 200 && res.data) {
							uni.showToast({ title: '登录成功', icon: 'success' });
							setTimeout(() => {
								uni.switchTab({ url: '/pages/home/index' });
							}, 1500);
						} else {
							uni.showToast({ title: res.data?.message || '登录失败', icon: 'error' });
						}
					} catch (err) {
						uni.hideLoading();
						uni.showToast({ title: '登录失败', icon: 'none' });
					}
				} else if (this.loginType === 'account') {
					// 账号+密码登录
					if (!this.username || !this.password) {
						uni.showToast({ title: '请填写账号和密码', icon: 'none' });
						return;
					}
					uni.showLoading({ title: '登录中...', mask: true });
					try {
						const res = await uni.request({
							url: 'http://localhost:8081/user/UserPassLogin',
							method: 'POST',
							data: {
								username: this.username,
								password: this.password
							},
							header: { 'content-type': 'application/json' }
						});
						uni.hideLoading();
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							uni.showToast({ title: '登录成功', icon: 'success' });
							setTimeout(() => {
								uni.switchTab({ url: '/pages/home/index' });
							}, 1500);
						} else {
							uni.showToast({ title: res.data?.msg || '登录失败', icon: 'error' });
						}
					} catch (err) {
						uni.hideLoading();
						uni.showToast({ title: '登录失败', icon: 'none' });
					}
				}
			},
			toRegister() {
				this.showRegisterPopup = true;
			},
			toForgot() {
				uni.showToast({ title: '跳转找回密码', icon: 'none' });
			},
			openAgreement() {
				uni.navigateTo({ url: '/pages/agreement/agreement' });
			},
			openPrivacy() {
				uni.navigateTo({ url: '/pages/privacy/privacy' });
			},
			qqLogin() {
				uni.showToast({ title: 'QQ登录', icon: 'none' });
			},
			async sendRegCode() {
				// 如果正在发送或倒计时中，则不执行任何操作
				if (this.isSendingRegCode || this.regCodeTimer > 0) {
					return;
				}
				// 检查手机号是否已填写
				if (!this.regPhone) {
					uni.showToast({ title: '请输入手机号', icon: 'none' });
					return;
				}

				// 设置状态，显示加载提示
				this.isSendingRegCode = true;
				uni.showLoading({ title: '发送中...', mask: true });

				try {
					// 发起POST请求到后端接口
					const res = await uni.request({
						url: 'http://localhost:8081/user/code',
						method: 'POST',
						data: {
							phone: this.regPhone // 发送手机号参数
						},
						header: { 'content-type': 'application/json' }
					});

					// 隐藏加载提示，重置发送状态
					uni.hideLoading();
					this.isSendingRegCode = false;

					// 根据后端响应处理结果
					if (res.statusCode === 200 && res.data) {
						console.log('Send registration code success:', res.data);
						uni.showToast({ title: '验证码已发送', icon: 'success' });

						// 开始60秒倒计时
						this.regCodeTimer = 60;
						const timerInterval = setInterval(() => {
							this.regCodeTimer--;
							if (this.regCodeTimer <= 0) {
								clearInterval(timerInterval); // 倒计时结束时清除定时器
								this.regCodeTimer = 0;
							}
						}, 1000); // 每秒更新
					} else {
						// 处理发送失败的情况
						console.error('Send registration code failed:', res);
						uni.showToast({ title: res.data?.message || '发送失败', icon: 'none' });
					}
				} catch (err) {
					// 处理请求异常
					uni.hideLoading();
					this.isSendingRegCode = false;
					console.error('Send registration code request failed:', err);
					uni.showToast({ title: '发送失败', icon: 'none' });
				}
			},
			async doRegister() {
				if (!this.regPhone || !this.regCode || !this.regUsername || !this.regPassword) {
					uni.showToast({ title: '请填写所有注册信息', icon: 'none' });
					return;
				}

				uni.showLoading({ title: '注册中...', mask: true });

				try {
					const res = await uni.request({
						url: 'http://localhost:8081/user/register',
						method: 'POST',
						data: {
							phone: this.regPhone,
							code: this.regCode,
							username: this.regUsername,
							password: this.regPassword
						},
						header: { 'content-type': 'application/json' }
					});

					uni.hideLoading();

					if (res.statusCode === 200 && res.data) {
						console.log('Registration success:', res.data);
						uni.showToast({ title: '注册成功', icon: 'success' });
						// Optionally, clear the form fields
						this.regPhone = '';
						this.regCode = '';
						this.regUsername = '';
						this.regPassword = '';
						// Close the popup after successful registration
						setTimeout(() => {
							this.showRegisterPopup = false;
						}, 1500); // Delay closing slightly to show toast
					} else {
						console.error('Registration failed:', res);
						uni.showToast({ title: res.data?.message || '注册失败', icon: 'none' });
					}
				} catch (err) {
					uni.hideLoading();
					console.error('Registration request failed:', err);
					uni.showToast({ title: '注册失败', icon: 'none' });
				}
			},
		}
	}
</script>

<style>
	.login-bg {
		min-height: 100vh;
		background: #f7f8fa;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.login-box {
		width: 90vw;
		max-width: 600rpx;
		background: #fff;
		border-radius: 24rpx;
		box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.08);
		padding: 60rpx 40rpx 40rpx 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.login-title {
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	}
	.login-tabs {
		display: flex;
		width: 100%;
		margin-bottom: 30rpx;
	}
	.tab {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		padding: 16rpx 0;
		color: #888;
		border-bottom: 4rpx solid transparent;
	}
	.tab.active {
		color: #7ac81e;
		border-bottom: 4rpx solid #7ac81e;
		font-weight: bold;
	}
	.login-form {
		width: 100%;
		margin-bottom: 20rpx;
	}
	.login-input {
		width: 90%;
		height: 80rpx;
		border: 1rpx solid #eee;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		background: #f7f8fa;
	}
	.code-row {
		display: flex;
		align-items: center;
	}
	.code-input {
		flex: 1;
		margin-right: 16rpx;
	}
	.code-btn {
		height: 80rpx;
		background: #7ac81e;
		color: #fff;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
	}
	.login-btn {
		width: 100%;
		height: 80rpx;
		background: #7ac81e;
		color: #fff;
		font-size: 32rpx;
		border-radius: 40rpx;
		margin-bottom: 20rpx;
	}
	.login-btn:disabled {
		background: #b2e59e;
	}
	.login-agree {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #888;
		margin-bottom: 30rpx;
	}
	.login-agree .link {
		color: #7ac81e;
		margin: 0 4rpx;
	}
	.login-divider {
		width: 100%;
		text-align: center;
		color: #bbb;
		font-size: 24rpx;
		margin: 30rpx 0 20rpx 0;
	}
	.wechat-btn, .qq-btn {
		width: 100%;
		height: 70rpx;
		border-radius: 35rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 16rpx;
		border: 1rpx solid #eee;
		background: #f7f8fa;
	}
	.wechat-btn {
		color: #09bb07;
		border: 1rpx solid #09bb07;
	}
	.qq-btn {
		color: #498ff6;
		border: 1rpx solid #498ff6;
	}
	.icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 16rpx;
	}

	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6); /* 半透明背景 */
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999; /* 确保在最上层 */
	}

	.register-popup-content {
		background-color: #fff;
		border-radius: 24rpx;
		width: 85vw; /* 弹窗宽度 */
		max-width: 600rpx;
		padding: 60rpx 40rpx;
		position: relative; /* 用于定位关闭按钮 */
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.register-popup-content .popup-title {
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
		color: #333;
	}

	.register-form {
		width: 100%;
		margin-bottom: 30rpx;
	}

	/* 注册表单的输入框样式，可以复用登录的 login-input */
	.register-form .login-input {
		width: 90%; /* 输入框宽度调整为100% */
		height: 80rpx;
		border: 1rpx solid #eee;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		background: #f7f8fa;
	}

	/* 注册表单的获取验证码行样式，可以复用登录的 code-row */
	.register-form .code-row {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx; /* 增加底部间距 */
	}

	/* 注册表单的验证码输入框样式，可以复用登录的 code-input */
	.register-form .code-input {
		flex: 1;
		margin-right: 16rpx;
		width: auto; /* 验证码输入框宽度自适应 */
	}

	/* 注册表单的获取验证码按钮样式，可以复用登录的 code-btn */
	.register-form .code-btn {
		height: 80rpx;
		background: #7ac81e;
		color: #fff;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
	}

	/* 注册按钮样式，可以复用登录的 login-btn */
	.register-popup-content .login-btn {
		width: 100%;
		height: 80rpx;
		background: #7ac81e;
		color: #fff;
		font-size: 32rpx;
		border-radius: 40rpx;
		margin-bottom: 0; /* 移除底部间距 */
	}

	.close-btn {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 36rpx; /* 调整文本大小 */
		color: #999;
		padding: 10rpx;
		/* 可以加个边框或者背景 */
		/* border: 1rpx solid #999; */
		/* border-radius: 50%; */
		/* background-color: #eee; */
	}
	/* 如果你没有引入uni-ui，可以使用文本X并给样式 */
	/* .close-btn text { font-size: 36rpx; } */

	.form-actions {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: -10rpx;
		margin-bottom: 20rpx;
		padding: 0 10rpx;
	}

	.login-link {
		color: #7ac81e;
		font-size: 26rpx;
	}

	.forgot-password-link {
		color: #7ac81e;
		font-size: 26rpx;
	}
</style>
