<template>
	<view class="login-container">
		<view class="header-row">
			<view class="back-button" @click="back">
				<image src="/static/ic_back.png" class="back-icon"></image>
			</view>
			<text class="title">{{ $t('login.title') }}</text>
			<view class="back-button" @click="markAllRead">
			</view>
		</view>

		<!-- Logo Section -->
		<view class="logo-section">
			<view class="logo-box">
				<image v-if="appLogo" :src="appLogo" class="logo-image" mode="aspectFit"></image>
				<text v-else class="logo-text">LOGO</text>
			</view>
		</view>

		<!-- Main Content -->
		<view class="main-content">
			<!-- One-Click Login Button -->
			<button class="login-button" @click="handleWechatLogin" :loading="isLoading">
				{{ $t('login.oneClickLogin') }}
			</button>

			<!-- Agreement Checkbox -->
			<view class="agreement-section">
				<view class="agreement-label" @click="toggleAgreement">
					<image :src="agreeToTerms ? '/static/ic_checked.png' : '/static/ic_check.png'" class="check-icon"></image>
					<text class="agreement-text">
						{{ $t('login.agreeToTerms') }}
						<text class="link-text" @click.stop="goToUserAgreement">{{ $t('login.userAgreement') }}</text>
						{{ $t('login.and') }}
						<text class="link-text" @click.stop="goToPrivacyPolicy">{{ $t('login.privacyPolicy') }}</text>
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		AppServer
	} from '../../modules/api/AppServer';
	import {
		saveAuthData
	} from '@/utils/auth.js';
	import Config from '@/modules/Config.js';

	export default {
		data() {
			return {
				isLoading: false,
				agreeToTerms: false,
				statusBarHeight: 0,
				appLogo: ''
			}
		},
		onLoad() {
			// Get status bar height
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			// 加载配置
			this.loadConfig()
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			// Handle WeChat login
			async handleWechatLogin() {
				// 防止重复点击
				if (this.isLoading) {
					return;
				}

				// 检查是否勾选协议
				if (!this.agreeToTerms) {
					uni.showToast({
						title: this.$t('login.mustAgreeToTerms'),
						icon: 'none'
					})
					return
				}

				this.isLoading = true

				try {
					// 获取微信登录code
					const loginRes = await this.getWechatLoginCode();

					console.log('微信登录 code:', loginRes);

					if (!loginRes || !loginRes.code) {
						uni.showToast({
							title: this.$t('login.wechatLoginFailed'),
							icon: 'none'
						})
						this.isLoading = false
						return
					}

					// 获取邀请码（从全局数据或本地存储）
					let invitationCode = ''
					const app = getApp()
					if (app && app.globalData && app.globalData.inviteCode) {
						invitationCode = app.globalData.inviteCode
					} else {
						invitationCode = uni.getStorageSync('inviteCode') || ''
					}
					
					if (invitationCode) {
						console.log('使用邀请码登录:', invitationCode)
					}
					
					// 调用后端登录接口（带邀请码）
					const appserver = new AppServer();
					const data = await appserver.WechatLogin(loginRes.code, invitationCode);

					console.log('登录接口返回:', data);

					// 检查API响应
					if (!data) {
						console.error('登录接口无响应');
						uni.showToast({
							title: this.$t('login.loginFailed'),
							icon: 'none'
						})
						this.isLoading = false
						return
					}

					// 检查返回码（0表示成功）
					if (data.code !== 0) {
						console.error('登录失败，code:', data.code, 'message:', data.message);
						uni.showToast({
							title: data.message || this.$t('login.loginFailed'),
							icon: 'none'
						})
						this.isLoading = false
						return
					}

					// 检查token数据
					if (!data.data || !data.data.token) {
						console.error('Token 数据缺失:', data.data);
						uni.showToast({
							title: this.$t('login.loginFailed'),
							icon: 'none'
						})
						this.isLoading = false
						return
					}

					console.log('登录成功，保存认证信息');

					// 保存认证信息
					const token = "Bearer " + data.data.token
					saveAuthData(token, data.data.refreshToken, data.data.user)
					
					// 清除邀请码（已使用）
					if (invitationCode) {
						const app = getApp()
						if (app && app.globalData) {
							app.globalData.inviteCode = ''
						}
						uni.removeStorageSync('inviteCode')
						console.log('邀请码已清除')
					}

					// 登录成功
					uni.showToast({
						title: this.$t('login.loginSuccess') || '登录成功',
						icon: 'success',
						duration: 1500
					});

					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						this.redirectToHome();
					}, 500);

				} catch (error) {
					console.error('登录异常:', error);
					console.error('错误堆栈:', error.stack);
					uni.showToast({
						title: this.$t('login.loginError') + ': ' + (error.message || ''),
						icon: 'none',
						duration: 3000
					})
				} finally {
					this.isLoading = false
				}
			},

			// 获取微信登录code（Promise封装）
			getWechatLoginCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: (res) => {
							resolve(res);
						},
						fail: (err) => {
							console.error('uni.login 失败:', err);
							reject(err);
						}
					});
				});
			},

			// 登录成功后跳转到首页
			redirectToHome() {
				// 设置全局标志，标记登录成功
				const app = getApp();
				if (app.globalData) {
					app.globalData.shouldRefresh = true;
					app.globalData.loginTime = Date.now();
				}

				// 跳转到首页（tabBar页面）
				uni.switchTab({
					url: '/pages/index/index',
					success: () => {
						console.log('登录成功，已跳转到首页');
					},
					fail: (err) => {
						console.error('跳转首页失败:', err);
						// 如果 switchTab 失败，尝试使用 reLaunch
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				});
			},

			// Toggle agreement checkbox
			toggleAgreement() {
				this.agreeToTerms = !this.agreeToTerms
			},

			// Go to user agreement page
			goToUserAgreement() {
				uni.navigateTo({
					url: '/pages/me/user-agreement-page'
				})
			},

			// Go to privacy policy page
			goToPrivacyPolicy() {
				uni.navigateTo({
					url: '/pages/me/privacy-policy-page'
				})
			},

			// 加载配置
			async loadConfig() {
				try {
					const config = await Config.getPublicConfig()
					if (config.app_logo) {
						this.appLogo = Config.getImageUrl(config.app_logo)
					}
				} catch (error) {
					console.error('加载配置失败:', error)
				}
			},


		},
	}
</script>

<style lang="scss" scoped>
	.login-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.header-row {
		width: 100%;
		margin-top: 100rpx;
		padding-bottom: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}

	.back-button {
		width: 80rpx;
		height: 50rpx;
		margin-left: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		width: 48rpx;
		height: 48rpx;
	}

	// Logo Section
	.logo-section {
		display: flex;
		justify-content: center;
		padding: 30px 20px 20px;
		flex: 0 0 auto;

		.logo-box {
			width: 140px;
			height: 140px;
			border: 2px solid #17a2b8;
			border-radius: 16px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #fff;
			box-shadow: 0 2px 8px rgba(23, 162, 184, 0.1);
			overflow: hidden;

			.logo-image {
				width: 100%;
				height: 100%;
			}

			.logo-text {
				font-size: 36px;
				color: #17a2b8;
				font-weight: 600;
			}
		}
	}

	// Main Content
	.main-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		padding: 0 20px 40px;
	}

	// Login Button
	.login-button {
		width: 100%;
		height: 50px;
		background-color: #17a2b8;
		color: #fff;
		border-radius: 10px;
		font-size: 16px;
		font-weight: 600;
		border: none;
		margin-bottom: 20px;
		box-shadow: 0 3px 10px rgba(23, 162, 184, 0.2);
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		line-height: 50px;
		padding: 0;
		text-align: center;

		&:active {
			background-color: #138496;
			box-shadow: 0 2px 6px rgba(23, 162, 184, 0.15);
		}

		&::after {
			border: none;
		}
	}

	// Agreement Section
	.agreement-section {
		display: flex;
		align-items: center;
		justify-content: center;

		.agreement-label {
			display: flex;
			align-items: center;
			font-size: 13px;
			color: #666;
			line-height: 1.8;

			.check-icon {
				width: 36rpx;
				height: 36rpx;
				margin-right: 12rpx;
				flex-shrink: 0;
			}

			.agreement-text {
				padding-top: 1px;
			}

			.link-text {
				color: #17a2b8;
				text-decoration: underline;
				font-weight: 500;
			}
		}
	}
</style>