<template>
	<view class="login-page">
		<view class="overlay"></view>
		<view class="animated-bg">
			<view class="circle circle-1"></view>
			<view class="circle circle-2"></view>
			<view class="circle circle-3"></view>
			<view class="circle circle-4"></view>
			<view class="circle circle-5"></view>
			<view class="shape shape-triangle"></view>
			<view class="shape shape-square"></view>
			<view class="shape shape-pentagon"></view>
			<view class="shape shape-hexagon"></view>
		</view>
		<view class="content-wrapper">
			<view class="content">
				<view class="header">
					<view class="main-title">登录</view>
					<view class="sub-title">请输入标识进行登录</view>
				</view>

			<view class="form-section">
				<view class="input-wrap" :class="{ focus: inputFocus }">
					<input
						v-model="identifier"
						class="input"
						placeholder="请输入标识"
						placeholder-class="placeholder"
						@focus="inputFocus = true"
						@blur="inputFocus = false"
						@input="showError = false"
					/>
				</view>
				<text v-if="showError" class="error">请输入标识</text>
			</view>

			<view class="btn-section">
				<button
					class="btn-login"
					:class="{ disabled: !identifier || loading || !agreed }"
					:disabled="!identifier || loading || !agreed"
					@tap="handleLogin"
				>
					<view v-if="loading" class="loading">
						<view class="dot"/>
						<view class="dot"/>
						<view class="dot"/>
					</view>
					<text v-else>登录</text>
				</button>
			</view>

			<view class="agreement">
				<view class="agreement-text">
					<text class="text">登录即表示同意</text>
					<text class="link">《用户协议》</text>
					<text class="text">和</text>
					<text class="link">《隐私政策》</text>
				</view>
			</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import { authApi } from '@/api/index.js';
	import { useUserStore } from '@/store/index.js';
	import { APP_ID, USE_WECHAT_AUTH } from '@/utils/env.js';

	const userStore = useUserStore();

	const identifier = ref('');
	const loading = ref(false);
	const agreed = ref(true);
	const inputFocus = ref(false);
	const showError = ref(false);

	const getCode = () => {
		const params = new URLSearchParams(window.location.search);
		return params.get('code');
	};

	const clearCode = () => {
		window.history.replaceState({}, '', window.location.pathname);
	};

	const redirectToWxAuth = (assetToken) => {
		sessionStorage.setItem('assetToken', assetToken);
		const redirectUri = encodeURIComponent('https://cmp-c.boss160.cn/');
		const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=wechat_auth#wechat_redirect`;
		window.location.href = url;
	};

	const handleLogin = () => {
		if (!identifier.value) {
			showError.value = true;
			return;
		}
		doLogin();
	};

	const doLogin = async () => {
		loading.value = true;
		try {
			const verifyData = await authApi.verifyAsset(identifier.value);
			userStore.setAssetToken(verifyData.asset_token);
			userStore.setIdentifier(identifier.value);

			if (!USE_WECHAT_AUTH) {
				const loginData = await authApi.wechatLogin(verifyData.asset_token, 'mock_code');
				userStore.setToken(loginData.token);
				uni.setStorageSync('identifier', userStore.state.identifier);

				// 判断是否需要绑定手机号
				if (loginData.need_bind_phone) {
					uni.redirectTo({ url: '/pages/bind/bind?fromLogin=true' });
				} else {
					uni.redirectTo({ url: '/pages/index/index' });
				}
				return;
			}

			redirectToWxAuth(verifyData.asset_token);
		} catch (e) {
			console.error('登录失败', e);
			loading.value = false;
		}
	};

	const handleWechatCallback = async () => {
		if (!USE_WECHAT_AUTH) return;

		const code = getCode();
		const assetToken = sessionStorage.getItem('assetToken');

		if (!code || !assetToken) return;

		loading.value = true;
		clearCode();

		try {
			const loginData = await authApi.wechatLogin(assetToken, code);
			userStore.setToken(loginData.token);
			uni.setStorageSync('identifier', userStore.state.identifier);

			// H5 环境获取微信用户信息
			// #ifdef H5
			try {
				// 通过 uni.getUserProfile 获取用户信息（需要用户点击授权）
				// 注意：这个方法在微信公众号 H5 中不可用，需要通过后端接口获取
				// 这里暂时保存默认信息，实际应该由后端返回用户信息
				if (loginData.user_info) {
					userStore.setUserInfo({
						avatar: loginData.user_info.avatar || '',
						nickname: loginData.user_info.nickname || ''
					});
				}
			} catch (err) {
				console.log('获取用户信息失败', err);
			}
			// #endif

			// #ifdef MP-WEIXIN
			// 小程序环境可以直接获取用户信息
			try {
				const { userInfo } = await uni.getUserProfile({
					desc: '用于完善用户资料'
				});
				userStore.setUserInfo({
					avatar: userInfo.avatarUrl || '',
					nickname: userInfo.nickName || ''
				});
			} catch (err) {
				console.log('用户取消授权');
			}
			// #endif

			// 判断是否需要绑定手机号
			if (loginData.need_bind_phone) {
				// 需要绑定手机号，跳转到绑定页面
				uni.redirectTo({ url: '/pages/bind/bind?fromLogin=true' });
			} else {
				// 不需要绑定，直接进入首页
				uni.redirectTo({ url: '/pages/index/index' });
			}
		} catch (e) {
			console.error('微信登录失败', e);
			loading.value = false;
		}
	};

	onMounted(() => {
		handleWechatCallback();
	});
</script>

<style lang="scss" scoped>
	.login-page {
		position: relative;
		display: flex;
		flex-direction: column;
		background: linear-gradient(135deg, #005cbf 0%, #007aff 50%, #4da6ff 100%);
		min-height: 100vh;
	}

	.overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: radial-gradient(circle at 30% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
		            radial-gradient(circle at 70% 80%, rgba(255, 255, 255, 0.08) 0%, transparent 50%);
		z-index: 0;
	}

	.animated-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
		z-index: 0;
	}

	.circle {
		position: absolute;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.1);
		backdrop-filter: blur(2px);
	}

	.circle-1 {
		width: 300rpx;
		height: 300rpx;
		top: 10%;
		left: -100rpx;
		animation: float1 20s infinite ease-in-out;
	}

	.circle-2 {
		width: 200rpx;
		height: 200rpx;
		top: 60%;
		right: -50rpx;
		animation: float2 15s infinite ease-in-out;
	}

	.circle-3 {
		width: 150rpx;
		height: 150rpx;
		top: 30%;
		right: 20%;
		animation: float3 18s infinite ease-in-out;
	}

	.circle-4 {
		width: 250rpx;
		height: 250rpx;
		bottom: 10%;
		left: 10%;
		animation: float4 22s infinite ease-in-out;
	}

	.circle-5 {
		width: 180rpx;
		height: 180rpx;
		top: 50%;
		left: 50%;
		animation: float5 16s infinite ease-in-out;
	}

	@keyframes float1 {
		0%, 100% {
			transform: translate(0, 0) scale(1);
			opacity: 0.3;
		}
		50% {
			transform: translate(100rpx, -80rpx) scale(1.2);
			opacity: 0.5;
		}
	}

	@keyframes float2 {
		0%, 100% {
			transform: translate(0, 0) scale(1);
			opacity: 0.2;
		}
		50% {
			transform: translate(-80rpx, 100rpx) scale(1.3);
			opacity: 0.4;
		}
	}

	@keyframes float3 {
		0%, 100% {
			transform: translate(0, 0) scale(1);
			opacity: 0.25;
		}
		50% {
			transform: translate(-60rpx, -60rpx) scale(1.1);
			opacity: 0.45;
		}
	}

	@keyframes float4 {
		0%, 100% {
			transform: translate(0, 0) scale(1);
			opacity: 0.3;
		}
		50% {
			transform: translate(120rpx, -100rpx) scale(1.15);
			opacity: 0.5;
		}
	}

	@keyframes float5 {
		0%, 100% {
			transform: translate(-50%, -50%) scale(1);
			opacity: 0.2;
		}
		50% {
			transform: translate(calc(-50% + 80rpx), calc(-50% + 80rpx)) scale(1.25);
			opacity: 0.4;
		}
	}

	.shape {
		position: absolute;
		background: rgba(255, 255, 255, 0.08);
		backdrop-filter: blur(1px);
	}

	.shape-triangle {
		width: 0;
		height: 0;
		background: transparent;
		border-left: 80rpx solid transparent;
		border-right: 80rpx solid transparent;
		border-bottom: 140rpx solid rgba(255, 255, 255, 0.1);
		top: 15%;
		right: 15%;
		animation: rotate1 25s infinite linear;
	}

	.shape-square {
		width: 120rpx;
		height: 120rpx;
		top: 70%;
		left: 5%;
		transform: rotate(45deg);
		animation: float-rotate 20s infinite ease-in-out;
	}

	.shape-pentagon {
		width: 100rpx;
		height: 100rpx;
		clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%);
		top: 40%;
		left: 80%;
		animation: pulse 18s infinite ease-in-out;
	}

	.shape-hexagon {
		width: 90rpx;
		height: 90rpx;
		clip-path: polygon(30% 0%, 70% 0%, 100% 50%, 70% 100%, 30% 100%, 0% 50%);
		bottom: 25%;
		right: 25%;
		animation: float-spin 22s infinite ease-in-out;
	}

	@keyframes rotate1 {
		0% {
			transform: rotate(0deg);
			opacity: 0.15;
		}
		50% {
			opacity: 0.25;
		}
		100% {
			transform: rotate(360deg);
			opacity: 0.15;
		}
	}

	@keyframes float-rotate {
		0%, 100% {
			transform: translate(0, 0) rotate(45deg);
			opacity: 0.2;
		}
		50% {
			transform: translate(80rpx, -60rpx) rotate(225deg);
			opacity: 0.35;
		}
	}

	@keyframes pulse {
		0%, 100% {
			transform: scale(1);
			opacity: 0.2;
		}
		50% {
			transform: scale(1.3);
			opacity: 0.4;
		}
	}

	@keyframes float-spin {
		0%, 100% {
			transform: translate(0, 0) rotate(0deg);
			opacity: 0.25;
		}
		50% {
			transform: translate(-70rpx, 90rpx) rotate(180deg);
			opacity: 0.4;
		}
	}

	.content-wrapper {
		position: relative;
		padding: 60rpx 40rpx;
		z-index: 1;
	}

	.header {
		margin-bottom: 80rpx;
	}

	.main-title {
		font-size: 56rpx;
		font-weight: 700;
		color: #FFFFFF;
		line-height: 1.3;
		margin-bottom: 24rpx;
		letter-spacing: 0.5rpx;
		text-shadow: 0 2rpx 8rpx rgba(64, 40, 128, 0.3);
	}

	.sub-title {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.9);
		line-height: 1.5;
		letter-spacing: 0.5rpx;
		text-shadow: 0 1rpx 4rpx rgba(64, 40, 128, 0.2);
	}

	.form-section {
		margin-bottom: 60rpx;
	}

	.input-wrap {
		display: flex;
		align-items: center;
		background: rgba(255, 255, 255, 0.95);
		border-radius: 20rpx;
		padding: 32rpx 40rpx;
		transition: all 0.3s;
		box-shadow: 0 4rpx 16rpx rgba(64, 40, 128, 0.1);
	}

	.input-wrap.focus {
		background: rgba(255, 255, 255, 1);
		box-shadow: 0 4rpx 20rpx rgba(64, 40, 128, 0.2);
	}

	.input {
		flex: 1;
		font-size: 32rpx;
		color: #1A1A1A;
		background: transparent;
	}

	.placeholder {
		color: #C4C4C4;
	}

	.error {
		font-size: 24rpx;
		color: #EF4444;
		margin-top: 16rpx;
		padding-left: 8rpx;
	}

	.btn-section {
		margin-bottom: 60rpx;
	}

	.btn-login {
		width: 100%;
		height: 108rpx;
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(10px);
		border: 2rpx solid rgba(255, 255, 255, 0.4);
		border-radius: 20rpx;
		font-size: 36rpx;
		font-weight: 600;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	}

	.btn-login.disabled {
		background: rgba(255, 255, 255, 0.3);
		color: rgba(255, 255, 255, 0.7);
		border: 2rpx solid rgba(255, 255, 255, 0.2);
		box-shadow: none;
	}

	.btn-login:active:not(.disabled) {
		opacity: 0.8;
	}

	.loading {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.dot {
		width: 10rpx;
		height: 10rpx;
		background: #FFFFFF;
		border-radius: 50%;
		animation: load 1.4s infinite ease-in-out both;
	}

	.dot:nth-child(1) { animation-delay: -0.32s; }
	.dot:nth-child(2) { animation-delay: -0.16s; }

	@keyframes load {
		0%, 80%, 100% {
			transform: scale(0.5);
			opacity: 0.3;
		}
		40% {
			transform: scale(1);
			opacity: 1;
		}
	}

	.agreement {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 8rpx;
	}

	.agreement-text {
		font-size: 24rpx;
		line-height: 1.6;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: center;
		gap: 4rpx;
	}

	.text {
		color: rgba(255, 255, 255, 0.8);
		white-space: nowrap;
	}

	.link {
		color: #FFFFFF;
		font-weight: 500;
		white-space: nowrap;
		text-decoration: underline;
	}
</style>
