<template>
	<view class="container">
		<view class="card">
			<view class="title-login">
				登录
			</view>
			<view class="input">
				<up-input class="mt-30" v-model="identifier" placeholder="请输入SN/IMEI/虚拟号/ICCID/MSISDN"></up-input>
			</view>
			<view class="button">
				<up-button class="mt-30 btn-apple btn-primary" type="primary" :loading="loading" @click="login">立即登录</up-button>
			</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 } from '@/utils/env.js';

	const userStore = useUserStore();

	const identifier = ref('');
	const loading = ref(false);

	const isWechat = /micromessenger/i.test(navigator.userAgent);

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

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

	const redirectToWxAuth = (assetToken) => {
		const redirectUri = encodeURIComponent(window.location.href.split('?')[0]);
		const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${assetToken}#wechat_redirect`;
		window.location.href = url;
	};

	const login = async () => {
		if (!identifier.value) {
			uni.showToast({ title: '请输入SN/IMEI/虚拟号/ICCID/MSISDN', icon: 'none' });
			return;
		}

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

			// if (!isWechat) {
			// 	uni.showToast({ title: '请在微信中打开', icon: 'none' });
			// 	loading.value = false;
			// 	return;
			// }

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

	const handleWechatCallback = async () => {
		const code = getCode();
		const assetToken = userStore.state.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);
			uni.redirectTo({ url: '/pages/index/index' });
		} catch (e) {
			console.error('微信登录失败', e);
			loading.value = false;
		}
	};

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

<style lang="scss" scoped>
	.container {
		padding-top: 30vh;

		.title-login {
			color: var(--text-primary);
			font-size: 24px;
			text-align: center;
			margin: 20px 0;
			font-weight: bold;
		}

		.input {
			margin: 70rpx 0 50rpx 0;
		}

		.button {
			margin-bottom: 40rpx;
		}
	}
</style>