<template>
	<view class="page">
		<view class="logo">
			<image src="../../../static/logo.png"></image>
		</view>

		<view class="input">
			<input v-model="register_email" placeholder="请输入邮箱地址" @input="onInputEmail" @blur="validateEmail" />
			<view v-if="showSuggestions" class="suggestions">
				<text v-for="suffix in suggestedSuffixes" :key="suffix"
					@click="appendSuffix(suffix)">{{ register_email + suffix }}</text>
			</view>
		</view>

		<view class="input">
			<input v-model="register_username" placeholder="请输入用户名" @blur="validateUsername" />
		</view>

		<view class="input">
			<input v-model="register_password" type="password" placeholder="请输入密码" @blur="checkPassword" />
		</view>
		<view class="input">
			<input v-model="register_password_sub" type="password" placeholder="请再次输入密码" @blur="validatePassword" />
		</view>

		<view class="underlinecontainer">
			<view class="buttonleft">
				<button @click="return2login()">返回登录</button>
			</view>
			<view class="buttonright">
				<button @click="register()">立即注册</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				register_username: '',
				register_email: '',
				register_password: '',
				register_password_sub: '',
				passwordError: true,
				showSuggestions: false,
				emailValid: false,
				passwordValid: false,
				usernameValid: false,
				suggestedSuffixes: ['@qq.com']
			}
		},
		methods: {
			return2login() {
				uni.reLaunch({
					url: "./login"
				});
			},
			validatePassword() {
				// 验证两次输入的密码是否一致
				if (this.register_password !== this.register_password_sub) {
					this.passwordError = true;
					// 显示错误提示，这里可以是弹窗或者气泡提示
					uni.showToast({
						title: '两次输入的密码不一致！',
						icon: 'none'
					})
				} else {
					this.passwordError = false;
				}
			},
			validateUsername() {
				this.usernameValid = this.register_username;
			},
			checkPassword() {
				this.passwordValid = this.register_password;
			},
			validateEmail() {
				// 邮箱格式校验正则表达式
				const emailPattern = /^[a-zA-Z0-9._%+-]/;
				this.emailValid = emailPattern.test(this.register_email);
				if (!this.emailValid) {
					uni.showToast({
						title: '邮箱格式不正确',
						icon: 'none'
					});
				}
			},
			onInputEmail(e) {
				// 确保 e 不为 undefined 并且 e.target 不为 undefined
				if (e && e.target) {
					// 当输入框内容改变时，检查是否需要显示建议
					// this.showSuggestions = e.detail.value.includes('@') && !e.detail.value.includes('.');
					if (e.detail.value) {
						this.showSuggestions = true;
					} else {
						this.showSuggestions = false;
					}
				}
			},
			appendSuffix(suffix) {
				// 当用户点击建议的后缀时，将其添加到输入框中
				this.register_email += suffix;
				this.showSuggestions = false;
			},
			async register() {
				// 确保在注册前密码已经验证过
				if (!this.emailValid) {
					uni.showToast({
						title: '请先输入邮箱',
						icon: 'none'
					});
					return;
				}

				if (!this.usernameValid) {
					uni.showToast({
						title: '请先输入用户名',
						icon: 'none'
					});
					return;
				}

				if (!this.passwordValid) {
					uni.showToast({
						title: '请先输入密码',
						icon: 'none'
					});
					return;
				}

				if (this.passwordError) {
					this.passwordError = (this.register_password !== this.register_password_sub);
					if (this.passwordError) {
						uni.showToast({
							title: '两次输入的密码不一致',
							icon: 'none'
						});
						return;
					}
				}

				if (!this.passwordError && this.emailValid && this.usernameValid && this.passwordValid) {
					// 注册操作
					const registerData = {
						username: this.register_username,
						password: this.register_password,
						email: this.register_email
					};

					// 显示加载提示
					uni.showLoading({
						title: '注册中...',
						mask: true // 可选，显示加载遮罩
					});

					try {
						// 调用注册接口
						const res = await uni.request({
							url: 'https://afanai.top:8089/v1/user/register',
							method: 'POST',
							data: registerData,
							header: {
								'content-type': 'application/json'
							}
						});

						// 关闭加载提示
						uni.hideLoading();

						// 成功响应处理
						if (res.statusCode === 201) {
							// 如果状态码为200，通常表示请求成功
							uni.showToast({
								title: '注册成功',
								duration: 2000,
								icon: 'success'
							});
						} else {
							try {
							    // 确保 res.data 是一个对象且包含 error 键
							    if (res.data && typeof res.data === 'object' && 'error' in res.data) {
							        uni.showToast({
							            title: res.data.error,
							            duration: 2000,
							            icon: 'none'
							        });
							    }
							} catch (e) {
							    // 如果尝试处理 res.data 时出错，显示默认错误信息
							    uni.showToast({
							        title: '处理服务器响应时出错',
							        duration: 2000,
							        icon: 'none'
							    });
							    console.error('Error processing response data:', e);
							}
						}
					} catch (error) {
						// 关闭加载提示
						uni.hideLoading();
						// 错误处理
						uni.showToast({
							title: '网络错误，请检查网络',
							duration: 2000,
							icon: 'none'
						});
						console.error('注册请求出错：', error);
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-height: 100vh;
		background: #f5f5f5;

		.logo {
			padding-top: 8vh;
			margin-bottom: 30rpx;

			image {
				width: 280rpx;
				height: 280rpx;
			}
		}

		.input {
			width: 660rpx;
			margin-bottom: 30rpx;
			position: relative;

			input {
				box-sizing: border-box;
				width: 660rpx;
				height: 80rpx;
				border-radius: 20rpx;
				padding: 0 40rpx;
				background: #fff;
				font-size: 14px;
			}

			.send_button {
				position: absolute;
				right: 0;
				top: 0;
				height: 80rpx;
				width: 220rpx;
				text-align: center;
				line-height: 80rpx;
				font-size: 12px;
				color: #777;
				z-index: 99;
			}

			.suggestions {
				position: absolute;
				top: 110%; // 修改这里，从bottom改为top
				left: 0;
				right: 0;
				background: #fff;
				border: 1px solid #e1e1e1;
				border-radius: 20rpx;
				z-index: 10;
			}

			.suggestions text {
				display: block;
				padding: 10px;
				cursor: pointer;
			}
		}

		.underlinecontainer {
			display: flex;
			/* 使用flex布局 */
			justify-content: space-between;
			/* 使子元素一个靠左，一个靠右 */
			gap: 60rpx;
			/* 在所有子元素之间添加间距 */

			.buttonleft {
				margin-bottom: 30rpx;

				button {
					width: 200rpx;
					height: 80rpx;
					line-height: 80rpx;
					border-radius: 20rpx;
					background: #0068B7;
					color: #fff;
					font-size: 14px;

					&:active {
						background: #005694;
					}
				}
			}

			.buttonright {
				margin-bottom: 30rpx;

				button {
					width: 400rpx;
					height: 80rpx;
					line-height: 80rpx;
					border-radius: 20rpx;
					background: #f0ad4e;
					color: #fff;
					font-size: 14px;

					&:active {
						background: #f09b2b;
					}
				}
			}
		}
	}
</style>
