<template>
	<view class="login-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">登录</text>
		</view>

		<!-- Logo 区域 -->
		<view class="logo-section">
			<image class="logo-icon" src="/static/image/public/logo.png" mode="aspectFill"></image>
			<text class="app-name">{{appName}}</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 手机号输入 -->
			<view class="input-item">
				<uni-easyinput v-model="phoneNumber" placeholder="请输入手机号" type="number" maxlength="11"
					:clearable="false" class="phone-input" />
			</view>

			<!-- 验证码输入 -->
			<view class="input-item verify-code-row">
				<uni-easyinput v-model="verifyCode" placeholder="验证码" type="number" maxlength="6" :clearable="false"
					class="code-input" />
				<text class="get-code-btn" :class="{ disabled: countdown > 0 }" @click="getVerifyCode">
					{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
				</text>
			</view>

			<!-- 登录按钮 -->
			<view class="login-btn-wrapper">
				<button class="login-btn" @click="handleLogin" :loading="isLoading">登录</button>
			</view>

			<!-- 协议说明 -->
			<view class="agreement-text">
				<text class="gray-text">登录即代表您已同意</text>
				<text class="link-text" @click="showUserAgreement">《用户协议》</text>
				<text class="gray-text">与</text>
				<text class="link-text" @click="showPrivacyPolicy">《隐私政策》</text>
			</view>
		</view>

		<!-- 其他登录方式 -->
		<view class="other-method-section">
			<view class="divider">
				<view class="divider-line"></view>
				<text class="divider-text">其他方式</text>
				<view class="divider-line"></view>
			</view>

			<!-- 微信一键登录 -->
			<view class="wechat-login-wrapper">
				<!-- #ifdef MP-WEIXIN -->
				<button class="wechat-login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
					<image class="wechat-icon-img" src="/static/image/public/wechat-icon.png" mode="aspectFit" />
					<text class="wechat-text">微信一键登录</text>
				</button>
				<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<button class="wechat-login-btn" @click="wechatLogin">
					<text class="wechat-icon"></text>
					<text class="wechat-text">微信一键登录</text>
				</button>
				<!-- #endif -->
			</view>
		</view>

		<!-- 用户协议弹窗 -->
		<view class="agreement-popup" v-if="showUserAgreementPopup" @click="closeUserAgreement">
			<view class="popup-mask"></view>
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">用户协议</text>
					<text class="popup-close" @click="closeUserAgreement">✕</text>
				</view>
				<scroll-view scroll-y class="popup-body">
					<view class="agreement-content">
						<yonghuxieyi />
					</view>
				</scroll-view>
				<view class="popup-footer">
					<button class="agree-btn" @click="closeUserAgreement">我已知晓</button>
				</view>
			</view>
		</view>

		<!-- 隐私政策弹窗 -->
		<view class="agreement-popup" v-if="showPrivacyPolicyPopup" @click="closePrivacyPolicy">
			<view class="popup-mask"></view>
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">隐私政策</text>
					<text class="popup-close" @click="closePrivacyPolicy">✕</text>
				</view>
				<scroll-view scroll-y class="popup-body">
					<view class="agreement-content">

						<yonghuzhengce />
					</view>
				</scroll-view>
				<view class="popup-footer">
					<button class="agree-btn" @click="closePrivacyPolicy">我已知晓</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import yonghuxieyi from "./yonghuxieyi.vue"
	import yonghuzhengce from "./yonghuzhengce.vue"

	import {
		getCurrentConfig
	} from '@/config/index.js'
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		sendCode,
		codeLogin,
		wxgetLogin,
		getUserInfo,
		wxLogin
	} from '@/api/login.js'
	import {
		saveToekn,
	} from '@/utils/userCache.js'
	import {
		useUserStore
	} from '@/store/modules/user.js'

	const userStore = useUserStore() || null

	let appName = ref('')
	let version = ref('')
	onMounted(async () => {
		const config = await getCurrentConfig()
		appName.value = config.appName
		version.value = config.appVersion
	})

	// 表单数据
	const phoneNumber = ref('')
	const verifyCode = ref('')
	const countdown = ref(0)
	const isLoading = ref(false)
	let timer = null

	// 弹窗控制
	const showUserAgreementPopup = ref(false)
	const showPrivacyPolicyPopup = ref(false)

	// 获取验证码
	const getVerifyCode = async () => {
		if (countdown.value > 0) return

		if (!phoneNumber.value || phoneNumber.value.length !== 11) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			})
			return
		}
		try {
			const res = await sendCode({
				phone: phoneNumber.value,
				type: 3
			})
			if (res.code != 200) {
				uni.showToast({
					title: res.msg,
					icon: 'error'
				})
				return
			}
			console.log('验证码发送成功:', res)

			// 开始倒计时
			countdown.value = 60
			timer = setInterval(() => {
				countdown.value--
				if (countdown.value <= 0) {
					clearInterval(timer)
				}
			}, 1000)

			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			})
		} catch (error) {
			console.error('发送验证码失败:', error)
		}
	}

	// 处理登录
	const handleLogin = async () => {
		if (isLoading.value) return

		if (!phoneNumber.value || phoneNumber.value.length !== 11) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			})
			return
		}

		if (!verifyCode.value) {
			uni.showToast({
				title: '请输入验证码',
				icon: 'none'
			})
			return
		}

		isLoading.value = true
		try {
			// 第一步：调用登录接口获取 token
			const res = await codeLogin({
				phonenumber: phoneNumber.value,
				smsCode: verifyCode.value
			})
			console.log('登录接口返回:', res)

			if (res.code != 200) {
				uni.showToast({
					title: res.msg || '登录失败',
					icon: 'none'
				})
				isLoading.value = false
				return
			}
			// 获取 token
			const {
				token
			} = res.data || res

			if (!token) {
				uni.showToast({
					title: '未获取到 token',
					icon: 'none'
				})
				isLoading.value = false
				return
			}
			if (token) {
				// 调用 store 里的函数获取名片和公司信息
				saveToekn(token)
			let cardInfo = 	await userStore.queryCardInfo()
				await userStore.queryCompanyInfo()
				await userStore.queryCardQrcode()
				console.log(cardInfo,"cardInfocardInfocardInfo");
				
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				})
				// 延迟跳转
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				uni.showToast({
					title: '保存登录信息失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('登录失败:', error)
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
		}
	}

	// 微信登录 - 获取手机号
	const getPhoneNumber = async (e) => {
		// #ifdef MP-WEIXIN
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			uni.showToast({
				title: '您取消了授权',
				icon: 'none'
			})
			return
		}

		try {
			// 先获取微信登录 code
			const code = await wxLogin()

			// 调用 wxgetLogin 接口，传入 code 和手机号信息
			console.log(e, "eeeeeeee");
			const res = await wxgetLogin({
				wxCode: code,
				phoneCode: e.detail.code,
				iv: e.detail.iv,
				type: 1
			})

			if (res.code != 200) {
				uni.showToast({
					title: res.msg || '登录失败',
					icon: 'none'
				})
				return
			}

			console.log('微信登录成功:', res)

			// 获取 token
			const {
				token
			} = res.data || res

			if (!token) {
				uni.showToast({
					title: '未获取到 token',
					icon: 'none'
				})
				return
			}

			if (token) {
				saveToekn(token)
				await userStore.queryCardInfo()
				await userStore.queryCompanyInfo()
				await userStore.queryCardQrcode()
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				})
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				uni.showToast({
					title: '保存登录信息失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('微信登录失败:', error)
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			})
		}
		// #endif
	}

	// 微信登录（非小程序环境备用）
	const wechatLogin = async () => {
		// #ifndef MP-WEIXIN
		uni.showToast({
			title: '请在微信小程序中使用',
			icon: 'none'
		})
		// #endif
	}

	// 显示用户协议
	const showUserAgreement = () => {
		showUserAgreementPopup.value = true
	}

	// 关闭用户协议
	const closeUserAgreement = () => {
		showUserAgreementPopup.value = false
	}

	// 显示隐私政策
	const showPrivacyPolicy = () => {
		showPrivacyPolicyPopup.value = true
	}

	// 关闭隐私政策
	const closePrivacyPolicy = () => {
		showPrivacyPolicyPopup.value = false
	}

	// 页面卸载时清除定时器
	import {
		onUnmounted
	} from 'vue'
	onUnmounted(() => {
		if (timer) {
			clearInterval(timer)
		}
	})
</script>

<style lang="scss" scoped>
	.login-container {
		min-height: 100vh;
		background-color: #ffffff;
		padding: 0 40rpx;
		position: relative;
	}

	// 导航栏
	.nav-bar {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.nav-title {
			font-size: 34rpx;
			font-weight: 600;
			color: #000000;
		}
	}

	// Logo 区域
	.logo-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 60rpx;
		margin-bottom: 80rpx;

		.logo-icon {
			width: 160rpx;
			height: 160rpx;
			background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
			border-radius: 32rpx;
			box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
		}

		.app-name {
			font-size: 40rpx;
			font-weight: 600;
			color: #000000;
			margin-top: 32rpx;
		}
	}

	// 表单区域
	.form-section {
		.input-item {
			margin-bottom: 24rpx;

			.phone-input,
			.code-input {
				background-color: #f5f7fa;
				border-radius: 16rpx;
				font-size: 28rpx;
			}
		}

		.verify-code-row {
			display: flex;
			align-items: center;

			.code-input {
				flex: 1;
				margin-right: 20rpx;
			}

			.get-code-btn {
				font-size: 26rpx;
				color: #1890ff;
				white-space: nowrap;

				&.disabled {
					color: #999999;
				}
			}
		}

		.login-btn-wrapper {
			margin-top: 48rpx;
			margin-bottom: 24rpx;

			.login-btn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(90deg, #1890ff 0%, #096dd9 100%);
				border-radius: 16rpx;
				border: none;
				font-size: 32rpx;
				font-weight: 500;
				color: #ffffff;
				display: flex;
				align-items: center;
				justify-content: center;

				&::after {
					border: none;
				}
			}
		}

		.agreement-text {
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			font-size: 22rpx;

			.gray-text {
				color: #999999;
				margin: 0 4rpx;
			}

			.link-text {
				color: #1890ff;
				margin: 0 4rpx;
			}
		}
	}

	// 其他登录方式
	.other-method-section {
		margin-top: 120rpx;

		.divider {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 40rpx;

			.divider-line {
				width: 120rpx;
				height: 1rpx;
				background-color: #e5e5e5;
			}

			.divider-text {
				font-size: 24rpx;
				color: #999999;
				margin: 0 24rpx;
			}
		}

		.wechat-login-wrapper {
			.wechat-login-btn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(90deg, #07c160 0%, #06ad56 100%);
				border-radius: 16rpx;
				border: none;
				font-size: 32rpx;
				font-weight: 500;
				color: #ffffff;
				display: flex;
				align-items: center;
				justify-content: center;

				&::after {
					border: none;
				}

				.wechat-icon-img {
					width: 40rpx;
					height: 40rpx;
					margin-right: 12rpx;
				}

				.wechat-icon {
					margin-right: 12rpx;
					font-size: 36rpx;
				}

				.wechat-text {
					color: #ffffff;
				}
			}
		}
	}

	// 协议弹窗
	.agreement-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1000;

		.popup-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.popup-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #ffffff;
			border-radius: 32rpx 32rpx 0 0;
			max-height: 80vh;
			display: flex;
			flex-direction: column;
			animation: slideUp 0.3s ease-out;

			.popup-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 32rpx;
				border-bottom: 1rpx solid #f0f0f0;

				.popup-title {
					font-size: 32rpx;
					font-weight: 600;
					color: #000000;
				}

				.popup-close {
					font-size: 40rpx;
					color: #999999;
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.popup-body {
				flex: 1;
				overflow-y: auto;
				padding: 32rpx;

				.agreement-content {
					display: flex;
					flex-direction: column;

					.agreement-title {
						font-size: 36rpx;
						font-weight: 600;
						color: #000000;
						display: block;
						text-align: center;
						margin-bottom: 20rpx;
					}

					.update-time {
						font-size: 24rpx;
						color: #999999;
						display: block;
						text-align: center;
						margin-bottom: 40rpx;
					}

					.section {
						margin-bottom: 32rpx;

						.section-title {
							font-size: 28rpx;
							font-weight: 600;
							color: #000000;
							display: block;
							margin-bottom: 16rpx;
						}

						.section-content {
							font-size: 24rpx;
							color: #333333;
							line-height: 1.8;
							display: block;
							white-space: pre-wrap;
						}
					}
				}
			}

			.popup-footer {
				padding: 24rpx 32rpx 40rpx;
				border-top: 1rpx solid #f0f0f0;

				.agree-btn {
					width: 100%;
					height: 80rpx;
					background: linear-gradient(90deg, #1890ff 0%, #096dd9 100%);
					border-radius: 16rpx;
					border: none;
					font-size: 30rpx;
					font-weight: 500;
					color: #ffffff;
					display: flex;
					align-items: center;
					justify-content: center;

					&::after {
						border: none;
					}
				}
			}
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}
</style>