<template>
	<view class="login-page">
		<!-- 返回按钮 -->
		<view class="nav-back" @click="navigateBack">
			<text class="back-icon">‹</text>
		</view>
		
		<!-- 页面标题 -->
		<view class="nav-title">登录</view>
		
		<!-- 占位区域，背景图已包含Logo和欢迎语 -->
		<view class="logo-section"></view>
		
		<!-- 底部登录区域 -->
		<view class="login-bottom">
			<!-- 小程序手机号快速验证登录按钮 -->
			<button v-if="isMpWeixin" class="login-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
				一键注册/登录
			</button>
			
			<!-- H5手机号登录按钮 -->
			<button v-else class="login-btn" @click="showPhoneLogin = true">
				一键注册/登录
			</button>
			
			<!-- 协议勾选 -->
			<view class="agree-section" @click="isAgree = !isAgree">
				<view class="check-icon">
					<image v-if="isAgree" :src="$img1('common/check_act.png')"></image>
					<image v-else :src="$img1('common/check.png')"></image>
				</view>
				<view class="agree-text">
					注册即同意<text class="link" @click.stop="goAgreement(4)">《用户协议》</text>和<text class="link" @click.stop="goAgreement(5)">《隐私政策》</text>
				</view>
			</view>
		</view>
		
		<!-- H5手机号登录弹窗 -->
		<uni-popup ref="phonePopup" type="bottom" v-if="!isMpWeixin">
			<view class="phone-login-popup">
				<view class="popup-header">
					<text class="popup-title">手机号登录</text>
					<view class="popup-close" @click="$refs.phonePopup.close()">×</view>
				</view>
				
				<view class="phone-form">
					<view class="input-row">
						<input type="number" v-model="mobile" placeholder="请输入手机号" maxlength="11" />
					</view>
					
					<view class="input-row code-row">
						<input type="number" v-model="verifyCode" placeholder="请输入验证码" maxlength="6" />
						<view class="send-btn" :class="{ disabled: countdown > 0 }" @click="sendVerifyCode">
							{{ countdown > 0 ? countdown + 's' : '获取验证码' }}
						</view>
					</view>
					
					<button class="submit-btn" @click="phoneLogin">登录</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { wxLogin, wxPhoneLogin, mobileLogin, sendSms, saveLoginTokens } from '@/common/server/auth.js';
	import { getUser } from '@/common/server/user.js';
	
	export default {
		data() {
			return {
				isAgree: false,
				isMpWeixin: false,
				showPhoneLogin: false,
				mobile: '',
				verifyCode: '',
				countdown: 0,
				timer: null,
				codeSent: false
			}
		},
		onLoad() {
			// #ifdef MP
			this.isMpWeixin = true;
			// #endif
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		watch: {
			showPhoneLogin(val) {
				if (val && this.$refs.phonePopup) {
					this.$refs.phonePopup.open();
				}
			}
		},
		methods: {
			navigateBack() {
				uni.navigateBack({
					delta: 1,
					fail: () => {
						this.$customRouter.navigateTo('/pages/shouye/index', {}, 'switchTab');
					}
				});
			},
			
			goAgreement(type) {
				// #ifdef MP
				this.$customRouter.navigateTo('/pages/guize/guize', { type });
				// #endif
				// #ifndef MP
				if (type === 4) {
					this.$platform.getUserAgreement();
				} else {
					this.$platform.getPrivacyAgreement();
				}
				// #endif
			},
			
			getUserProfile() {
				if (!this.isAgree) {
					return uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' });
				}
				// #ifdef MP
				this.wxUserProfile();
				// #endif
			},
			
			// 微信手机号快速验证登录
			async onGetPhoneNumber(e) {
				if (!this.isAgree) {
					return uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' });
				}
				
				if (!e.detail.code) {
					return uni.showToast({ title: '授权失败，请重试', icon: 'none' });
				}
				
				try {
					const res = await wxPhoneLogin(e.detail.code, uni.getStorageSync('pid'));
					if (res.status == 1) {
						saveLoginTokens(res.data);
						this.$c.msg("登录成功");
						this.handleLoginSuccess();
					} else {
						this.$c.msg("登录失败: " + res.msg);
					}
				} catch (error) {
					this.$c.msg("登录失败，请重试");
					console.error('微信手机号登录失败:', error);
				}
			},
			
			async sendVerifyCode() {
				if (this.countdown > 0) return;
				
				if (!this.mobile || !/^1\d{10}$/.test(this.mobile)) {
					return uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
				}
				
				try {
					const res = await sendSms(this.mobile);
					if (res.status == 1) {
						uni.showToast({ title: '验证码已发送', icon: 'none' });
						this.codeSent = true;
						this.countdown = res.data || 60;
						this.timer = setInterval(() => {
							this.countdown--;
							if (this.countdown <= 0) {
								clearInterval(this.timer);
								this.timer = null;
							}
						}, 1000);
					} else {
						uni.showToast({ title: res.msg || '发送失败', icon: 'none' });
					}
				} catch (error) {
					uni.showToast({ title: '发送失败，请稍后重试', icon: 'none' });
				}
			},
			
			async phoneLogin() {
				if (!this.isAgree) {
					return uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' });
				}
				if (!this.mobile || !/^1\d{10}$/.test(this.mobile)) {
					return uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
				}
				if (!this.verifyCode) {
					return uni.showToast({ title: '请输入验证码', icon: 'none' });
				}
				
				try {
					const res = await mobileLogin(this.mobile, this.verifyCode, uni.getStorageSync('pid'));
					if (res.status == 1) {
						saveLoginTokens(res.data);
						this.$c.msg("登录成功");
						this.handleLoginSuccess();
					} else {
						this.$c.msg("登录失败: " + res.msg);
					}
				} catch (error) {
					console.error('登录失败:', error);
				}
			},
			
			async wxUserProfile() {
				try {
					await new Promise((resolve, reject) => {
						uni.getUserProfile({
							desc: '用于完善用户资料',
							lang: 'zh_CN',
							success: resolve,
							fail: reject
						});
					});
					
					const loginRes = await new Promise((resolve, reject) => {
						uni.login({
							provider: 'weixin',
							success: resolve,
							fail: reject
						});
					});
					
					const res = await wxLogin({
						code: loginRes.code,
						nickname: '',
						headimg: '',
						pid: uni.getStorageSync('pid')
					});
					
					if (res.status == 1) {
						saveLoginTokens(res.data);
						this.$c.msg("登录成功");
						this.handleLoginSuccess();
					} else {
						this.$c.msg("登录失败: " + res.msg);
					}
				} catch (error) {
					this.$c.msg("登录失败，请重试");
					console.error('微信登录失败:', error);
				}
			},
			
			async handleLoginSuccess() {
				const redirectUrl = uni.getStorageSync('redirect');
				if (redirectUrl) {
					uni.removeStorageSync('redirect');
					setTimeout(() => {
						this.$customRouter.navigateTo(redirectUrl).catch(() => {
							this.$customRouter.navigateTo('/pages/user/index');
						});
					}, 1000);
				} else {
					setTimeout(() => this.checkUserMobile(), 1000);
				}
			},
			
			async checkUserMobile() {
				try {
					const res = await getUser();
					if (res.status == 1 && res.data.userinfo?.mobile_is == 0) {
						this.$customRouter.navigateTo('/pages/user/bangding');
					} else {
						this.$customRouter.navigateTo('/pages/user/index');
					}
				} catch (error) {
					console.error('获取用户数据失败:', error);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-page {
		min-height: 100vh;
		background: url($imgurl+'common/bj.png') no-repeat center top / 100% auto;
		background-color: #FFFFFF;
		position: relative;
		display: flex;
		flex-direction: column;
	}
	
	.nav-back {
		position: absolute;
		top: 88rpx;
		left: 32rpx;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.back-icon {
			font-size: 40rpx;
			color: #333;
		}
	}
	
	.nav-title {
		position: absolute;
		top: 88rpx;
		left: 50%;
		transform: translateX(-50%);
		font-size: 34rpx;
		color: #333;
		font-weight: 500;
	}
	
	.logo-section {
		flex: 1;
	}
	
	.login-bottom {
		padding: 0 48rpx 80rpx;
		
		.login-btn {
			width: 100%;
			height: 96rpx;
			background: #03D8F4;
			border-radius: 48rpx;
			font-size: 32rpx;
			color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			
			&::after {
				border: none;
			}
		}
		
		.agree-section {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 32rpx;
			
			.check-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 12rpx;
				
				image {
					width: 100%;
					height: 100%;
				}
			}
			
			.agree-text {
				font-size: 24rpx;
				color: #999;
				
				.link {
					color: #333;
				}
			}
		}
	}
	
	// 手机号登录弹窗
	.phone-login-popup {
		background: #FFFFFF;
		border-radius: 32rpx 32rpx 0 0;
		padding: 40rpx 48rpx 80rpx;
		
		.popup-header {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			margin-bottom: 48rpx;
			
			.popup-title {
				font-size: 34rpx;
				font-weight: 500;
				color: #333;
			}
			
			.popup-close {
				position: absolute;
				right: 0;
				font-size: 48rpx;
				color: #999;
			}
		}
		
		.phone-form {
			.input-row {
				height: 100rpx;
				border-bottom: 1rpx solid #EEEEEE;
				margin-bottom: 32rpx;
				
				input {
					height: 100%;
					font-size: 30rpx;
				}
			}
			
			.code-row {
				display: flex;
				align-items: center;
				
				input {
					flex: 1;
				}
				
				.send-btn {
					padding: 16rpx 24rpx;
					background: #333;
					color: #CDEF27;
					font-size: 26rpx;
					border-radius: 12rpx;
					
					&.disabled {
						background: #CCC;
						color: #FFF;
					}
				}
			}
			
			.submit-btn {
				width: 100%;
				height: 96rpx;
				background: linear-gradient(90deg, #5CE1E6, #38D9A9);
				border-radius: 48rpx;
				font-size: 32rpx;
				color: #FFFFFF;
				margin-top: 48rpx;
				border: none;
				
				&::after {
					border: none;
				}
			}
		}
	}
</style>
