<template>
	<view class="page">
		<view class="logo">
			<image src="../../../static/logo.png"></image>
		</view>
		<template v-if="type === 0">
			<view class="input">
				<input v-model="form_username" placeholder="请输入用户名" />
			</view>
			<view class="input">
				<input v-model="form_password" type="password" placeholder="请输入密码" />
			</view>
		</template>

		<template v-if="type === 1">
			<view class="input">
				<input v-model="form_tel" type="tel" maxlength="11" placeholder="请输入手机号" />
			</view>
			<view class="input">
				<input v-model="form_code" placeholder="请输入验证码" />
				<view class="send_button" @click="sendCode()">
					<text v-if="!send_count_down">发送验证码</text>
					<text v-else>重新发送 {{send_count_down}} S</text>
				</view>
			</view>
		</template>


		<view class="underlinecontainer">
			<view class="typeleft" @click="changeType()">
				<text v-if="type === 0">短信验证码登录</text>
				<text v-else>用户名密码登录</text>
			</view>
			<view class="typeright" @click="registerUserInfo()">
				<text class="a">没有用户名？点击注册</text>
			</view>
		</view>

		<view class="button">
			<button @click="login()">登录</button>
		</view>
		<view class="tip">
			<checkbox-group @change="privacyChange">
				<checkbox value="privacy" color="#0068B7" style="transform:scale(0.7)" />
			</checkbox-group>

			<text>
				我已阅读并同意<text class="a">《隐私政策》</text>和<text class="a">《服务协议》</text>
			</text>
		</view>
	</view>
</template>

<script>
	import { storeJwtInfo2User } from '@/utils/storage.js';
	// 引入解析JWT的库
	export default {
		data() {
			return {
				type: 0, // 0 用户密码 ， 1验证码登录
				form_username: '',
				form_password: '',
				form_tel: '',
				form_code: '',
				send_count_down: 0, // 验证码重新发送等待倒计时
				checked: false
			}
		},
		onLoad() {

		},
		methods: {
			changeType() {
				this.type = this.type ? 0 : 1
			},
			sendCode() {
				if (this.send_count_down === 0) {
					// 验证手机号规则 调用发送验证码接口
					let countDown = 60
					this.send_count_down = countDown
					let timer = setInterval(() => {
						countDown--
						this.send_count_down = countDown
						if (countDown === 0) {
							clearInterval(timer)
						}
					}, 1000)
				}
			},
			async login() {
				if (!this.checked) {
					return uni.showToast({
						icon: 'none',
						title: '请先同意隐私政策和服务协议'
					});
				}

				let loginUrl = this.type === 0 ?
					'https://afanai.top:8089/v1/user/pwdlogin' :
					'https://afanai.top:8089/v1/user/codeLogin';

				let loginData = {};
				if (this.type === 0) {
					// 用户密码登录
					loginData = {
						username: this.form_username,
						password: this.form_password
					};
				} else {
					// 验证码登录
					loginData = {
						tel: this.form_tel,
						code: this.form_code
					};
				}

				uni.showLoading({
					title: '登录中...'
				});

				try {
					// 调用登录接口
					const res = await uni.request({
						url: loginUrl,
						method: 'POST',
						data: loginData,
						header: {
							'content-type': 'application/json'
						}
					});

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

					// 成功响应处理
					if (res.statusCode === 200) {
						const jwt = res.data.token; // 后端返回的JWT字段名为token
						// // 存储JWT，例如存入本地存储
						// console.log(jwt);
						uni.setStorageSync('jwt', jwt);
						storeJwtInfo2User(jwt);

						// 存储JWT到Vuex
						// this.$store.commit('setToken', {
						// 	token: jwt,
						// 	expiry: new Date().getTime() + 3600 * 1000
						// }); // 假设token有效期为1小时，具体时间根据业务调整
						// 或者使用dispatch
						// this.$store.dispatch('setToken', jwt);

						uni.showToast({
							title: "登录成功",
							icon: 'succeed'
						});

						// 跳转到主页面
						uni.reLaunch({
							url: '../tabbar-1/tabbar-1'
						});
					} 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);
				}
			},
			registerUserInfo() {
				uni.navigateTo({
					url: "./register"
				});
			},
			privacyChange(e) {
				this.checked = e.detail.value.length ? true : false
			}

		}
	}
</script>

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

		.logo {
			padding-top: 12vh;
			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: 40rpx;
				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;
			}
		}

		.underlinecontainer {
			display: flex;
			/* 使用flex布局 */
			justify-content: space-between;
			/* 使子元素一个靠左，一个靠右 */

			.typeleft {
				width: 330rpx;
				font-size: 12px;
				color: #777;
				margin-bottom: 30rpx;
				text-align: left;

				&:active {
					color: #333;
				}
			}

			.typeright {
				width: 330rpx;
				font-size: 12px;
				color: #777;
				margin-bottom: 30rpx;
				text-align: right;

				&:active {
					color: #333;
				}
			}
		}

		.button {
			margin-bottom: 30rpx;

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

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

		.tip {
			width: 660rpx;
			height: 40rpx;
			font-size: 12px;
			color: #777;
			display: flex;
			align-items: center;

			.a {
				color: #0068B7;
			}
		}

	}
</style>
