<template>
	<view class="login-page">
		<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="handleBlur"
							@input="showError = false"
						/>
						<image
							v-if="identifier && inputFocus"
							class="clear-icon"
							src="/static/clear.png"
							mode="aspectFit"
							@mousedown.prevent="clearInput"
							@touchstart.prevent="clearInput"
						></image>
					</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>

					<button class="btn-scan" @tap="handleScanLogin">
						<image src="/static/scan-code.png" mode="aspectFit" class="scan-icon"></image>
						<text>扫一扫登录</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 { onHide, onShow, onUnload } from '@dcloudio/uni-app';
	import { authApi, wechatApi } from '@/api/index.js';
	import { useUserStore } from '@/store/index.js';
	import { initWxConfig, wxScan, isInWechat } from '@/utils/wxsdk.js';

	const POST_BIND_RELOGIN_NOTICE_KEY = 'postBindReloginNotice';

	const userStore = useUserStore();
	const identifier = ref(uni.getStorageSync('identifier') || '');
	const loading = ref(false);
	const agreed = ref(true);
	const inputFocus = ref(false);
	const showError = ref(false);
	const wechatAppId = ref('');

	const resetLoadingState = () => {
		loading.value = false;
	};

	onMounted(async () => {
		const token = uni.getStorageSync('token');
		if (token) {
			uni.reLaunch({ url: '/pages/index/index' });
			return;
		}

		showPostBindReloginNotice();
		handleWechatCallback();
		getPathDeviceId();

		// 初始化微信 SDK (仅在微信浏览器内执行)
		// #ifdef H5
		if (isInWechat()) {
			try {
				await initWxConfig();
				console.log('微信 SDK 初始化成功');
			} catch (e) {
				console.error('微信 SDK 初始化失败', e);
			}
		}
		// #endif
	});

	onShow(() => {
		resetLoadingState();
	});

	onHide(() => {
		resetLoadingState();
	});

	onUnload(() => {
		resetLoadingState();
	});

	const showPostBindReloginNotice = () => {
		if (uni.getStorageSync(POST_BIND_RELOGIN_NOTICE_KEY) !== '1') {
			return;
		}

		uni.removeStorageSync(POST_BIND_RELOGIN_NOTICE_KEY);
		uni.showToast({
			title: '绑定手机号成功，请重新登录',
			icon: 'none',
			duration: 2500
		});
	};

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

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

	const getWechatAppId = async () => {
		if (wechatAppId.value) {
			return wechatAppId.value;
		}

		const data = await wechatApi.getAppId();
		if (!data || !data.app_id) {
			uni.showToast({ title: '微信公众号配置缺失', icon: 'none' });
			throw new Error('wechat app_id is empty');
		}

		wechatAppId.value = data.app_id;
		return wechatAppId.value;
	};

	const redirectToWxAuth = async (assetToken) => {
		sessionStorage.setItem('assetToken', assetToken);
		const appId = await getWechatAppId();
		const redirectUri = encodeURIComponent(window.location.origin + window.location.pathname);
		const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=wechat_auth#wechat_redirect`;
		window.location.href = url;
	};

	const clearInput = () => {
		identifier.value = '';
		showError.value = false;
		inputFocus.value = true;
	};

	const handleBlur = () => {
		setTimeout(() => {
			inputFocus.value = false;
		}, 200);
	};

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

	const parseScanIdentifier = (resultStr) => {
		const scanValue = (resultStr || '').trim();
		if (!scanValue) return '';

		const barcodeMatch = scanValue.match(/^[A-Z0-9_]+,(.+)$/);
		if (barcodeMatch) return barcodeMatch[1].trim();

		if (scanValue.includes('?')) {
			const params = new URLSearchParams(scanValue.split('?')[1]);
			const queryValue = params.get('cardNum') || params.get('identifier');
			if (queryValue) return queryValue;
		}

		const match = scanValue.match(/=([^=]+)$/);
		return match ? match[1].trim() : scanValue;
	};

	const handleScanLogin = async () => {
		// #ifdef H5
		try {
			// 检查是否在微信环境
			if (!isInWechat()) {
				uni.showToast({ title: '请在微信中打开', icon: 'none' });
				return;
			}

			// 调用扫一扫
			const resultStr = await wxScan();
			console.log('扫码结果:', resultStr);

			const value = parseScanIdentifier(resultStr);

			if (value) {
				identifier.value = value;
				handleLogin();
			} else {
				uni.showToast({ title: '无效的扫码内容', icon: 'none' });
			}
		} catch (err) {
			console.error('扫码错误:', err);
			// uni.showToast({ title: JSON.stringify(err), icon: 'none' });
		}
		// #endif
		// #ifndef H5
		uni.showToast({ title: '请在微信中打开', icon: 'none' });
		// #endif
	};

	const getPathDeviceId = () => {
		const params = new URLSearchParams(window.location.search);
		const idf = params.get('identifier');
		if (idf) {
			identifier.value = idf;
			handleLogin();
		}
	};

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

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

	const handleWechatCallback = async () => {
		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);

			// #ifdef H5
			if (loginData.user_info) {
				userStore.setUserInfo({
					avatar: loginData.user_info.avatar || '',
					nickname: loginData.user_info.nickname || ''
				});
			}
			// #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;
		}
	};
</script>

<style lang="scss" scoped>
	.login-page {
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 100vh;
		background: var(--bg-secondary);
		max-width: 750rpx;
		margin: 0 auto;
		width: 100%;
		padding: 40rpx;
		box-sizing: border-box;
	}

	.content-wrapper {
		width: 100%;
	}

	.content {
		background: var(--bg-primary);
		border-radius: var(--radius-large);
		padding: 60rpx 40rpx;
		box-shadow: var(--shadow-medium);
	}

	.header {
		text-align: center;
		margin-bottom: 60rpx;
	}

	.main-title {
		font-size: 48rpx;
		font-weight: 700;
		color: var(--text-primary);
		line-height: 1.3;
		margin-bottom: 16rpx;
		letter-spacing: -0.5rpx;
	}

	.sub-title {
		font-size: 26rpx;
		color: var(--text-tertiary);
		line-height: 1.5;
	}

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

	.input-wrap {
		display: flex;
		align-items: center;
		gap: 16rpx;
		background: var(--bg-secondary);
		border: 2rpx solid var(--border-color);
		border-radius: var(--radius-medium);
		padding: 28rpx 32rpx;
		transition: all 0.3s ease;
	}

	.input-wrap.focus {
		background: var(--bg-primary);
		border-color: var(--primary);
		box-shadow: 0 0 0 4rpx rgba(10, 132, 255, 0.1);
	}

	.input {
		flex: 1;
		font-size: 30rpx;
		color: var(--text-primary);
		background: transparent;
	}

	.placeholder {
		color: var(--text-quaternary);
	}

	.clear-icon {
		width: 32rpx;
		height: 32rpx;
		opacity: 0.4;
		transition: opacity 0.3s ease;
		cursor: pointer;
		flex-shrink: 0;
	}

	.clear-icon:active {
		opacity: 0.6;
	}

	.error {
		font-size: 24rpx;
		color: var(--danger);
		margin-top: 16rpx;
		padding-left: 8rpx;
	}

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

	.btn-login {
		width: 100%;
		height: 96rpx;
		background: var(--primary);
		border: none;
		border-radius: var(--radius-medium);
		font-size: 32rpx;
		font-weight: 600;
		color: var(--text-inverse);
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 12rpx rgba(10, 132, 255, 0.2);
	}

	.btn-login.disabled {
		background: var(--gray-300);
		color: var(--text-quaternary);
		box-shadow: none;
	}

	.btn-login:active:not(.disabled) {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(10, 132, 255, 0.2);
	}

	.btn-scan {
		width: 100%;
		height: 88rpx;
		background: var(--bg-primary);
		border: 2rpx solid var(--primary);
		border-radius: var(--radius-medium);
		font-size: 30rpx;
		font-weight: 500;
		color: var(--primary);
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		margin-top: 24rpx;
		transition: all 0.3s ease;
	}

	.btn-scan:active {
		background: rgba(10, 132, 255, 0.05);
	}

	.scan-icon {
		width: 40rpx;
		height: 40rpx;
	}

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

	.dot {
		width: 12rpx;
		height: 12rpx;
		background: var(--text-inverse);
		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: var(--text-tertiary);
		white-space: nowrap;
	}

	.link {
		color: var(--primary);
		font-weight: 500;
		white-space: nowrap;
	}
</style>
