<template>
	<view class="w-body" :style="{'--bottom':$w.bottom+'px'}">
		<w-navbar fixed left-home left-back title="WebSocket" class="navbar"></w-navbar>
		<view class="chat">
			<view v-for="(item, i) in list" :key="i" :class="{ 'chat-my': item.from == authStore.user.userId }">
				<view><c-user :id="item.from" :name="false" /></view>
				<view class="chat-content">{{ item.msg }}</view>
			</view>
			
			<view style="height: calc(var(--bottom) + 105px);"></view>

		</view>
		<view class="chat-bar" style="padding-bottom: calc(var(--bottom) + 5px);">
			<view><u-input v-model="msg" @keyup.enter="sendMsg" />
				<view @click="msg+='😀'">😀</view><u-button @click="sendMsg">提交</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { send } from '@/WebSocket'
import { useAuthStore } from '@/store'
import { connect,close } from '@/WebSocket'

const authStore = useAuthStore();

const msg = ref("😀");

const list = ref([]);

const sendMsg = () => {
	if (msg.value) {
		console.debug("msg", msg.value)
		send('chat', { msg: msg.value });
		msg.value = "";
	}
}

onLoad(() => {
	connect();
	uni.$off("chat_response");
	uni.$on("chat_response", (e) => {
		console.debug("chat", e);
		list.value.push(e.data);
		uni.pageScrollTo({
			duration: 1000,
			scrollTop: 100000
		})
	});
});
onUnload(() => {
	close();
	uni.$off("chat_response");
})
</script>

<style lang="scss" scoped>
.w-body {
	min-height: 100vh;
	background-color: var(--w-bg);
}

.chat {
	font-size: .8rem;

	&-bar {
		padding: .5rem;
		position: fixed;
		width: 100vw;
		bottom: 0;
		left: 0;
		background-color: var(--w-bg);
		border-top: solid 1px var(--w-bg-dark);

		&>view {
			display: grid;
			grid-template-columns: 1fr 1em 4em;
			gap: .5rem;

			&>view {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}

	&>view {
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
		margin-top: .5rem;


	}

	&-content {
		margin: 0 .4rem;
		background-color: var(--w-bg-light);
		min-width: 20vw;
		max-width: calc(100vw - 5em);
		padding: .5rem;
		border-radius: .5rem;
		word-wrap: anywhere;
		position: relative;
		box-shadow: 0 0 .5rem #0001;

		&::before {
			content: '';
			position: absolute;
			width: 0;
			height: 0;
			box-sizing: content-box;
			border: solid .5rem #0000;
			border-left-width: 0;
			border-right-color: var(--w-bg-light);
			left: -.4rem;
			top: .5rem;
		}

	}

	&-my {
		flex-direction: row-reverse;

		.chat-content {
			background-color: var(--w-success);

			&::before {
				border-left-width: .5rem;
				border-right-width: 0;
				border-left-color: var(--w-success);
				left: auto;
				right: -.4rem;
			}
		}

	}
}
</style>