<template>
	<view id='app'>
		<view class="pageView">
			<view class="sidebar-left"></view>
			<view class="body">
				<view class="head">
					<text>uniapp聊天框</text>
				</view>
				<view class="list-wrap">
					<scroll-view id="content-box" scroll-y="true" class="scrollview" :scroll-top="msgList.scrollTop">
						<!-- 聊天主体 -->
						<view id="content-overflow">
							<view class="scrollview-item" v-for="(item,index) in msgList.myList" :key='index'>
								<!-- user方-聊天内容 -->
								<view class="item self" v-if="item.userContent != ''">
									<image class="avtar" src="../../static/user-avatar.png" mode="aspectFit"></image>
									<view class="content right" disabled>{{ item.userContent }}</view>
								</view>
								<!-- ai方-聊天内容 -->
								<view class="item other" v-if="item.otherContent != ''">
									<view class="content left">{{ item.otherContent }}</view>
									<image class="avtar" src="../../static/Ai-avatar.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>

				<view class="chat-bottom">
					<view class="send-msg">
						<view class="uni-textarea">
							<textarea id="input-textarea" type="text" v-model="msgList.chatMsg" placeholder="快来聊天吧"
								confirm-type="send" @confirm="handleSend" maxlength="300" />
						</view>
						<view class="uni-button">
							<button class="send-btn" @click="handleSend" type="primary">发送</button>
						</view>
					</view>
				</view>
			</view>
			<view class="sidebar-right">
				<image src="../../static/logo.png" mode="aspectFit"></image>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		nextTick,
		reactive,
		watch
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'

	const msgList = reactive({
		chatMsg: '',
		myList: [{
			userContent: '',
			otherContent: '',
			image: ''
		}, ],
		// 滚动距离
		scrollTop: 0,
		boxWord: '选择无处不在，面朝大海春暖花开是海子的选择，人不是生来被打败的是海明威的选择，人固有一死，或重于泰山，或轻于鸿毛，是司马迁的选择，选择是一次又一次自我重塑的过程，让我们不断地成长，不断地完善，如果说人生是一次不断选择的旅程，那么当千帆阅尽最终留下的就是一片属于自己的独一无二的风景   ——董卿《朗读者》'
	})

	// 发送消息
	const handleSend = (() => {
		if (msgList.chatMsg != '') {
			let obj = {
				otherContent: msgList.boxWord,
				userContent: msgList.chatMsg,
				image: ""
			}
			msgList.myList.push(obj)
		}
		msgList.chatMsg = ''
	})

	// 滚动条回到最底部
	const scrollToBottom = (() => {
		nextTick(() => {
			const query = uni.createSelectorQuery();
			query.select("#content-box").boundingClientRect()
			query.select("#content-overflow").boundingClientRect()
			query.exec(res => {
				const scrollViewHeight = res[0].height
				const scrollContentHeight = res[1].height
				if (scrollViewHeight < scrollContentHeight) {
					const scrollTop = scrollContentHeight - scrollViewHeight
					msgList.scrollTop = scrollTop
				}
			})
		})
	})
	//滚动至聊天底部
	watch(msgList.myList, (newVal) => {
		scrollToBottom()
	})
</script>

<style>
	@import url("../../theme/chat15.css");
</style>