<template>
	<view class="my">
		<view class="user-info">
			<view class="background">

			</view>
			<view class="info-content">
				<view class="top-user-name" :style="{'height': topHeight, 'line-height': topHeight}">
					{{userInfo.nickName}}
				</view>
				<view class="avatars">
					<image class="avatar-img"
						:src="userInfo.avatarUrl ? userInfo.avatarUrl : 'https://pic.rmb.bdstatic.com/bjh/down/1742bc3845cbbcf0c78c01eb59bb1c1a.jpeg'">
					</image>
				</view>
				<view class="hello-text">
					<p>你好，{{userInfo.nickName}}</p>
					<p>欢迎使用计分小程序</p>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		onUnmounted,
		ref,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import {
		getOpenId
	} from '@/utils/wxutils.js'
	import {
		register,
		login
	} from '@/api/user.js'

	const proxy = getCurrentInstance().proxy;

	// 小程序胶囊高度
	const topHeight = ref(proxy.$StaticValue.getTopHeight());

	// 用户信息相关
	const userInfo = ref({});
	const getUserInfo = async () => {
		// 从本地获取用户信息
		userInfo.value = proxy.$StaticValue.getUserInfo();
		if (!userInfo.value?.userId) {
			// 如果没有登录, 获取到当前用户的openid
			const openIdRes = await getOpenId();
			console.log("获取的openid: ", openIdRes)
			const openId = openIdRes.openid;
			userInfo.value = {
				openId: openId,
				nickName: '用户' + openId.substring(0, 6)
			};
			register(userInfo.value).then(res => {
				// 注册成功就执行登录
				login(userInfo.value).then(loginRes => {
					userInfo.value = loginRes.data;
					// 存储用户信息到本地
					proxy.$StaticValue.setUserInfo(userInfo.value);
				});
			});
		}
	}
	onMounted(() => {
		getUserInfo();
	});
</script>

<style lang="less" scoped>
	.my {
		width: 750rpx;
		margin: 0;
		padding: 0;
	}

	.user-info {
		--user-height: 500rpx;
		width: 750rpx;
		height: var(--user-height);
		background-color: #f5f5f5;
		position: relative;

		.background {
			width: 750rpx;
			height: var(--user-height);
			background-image: linear-gradient(rgb(87, 255, 87), rgb(144, 251, 144));
			position: absolute;
			top: 0;
			left: 0;
			z-index: 0;
		}

		.info-content {
			width: 750rpx;
			height: var(--user-height);
			position: absolute;
			top: 0;
			left: 0;
			z-index: 1;

			.top-user-name {
				width: 750rpx;
				font-size: 40rpx;
				font-weight: bold;
				color: #000000;
				padding: 0 20rpx;
				box-sizing: border-box;
			}

			.avatars {
				width: 750rpx;
				display: flex;
				justify-content: center;
				margin-top: 20rpx;

				.avatar-img {
					width: 150rpx;
					height: 150rpx;
					border-radius: 75rpx;
					border: 4rpx solid #ffffff;
				}
			}

			.hello-text {
				width: 750rpx;
				text-align: center;
				margin-top: 20rpx;
				font-size: 30rpx;
				color: #000000;

				p {
					margin: 5rpx 0;
				}
			}
		}
	}
</style>