<template>
	<view class="login-container">
		<!-- 自定义状态栏 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 关闭按钮 -->
		<view class="close-btn" @click="handleClose">
			<text class="close-icon">×</text>
		</view>
		
		<!-- Logo区域 -->
		<view class="logo-section">
			<view class="welcome-text">欢迎来到酒谷</view>
			<view class="logo-container">
				<view class="logo-icon">
					<text class="logo-text">酒谷</text>
				</view>
			</view>
		</view>
		
		<!-- 一键登录模式 -->
		<view v-if="loginMode === 'oneClick'" class="one-click-section">
			<view class="phone-display">{{ maskedPhoneNumber }}</view>
			<view class="agreement-section">
				<view class="checkbox-wrapper" @click="toggleAgreement">
					<view class="checkbox" :class="{ 'checked': agreeTerms }">
						<text v-if="agreeTerms" class="checkbox-icon">✓</text>
					</view>
					<text class="agreement-text">我已阅读并同意</text>
				</view>
				<text class="agreement-link" @click="showAgreement">《天翼账号认证服务条款》</text>
				<text class="agreement-text">及</text>
				<text class="agreement-link" @click="showPrivacy">《1919服务协议》、《隐私政策》</text>
			</view>
			<button 
				class="login-btn one-click-btn custom-button" 
				:class="{ 'disabled': !agreeTerms }"
				@click="handleOneClickLogin"
				:disabled="!agreeTerms || oneClickLoading"
			>
				<text v-if="oneClickLoading">登录中...</text>
				<text v-else>本机号码一键登录</text>
			</button>
			<view class="switch-mode" @click="switchToCodeLogin">
				其他号码登录/注册
			</view>
		</view>
		
		<!-- 验证码登录模式 -->
		<view v-else class="code-login-section">
			<view class="input-section">
				<!-- 手机号输入 -->
				<view class="input-item" :class="{ 'error': phoneError }">
					<text class="input-icon">📱</text>
					<input 
						v-model="phoneNumber" 
						placeholder="请输入手机号"
						maxlength="11"
						type="number"
						@input="handlePhoneInput"
						@blur="validatePhone"
						class="custom-input"
					/>
				</view>
				<view v-if="phoneError" class="error-text">{{ phoneErrorMsg }}</view>
				
				<!-- 验证码输入 -->
				<view class="input-item" :class="{ 'error': smsError }">
					<text class="input-icon">🔒</text>
					<input 
						v-model="smsCode" 
						placeholder="请输入验证码"
						maxlength="6"
						type="number"
						@input="handleSmsInput"
						class="custom-input sms-input"
					/>
					<button 
						class="sms-btn"
						:class="{
							'disabled': !canGetSms || smsCountdown > 0,
							'countdown': smsCountdown > 0
						}"
						@click="getSmsCode"
						:disabled="!canGetSms || smsCountdown > 0"
					>
						{{ smsButtonText }}
					</button>
				</view>
				<view v-if="smsError" class="error-text">{{ smsErrorMsg }}</view>
			</view>
			
			<!-- Debug信息 -->
			<view v-if="debugMode && debugSmsCode" class="debug-info">
				<text>调试验证码: {{ debugSmsCode }}</text>
			</view>
			
			<!-- 登录提示信息 -->
			<view v-if="!canLogin" class="login-tips">
				<text class="tips-text">
					{{ getLoginTips() }}
				</text>
			</view>
			
			<!-- 登录按钮 -->
			<button 
				class="login-btn custom-login-btn" 
				:class="{ 
					'disabled': !canLogin,
					'loading': smsLoginLoading
				}"
				@click="handleSmsLogin"
				:disabled="!canLogin || smsLoginLoading"
			>
				<text v-if="smsLoginLoading">登录中...</text>
				<text v-else-if="!canLogin">请完善登录信息</text>
				<text v-else>登录</text>
			</button>
			
			<!-- 切换到一键登录 -->
			<view class="switch-mode" @click="switchToOneClick">
				本机号码一键登录
			</view>
		</view>
		
		<!-- 加载遮罩 -->
		<view v-if="pageLoading" class="loading-mask">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{ loadingText }}</text>
			</view>
		</view>
		
		<!-- 消息提示 -->
		<view v-if="toastVisible" class="toast-mask" @click="hideToast">
			<view class="toast-content" :class="'toast-' + toastType">
				<text class="toast-text">{{ toastMessage }}</text>
			</view>
		</view>
	</view>
</template>

<script>
import * as authApi from '@/api/auth.js'

export default {
	name: 'Login',
	data() {
		return {
			statusBarHeight: 0,
			loginMode: 'oneClick', // 'oneClick' | 'smsCode'
			
			// 页面状态
			pageLoading: false,
			loadingText: '加载中...',
			debugMode: true, // 开发阶段显示调试信息
			
			// 一键登录相关
			phoneNumber: '',
			maskedPhoneNumber: '',
			agreeTerms: false,
			oneClickLoading: false,
			
			// 验证码登录相关
			smsCode: '',
			smsCountdown: 0,
			smsTimer: null,
			smsLoginLoading: false,
			debugSmsCode: '', // 调试用验证码
			
			// 验证状态
			phoneValid: false,
			smsValid: false,
			phoneError: false,
			phoneErrorMsg: '',
			smsError: false,
			smsErrorMsg: '',
			
			// Toast相关
			toastVisible: false,
			toastMessage: '',
			toastType: 'default',
			toastTimer: null
		}
	},
	computed: {
		// 验证码按钮文本
		smsButtonText() {
			return this.smsCountdown > 0 ? `${this.smsCountdown}s` : '获取验证码'
		},
		
		// 是否可以获取验证码
		canGetSms() {
			// 检查手机号：必须是11位且以1开头
			const phoneValid = this.phoneNumber.length === 11 && this.phoneNumber.startsWith('1')
			return phoneValid && this.smsCountdown === 0
		},
		
		// 是否可以登录（验证码模式）
		canLogin() {
			// 检查手机号：必须是11位且以1开头
			const phoneValid = this.phoneNumber.length === 11 && this.phoneNumber.startsWith('1')
			// 检查验证码：必须是6位数字
			const smsValid = this.smsCode.length === 6
			
			return phoneValid && smsValid
		}
	},
	onLoad() {
		this.initPage()
	},
	onUnload() {
		this.clearSmsTimer()
		this.hideToast()
	},
	methods: {
		// 初始化页面
		async initPage() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
			
			// 尝试获取本机号码
			await this.getPhoneNumber()
		},
		
		// 获取本机号码
		async getPhoneNumber() {
			try {
				this.pageLoading = true
				this.loadingText = '获取本机号码中...'
				
				const result = await authApi.getPhoneNumber()
				
				this.phoneNumber = result.data.phone
				this.maskedPhoneNumber = result.data.maskedPhone
				
				console.log('获取本机号码成功:', result.data)
				
			} catch (error) {
				console.error('获取本机号码失败:', error)
				// 如果获取失败，直接切换到验证码登录模式
				this.loginMode = 'smsCode'
				this.showToast('无法获取本机号码，请使用验证码登录', 'warning')
			} finally {
				this.pageLoading = false
			}
		},
		
		// 处理手机号输入
		handlePhoneInput(e) {
			let value = e.detail.value || e.target.value
			// 只允许数字输入，限制11位
			const numericValue = value.replace(/\D/g, '').slice(0, 11)
			this.phoneNumber = numericValue
			this.clearPhoneError()
			this.validatePhone(false) // 输入时不显示错误
		},
		
		// 验证手机号
		validatePhone(showError = true) {
			const phoneRegex = /^1[3-9]\d{9}$/
			this.phoneValid = phoneRegex.test(this.phoneNumber)
			
			if (showError && this.phoneNumber.length > 0 && !this.phoneValid) {
				this.phoneError = true
				if (this.phoneNumber.length !== 11) {
					this.phoneErrorMsg = '手机号长度必须为11位'
				} else if (!this.phoneNumber.startsWith('1')) {
					this.phoneErrorMsg = '手机号格式不正确'
				} else {
					this.phoneErrorMsg = '手机号格式不正确'
				}
			} else {
				this.clearPhoneError()
			}
		},
		
		// 清除手机号错误
		clearPhoneError() {
			this.phoneError = false
			this.phoneErrorMsg = ''
		},
		
		// 处理验证码输入
		handleSmsInput(e) {
			let value = e.detail.value || e.target.value
			// 只允许数字输入，限制6位
			const numericValue = value.replace(/\D/g, '').slice(0, 6)
			this.smsCode = numericValue
			this.clearSmsError()
		},
		
		// 清除验证码错误
		clearSmsError() {
			this.smsError = false
			this.smsErrorMsg = ''
		},
		
		// 获取验证码
		async getSmsCode() {
			if (!this.canGetSms) return
			
			try {
				const result = await authApi.sendSmsCode(this.phoneNumber)
				
				this.showToast('验证码发送成功', 'success')
				this.startSmsCountdown()
				
				// 开发阶段显示验证码
				if (this.debugMode && result.data.debugCode) {
					this.debugSmsCode = result.data.debugCode
					console.log('调试验证码:', result.data.debugCode)
				}
				
			} catch (error) {
				console.error('发送验证码失败:', error)
				this.showToast(error.message || '发送验证码失败，请重试', 'error')
			}
		},
		
		// 开始验证码倒计时
		startSmsCountdown() {
			this.smsCountdown = 60
			this.smsTimer = setInterval(() => {
				this.smsCountdown--
				if (this.smsCountdown <= 0) {
					this.clearSmsTimer()
				}
			}, 1000)
		},
		
		// 清除倒计时定时器
		clearSmsTimer() {
			if (this.smsTimer) {
				clearInterval(this.smsTimer)
				this.smsTimer = null
				this.smsCountdown = 0
			}
		},
		
		// 一键登录
		async handleOneClickLogin() {
			if (!this.agreeTerms) {
				this.showToast('请先同意服务条款', 'warning')
				return
			}
			
			this.oneClickLoading = true
			
			try {
				const result = await authApi.oneClickLogin(this.phoneNumber)
				
				this.showToast(result.message, 'success')
				// 保存登录数据
				this.saveLoginData(result.data)
				// 立即跳转
				this.navigateToHomePage()
				
			} catch (error) {
				console.error('一键登录失败:', error)
				this.showToast(error.message || '登录失败，请重试', 'error')
			} finally {
				this.oneClickLoading = false
			}
		},
		
		// 验证码登录
		async handleSmsLogin() {
			if (!this.canLogin) return
			
			// 先验证手机号
			this.validatePhone(true)
			if (this.phoneError) return
			
			this.smsLoginLoading = true
			
			try {
				const result = await authApi.smsLogin(this.phoneNumber, this.smsCode)
				
				this.showToast(result.message, 'success')
				// 保存登录数据
				this.saveLoginData(result.data)
				// 立即跳转
				this.navigateToHomePage()
				
			} catch (error) {
				console.error('验证码登录失败:', error)
				
				if (error.message === '验证码错误') {
					this.smsError = true
					this.smsErrorMsg = '验证码错误'
				}
				
				this.showToast(error.message || '登录失败，请重试', 'error')
			} finally {
				this.smsLoginLoading = false
			}
		},
		
		// 保存登录数据
		saveLoginData(loginData) {
			const { token, user, isNewUser } = loginData
			
			// 保存用户登录状态
			uni.setStorageSync('userToken', token)
			uni.setStorageSync('userInfo', user)
			uni.setStorageSync('loginTime', Date.now())
			
			console.log('登录数据已保存:', { user, isNewUser })
		},
		
		// 跳转到首页
		navigateToHomePage() {
			// 短暂延迟让用户看到成功提示
			setTimeout(() => {
				// 检查是否有返回页面
				const returnUrl = uni.getStorageSync('returnUrl')
				if (returnUrl) {
					uni.removeStorageSync('returnUrl')
					console.log('返回原页面:', returnUrl)
					
					// 检查是否是tabBar页面
					const tabBarPages = [
						'/pages/index/index',
						'/pages/community/index',
						'/pages/legou/index',
						'/pages/cart/index',
						'/pages/user/index'
					]
					
					if (tabBarPages.includes(returnUrl)) {
						uni.switchTab({
							url: returnUrl
						})
					} else {
						uni.reLaunch({
							url: returnUrl
						})
					}
				} else {
					console.log('跳转到首页')
					// 使用switchTab跳转到tabBar页面
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			}, 500) // 进一步减少延迟时间，提升用户体验
		},
		
		// 切换到验证码登录
		switchToCodeLogin() {
			this.loginMode = 'smsCode'
			this.phoneNumber = ''
			this.smsCode = ''
			this.phoneValid = false
			this.smsValid = false
			this.clearPhoneError()
			this.clearSmsError()
			this.debugSmsCode = ''
		},
		
		// 切换到一键登录
		switchToOneClick() {
			this.loginMode = 'oneClick'
			this.getPhoneNumber()
		},
		
		// 切换协议同意状态
		toggleAgreement() {
			this.agreeTerms = !this.agreeTerms
		},
		
		// 显示协议
		showAgreement() {
			uni.showModal({
				title: '天翼账号认证服务条款',
				content: '这里是天翼账号认证服务条款的详细内容...',
				showCancel: false
			})
		},
		
		// 显示隐私政策
		showPrivacy() {
			uni.showModal({
				title: '服务协议和隐私政策',
				content: '这里是1919服务协议和隐私政策的详细内容...',
				showCancel: false
			})
		},
		
		// 关闭页面
		handleClose() {
			uni.navigateBack({
				fail() {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			})
		},
		
		// 显示提示
		showToast(message, type = 'default') {
			this.toastMessage = message
			this.toastType = type
			this.toastVisible = true
			
			// 清除之前的定时器
			if (this.toastTimer) {
				clearTimeout(this.toastTimer)
			}
			
			// 2秒后自动隐藏
			this.toastTimer = setTimeout(() => {
				this.hideToast()
			}, 2000)
		},
		
		// 隐藏Toast
		hideToast() {
			this.toastVisible = false
			if (this.toastTimer) {
				clearTimeout(this.toastTimer)
				this.toastTimer = null
			}
		},
		
		// 获取登录提示信息
		getLoginTips() {
			const phoneLength = this.phoneNumber.length
			const smsLength = this.smsCode.length
			
			if (phoneLength === 0) {
				return '请输入手机号'
			}
			
			if (phoneLength < 11) {
				return '手机号必须为11位数字'
			}
			
			if (phoneLength === 11 && !this.phoneNumber.startsWith('1')) {
				return '手机号首位必须为1'
			}
			
			if (smsLength === 0) {
				return '请输入验证码'
			}
			
			if (smsLength < 6) {
				return '验证码必须为6位数字'
			}
			
			return '登录信息完整'
		}
	}
}
</script>

<style lang="scss" scoped>
.login-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	position: relative;
	overflow: hidden;
}

.status-bar {
	background: transparent;
}

.close-btn {
	position: absolute;
	top: 60rpx;
	left: 30rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
	background: rgba(255, 255, 255, 0.8);
	border-radius: 30rpx;
	backdrop-filter: blur(10px);
	
	.close-icon {
		font-size: 36rpx;
		color: #999;
		font-weight: bold;
	}
}

.logo-section {
	padding: 100rpx 60rpx 80rpx;
	text-align: center;
	
	.welcome-text {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 40rpx;
		font-weight: 500;
	}
	
	.logo-container {
		.logo-icon {
			width: 120rpx;
			height: 120rpx;
			background: #C32222;
			border-radius: 24rpx;
			margin: 0 auto;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 8rpx 32rpx rgba(195, 34, 34, 0.3);
			
			.logo-text {
				color: white;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}
}

.one-click-section {
	padding: 0 60rpx;
	
	.phone-display {
		text-align: center;
		font-size: 36rpx;
		color: #333;
		font-weight: 600;
		letter-spacing: 2rpx;
		margin-bottom: 60rpx;
	}
	
	.agreement-section {
		margin-bottom: 60rpx;
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		
		.checkbox-wrapper {
			display: flex;
			align-items: center;
			margin-right: 10rpx;
			
			.checkbox {
				width: 32rpx;
				height: 32rpx;
				border: 2rpx solid #ddd;
				border-radius: 6rpx;
				margin-right: 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;
				
				&.checked {
					background: #667eea;
					border-color: #667eea;
				}
				
				.checkbox-icon {
					color: white;
					font-size: 20rpx;
					font-weight: bold;
				}
			}
		}
		
		.agreement-text {
			color: #666;
		}
		
		.agreement-link {
			color: #667eea;
			text-decoration: underline;
			margin: 0 8rpx;
		}
	}
	
	.one-click-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border: none;
		border-radius: 50rpx;
		height: 88rpx;
		font-size: 32rpx;
		margin-bottom: 40rpx;
		width: 100%;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		
		&.disabled {
			background: #ccc;
			color: #999;
		}
		
		&:not(.disabled):active {
			background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
			transform: scale(0.98);
		}
	}
	
	.switch-mode {
		text-align: center;
		color: #666;
		font-size: 28rpx;
		padding: 20rpx;
		text-decoration: underline;
	}
}

.code-login-section {
	padding: 0 60rpx;
	
	.input-section {
		margin-bottom: 40rpx;
		
		.input-item {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.9);
			border-radius: 50rpx;
			padding: 0 30rpx;
			margin-bottom: 10rpx;
			height: 88rpx;
			backdrop-filter: blur(10px);
			border: 2px solid transparent;
			transition: all 0.3s ease;
			
			&.error {
				border-color: #ff4757;
				background: rgba(255, 71, 87, 0.1);
			}
			
			.input-icon {
				font-size: 32rpx;
				margin-right: 20rpx;
			}
			
			.custom-input {
				flex: 1;
				border: none;
				outline: none;
				background: transparent;
				font-size: 28rpx;
				color: #333;
				
				&::placeholder {
					color: #999;
				}
			}
			
			.sms-input {
				margin-right: 20rpx;
			}
			
			.sms-btn {
				min-width: 160rpx;
				height: 60rpx;
				border-radius: 30rpx;
				background: #667eea;
				color: white;
				border: none;
				font-size: 24rpx;
				transition: all 0.3s ease;
				
				&.disabled {
					background: #ccc;
					color: #999;
				}
				
				&.countdown {
					background: #999;
				}
			}
		}
		
		.error-text {
			color: #ff4757;
			font-size: 24rpx;
			margin: 0 30rpx 20rpx;
			line-height: 1.4;
		}
	}
	
	.debug-info {
		background: rgba(255, 193, 7, 0.1);
		border: 1px solid #ffc107;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		text-align: center;
		
		text {
			color: #856404;
			font-size: 24rpx;
			font-weight: bold;
		}
	}
	
	.login-tips {
		margin-bottom: 20rpx;
		text-align: center;
		
		.tips-text {
			color: #666;
			font-size: 24rpx;
			line-height: 1.4;
		}
	}
	
	.custom-login-btn {
		background: #C32222;
		border: none;
		border-radius: 50rpx;
		height: 88rpx;
		font-size: 32rpx;
		margin-bottom: 40rpx;
		width: 100%;
		color: white;
		transition: all 0.3s ease;
		position: relative;
		
		&.disabled {
			background: #cccccc;
			color: #999999;
			cursor: not-allowed;
		}
		
		&.loading {
			background: #999999;
			cursor: not-allowed;
		}
		
		&:not(.disabled):not(.loading):active {
			background: #a01818;
			transform: scale(0.98);
		}
		
		/* 禁用状态下的文字提示 */
		&.disabled text {
			font-size: 28rpx;
		}
	}
	
	.switch-mode {
		text-align: center;
		color: #666;
		font-size: 28rpx;
		padding: 20rpx;
		text-decoration: underline;
	}
}

/* 动画效果 */
.login-container {
	animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

/* 输入框焦点效果 */
.input-item:focus-within {
	border-color: #667eea;
	background: rgba(102, 126, 234, 0.1);
}

/* 加载遮罩 */
.loading-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	
	.loading-content {
		background: white;
		padding: 60rpx 40rpx;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.loading-spinner {
			width: 60rpx;
			height: 60rpx;
			border: 4rpx solid #f3f3f3;
			border-top: 4rpx solid #667eea;
			border-radius: 50%;
			animation: spin 1s linear infinite;
			margin-bottom: 20rpx;
		}
		
		.loading-text {
			color: #333;
			font-size: 28rpx;
		}
	}
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* Toast样式 */
.toast-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 10000;
	display: flex;
	align-items: center;
	justify-content: center;
	pointer-events: none;
	
	.toast-content {
		background: rgba(0, 0, 0, 0.8);
		color: white;
		padding: 20rpx 40rpx;
		border-radius: 10rpx;
		max-width: 70%;
		text-align: center;
		animation: toastIn 0.3s ease-out;
		pointer-events: auto;
		
		&.toast-success {
			background: rgba(67, 160, 71, 0.9);
		}
		
		&.toast-error {
			background: rgba(244, 67, 54, 0.9);
		}
		
		&.toast-warning {
			background: rgba(255, 152, 0, 0.9);
		}
		
		&.toast-info {
			background: rgba(33, 150, 243, 0.9);
		}
		
		.toast-text {
			color: white;
			font-size: 28rpx;
			line-height: 1.4;
		}
	}
}

@keyframes toastIn {
	from {
		opacity: 0;
		transform: scale(0.8);
	}
	to {
		opacity: 1;
		transform: scale(1);
	}
}
</style>
