<template>
	<view class="login-page">
		<nav-bar title="登录" bgColor="transparent" color="#fff" :showBack="false"></nav-bar>
		<!-- 顶部渐变装饰区 -->
		<view class="hero-bg">
			<view class="deco-circle c1"></view>
			<view class="deco-circle c2"></view>
			<view class="deco-circle c3"></view>

			<!-- 返回按钮 -->
			<view class="back-btn" @click="onClickLeft">
				<uni-icons type="left" size="22" color="#fff"></uni-icons>
			</view>

			<!-- Logo 区域 -->
			<view class="hero-content">
				<view class="logo-wrap">
					<uni-icons type="headphones" size="42" color="#fff"></uni-icons>
				</view>
				<text class="brand-name">好萌友</text>
				<text class="brand-desc">专业 · 安心 · 便捷</text>
			</view>
		</view>

		<!-- 表单白色卡片区 -->
		<view class="form-card">
			<text class="form-title">账号登录</text>

			<!-- 账号输入框 -->
			<view class="input-group">
				<view class="input-icon-wrap">
					<uni-icons type="person" size="18" color="#ffc837"></uni-icons>
				</view>
				<input class="custom-input" v-model="username" placeholder="请输入登录账号"
					placeholder-class="input-placeholder" />
			</view>

			<!-- 密码输入框 -->
			<view class="input-group">
				<view class="input-icon-wrap">
					<uni-icons type="locked" size="18" color="#ffc837"></uni-icons>
				</view>
				<input class="custom-input" v-model="password" type="password" placeholder="请输入密码"
					placeholder-class="input-placeholder" />
			</view>

			<!-- 提示信息 -->
			<view class="tip-row">
				<uni-icons type="info" size="13" color="#ffaa00"></uni-icons>
				<text>账号由后台创建，不支持自主注册</text>
			</view>

			<!-- 协议勾选 -->
			<view class="agreement-row">
				<checkbox-group @change="onCheckChange">
					<label class="agree-label">
						<checkbox :checked="checked" color="#ffc837" style="transform: scale(0.7);" />
						<text class="agree-text">我已阅读并同意</text>
						<text class="text-link" @click.stop="showAgreement(2)">《隐私政策》</text>
						<text class="agree-text">和</text>
						<text class="text-link" @click.stop="showAgreement(1)">《用户服务协议》</text>
					</label>
				</checkbox-group>
			</view>

			<!-- 登录按钮 -->
			<button class="login-btn" @click="onSubmit">安全登录</button>

			<!-- 注册入口 -->
			<view class="register-redirect-row">
				<text class="redirect-hint">还没有账号？</text>
				<text class="redirect-action" @click="goToRegister">立即注册</text>
			</view>
		</view>

		<!-- 底部装饰 -->
		<view class="footer-hint">
			<text>安全加密 · 保护您的账号信息</text>
		</view>

		<!-- 隐私政策/用户服务协议弹窗 -->
		<policy-dialog v-model:visible="dialogVisible" :title="dialogTitle" :content="dialogContent"></policy-dialog>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import navBar from '@/components/nav-bar/index.vue'
import policyDialog from '@/components/policy-dialog/index.vue'
import { login } from '@/api/auth'
import { getInfo } from '@/api/system/user'
import { getAgreement } from '@/api/system/agreement'
import { AgreementType } from '@/enums/agreementType'
import { DEFAULT_HEADERS } from '@/utils/config'

const username = ref('')
const password = ref('')
const checked = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogContent = ref('')

const onClickLeft = () => uni.reLaunch({ url: '/pages/index/index' })

const goToRegister = () => {
	uni.navigateTo({
		url: '/pages/login/register'
	})
}

const onCheckChange = () => {
	checked.value = !checked.value
}

const onSubmit = async () => {
	if (!username.value) {
		uni.showToast({ title: '请填写账号', icon: 'none' })
		return
	}
	if (!password.value) {
		uni.showToast({ title: '请填写密码', icon: 'none' })
		return
	}
	if (!checked.value) {
		uni.showToast({ title: '请先阅读并勾选协议', icon: 'none' })
		return
	}

	try {
		uni.showLoading({ title: '登录中...' })
		const res = await login({
			userSource: 0,
			username: username.value,
			password: password.value,
			clientId: DEFAULT_HEADERS.clientid,
			grantType: 'password',
			source: 1
		})

		if (res.access_token) {
			uni.setStorageSync('token', res.access_token)

			// 获取用户信息并存储 tenantId
			try {
				const userRes = await getInfo()
				if (userRes && userRes.user && userRes.user.tenantId) {
					uni.setStorageSync('tenantId', userRes.user.tenantId)
				}
			} catch (e) {
				console.error('获取用户信息失败', e)
				uni.showToast({ title: typeof e === 'string' ? e : '请求失败', icon: 'none' })
			}

			uni.showToast({ title: '登录成功', icon: 'success' })
			setTimeout(() => {
				uni.reLaunch({ url: '/pages/index/index' })
			}, 1000)
		} else {
			uni.showToast({ title: '登录异常：未获取到Token', icon: 'none' })
		}
	} catch (error) {
		console.error('Login error:', error)
		uni.showToast({ title: typeof error === 'string' ? error : '登录失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}

const showAgreement = async (agreementId) => {
	try {
		uni.showLoading({ title: '加载中...' })
		const res = await getAgreement(agreementId)

		if (res && res.title) {
			dialogTitle.value = res.title || '协议详情'
			let decodedContent = res.content || '暂无内容'
			if (res.content) {
				try {
					decodedContent = decodeURIComponent(escape(atob(res.content)))
				} catch (e) {
					decodedContent = res.content
				}
			}
			dialogContent.value = decodedContent
			dialogVisible.value = true
		} else {
			console.warn('接口返回数据格式异常:', res)
			uni.showToast({ title: '数据格式异常', icon: 'none' })
		}
	} catch (error) {
		console.error('获取协议失败:', error)
		uni.showToast({ title: typeof error === 'string' ? error : '加载失败，请稍后重试', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}
</script>

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

:deep(.nav-bar) {
	position: absolute !important;
}

.hero-bg {
	background: linear-gradient(150deg, #ffd53f 0%, #ff9500 100%);
	padding: 0 40rpx 140rpx;
	position: relative;
	overflow: hidden;
	min-height: 560rpx;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
}

.deco-circle {
	position: absolute;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.12);
}

.c1 {
	width: 400rpx;
	height: 400rpx;
	top: -160rpx;
	right: -120rpx;
}

.c2 {
	width: 260rpx;
	height: 260rpx;
	top: 80rpx;
	left: -100rpx;
}

.c3 {
	width: 160rpx;
	height: 160rpx;
	bottom: 80rpx;
	right: 80rpx;
}

.back-btn {
	position: absolute;
	top: calc(var(--status-bar-height, 44px) + 20rpx);
	left: 32rpx;
	width: 76rpx;
	height: 76rpx;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.35);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	z-index: 1000;
}

.hero-content {
	position: relative;
	z-index: 2;
}

.logo-wrap {
	width: 140rpx;
	height: 140rpx;
	background: rgba(255, 255, 255, 0.25);
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 28rpx;
}

.brand-name {
	display: block;
	font-size: 52rpx;
	font-weight: 800;
	color: #fff;
	margin-bottom: 8rpx;
}

.brand-desc {
	display: block;
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
	letter-spacing: 4rpx;
}

.form-card {
	background: #fff;
	border-radius: 56rpx 56rpx 0 0;
	margin-top: -60rpx;
	padding: 60rpx 48rpx 40rpx;
	flex: 1;
	position: relative;
	z-index: 10;
}

.form-title {
	display: block;
	font-size: 38rpx;
	font-weight: 700;
	color: #1a1a1a;
	margin-bottom: 48rpx;
}

.input-group {
	display: flex;
	align-items: center;
	background: #f8f8f8;
	border-radius: 28rpx;
	padding: 8rpx 24rpx;
	margin-bottom: 28rpx;
	border: 3rpx solid transparent;
}

.input-icon-wrap {
	margin-right: 16rpx;
	flex-shrink: 0;
}

.custom-input {
	flex: 1;
	height: 88rpx;
	font-size: 30rpx;
	color: #222;
	background: transparent;
}

.input-placeholder {
	color: #c0c0c0;
}

.tip-row {
	display: flex;
	align-items: center;
	gap: 10rpx;
	font-size: 24rpx;
	color: #aaa;
	padding: 8rpx 8rpx 24rpx;
}

.agreement-row {
	margin-bottom: 48rpx;
	padding: 0 4rpx;
}

.agree-label {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}

.agree-text {
	font-size: 24rpx;
	color: #999;
}

.text-link {
	font-size: 24rpx;
	color: #ff9500;
}

.login-btn {
	width: 100%;
	height: 104rpx;
	font-size: 34rpx;
	font-weight: 700;
	color: #fff;
	background: linear-gradient(90deg, #ffd53f, #ff9500);
	border: none;
	border-radius: 52rpx;
	letter-spacing: 4rpx;

	&::after {
		border: none;
	}
}

.footer-hint {
	text-align: center;
	font-size: 22rpx;
	color: #bbb;
	padding: 32rpx 0 60rpx;
	background: #fff;
}

.register-redirect-row {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 36rpx;
	font-size: 26rpx;
}

.redirect-hint {
	color: #999;
}

.redirect-action {
	color: #ff9500;
	font-weight: bold;
	margin-left: 12rpx;
	text-decoration: underline;
}
</style>
