<template>
	<view class="content" style="height:100vh">
		<u-loading-icon mode="circle" size="64" :vertical="true" color="#2b85e4" textColor="#2b85e4"
			text="正在登录"></u-loading-icon>
	</view>
</template>

<script setup>
	import {
		getCurrentInstance,
		reactive,
		computed
	} from 'vue'
	const api = getCurrentInstance()?.appContext.config.globalProperties.$api;
	const configSign = getCurrentInstance()?.appContext.config.globalProperties.$configSign;
	const openid = computed(() => {
		return uni.getStorageSync('openid');
	})
	const login = async (js_code) => {
		const result = await api('https://broadcast.waityou24.cn/wechat/api/login/app', 'GET', {
			js_code,
			config: configSign
		});
		if (result.errcode === 0) return result.data.openid;
		else {
			uni.showToast({
				title: '登录失败请重进',
				icon: 'fail',
			});
			return false;
		}
	};
	const initUser = async () => {
		uni.login({
			success: async function(result) {
				if (!result.code) {
					uni.showToast({
						title: '登录失败请重进',
						icon: 'fail',
					});
					return false;
				}
				let openid = uni.getStorageSync('openid');
				if (!openid) {
					const res = await login(result.code)
					if (res) {
						uni.setStorageSync('openid', res);
						openid = res;
					}
				}
				if (openid) {
					const result = await api('/user', 'POST', {
						openid
					});
					if(result.errcode!=0) {
						uni.showToast({
							title: result.errmsg,
							icon: 'error',
						});
						return false;
					}
					uni.navigateTo({
						url: '/pages/list/index'
					})
				}

			}
		})
	};
	initUser();
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>