<template>
	<view class="container">
		<view class="card">
			<view class="title-login">
				物联网卡登录
			</view>
			<view class="input">
				<up-input class="mt-30" v-model="device_id" placeholder="请输入ICCID"></up-input>
			</view>
			<view class="button">
				<up-button class="mt-30 btn-apple btn-primary" type=" primary" @click="login">立即登录</up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue';

	import {
		userStore
	} from '@/store/index.js';

	const device_id = ref('');

	const login = async () => {
		if (!device_id.value) {
			uni.showToast({
				title: '请输入ICCID',
				icon: 'none'
			})
			return
		}

		try {
			const result = await userStore.actions.login(device_id.value);

			if (result.system_result_message_key) {
				uni.showToast({
					title: result.system_result_message_key,
					icon: 'none'
				})
				return
			}

			uni.showToast({
				title: '登录成功',
				icon: 'none'
			})

			// 登录成功后跳转到首页（登录状态已在store中设置）
			uni.redirectTo({
				url: "/pages/index/index"
			})
		} catch (error) {
			console.error('登录过程中发生错误:', error);
			uni.showToast({
				title: '登录失败，请稍后重试',
				icon: 'none'
			})
		}
	}

	// 获取扫码后路由中带的device_id
	const getPathDeviceId = () => {
		const path = window.location.href.split("=")
		if (path.length > 1) {
			device_id.value = path[1]
			login()
		}
	}

	// 进入页面后自动获取Cookie
	const getCookieAndWxUrl = async () => {
		await userStore.actions.getWxUrl();
	}

	onMounted(() => {
		getCookieAndWxUrl()
		getPathDeviceId()
	})
</script>

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

		.title-login {
			color: #333;
			font-size: 24px;
			text-align: center;
			margin: 20px 0;
			font-weight: bold;
		}

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

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