

<template>

</template>
<script>
// 获取用户信息和聊天信息后端接口，根据自己的实际项目修改
import {findMessageBySendUserAndReceiveUser, searchUserForForm} from '../api/message'
// 发送信息给指定userId的websocket
import {sendMessageTo} from '../api/webSocketApi'
// 根据userId获取用户信息
import {searchUserByUserId} from '../api/user'
// 刚刚写的websocket
import websocket from '../utils/webSocket'

export default {
	data () {
		return {
			currentUser: null, // 当前聊天的人
			loginUser: null,
			messages: [],
			messageForm: [], // 聊天所有信息
			newMessage: {
				handle: '',
				sendUser: '',
				receiveUser: '',
				content: '',
				is_read: '0',
				createTime: ''
			},
			searchUserName: ''
		}
	},
	methods: {
		async fetchMessages (userId) {
			if (!userId) {
				this.searchUserForForm()
				return
			}
			if (this.loginUser.userId == null) {
				this.$message.error('登录用户编号获取失败,请重新登录!')
				return
			}
			findMessageBySendUserAndReceiveUser(userId, this.loginUser.userId ).then(async res => {
				await this.searchUserForForm()
				this.messages = res.value
				// 将聊天记录总下拉到最下方
				this.$nextTick(() => {
					this.scrollToBottom()
				})
			})
		},
		sendMessage () {
			if (!this.newMessage.content.trim()) {
				this.$message.warning('请输入聊天内容')
				return
			}
			this.newMessage.content = this.newMessage.content.trim()
			if (this.loginUser.userId == null) {
				this.$message.error('登录用户编号获取失败,请重新登录!')
				return
			}
			if (this.loginUser.userId  === this.currentUser.userId) {
				this.$message.error('不能给自己发送信息!')
				return
			}
			this.newMessage.sendUser = this.loginUser.userId
			this.newMessage.receiveUser = this.currentUser.userId
			this.sendWebSocketMessage(this.newMessage)
			sendMessageTo(this.newMessage).then(res => {
				if (res.header.code !== 0) {
					this.$message.error(res.header.message)
					return
				}
				this.chooseUser(this.currentUser)
			})
		},
		// 消息过多的时候滚动到最新消息位置
		scrollToBottom () {
			// 使用 $refs 来获取对消息容器的引用
			const container = this.$refs.messageContainer.$refs.wrap
			// 滚动到底部
			container.scrollTop = container.scrollHeight
		},
		checkAvatar (avatar) {
			if (avatar && avatar !== undefined) {
				return avatar
			}
			return ''
		},
		chooseUser (user) {
			this.currentUser = user
			this.fetchMessages(user.userId)
		},
		// websocket
		async connectWebSocket (userId) {
			await new Promise((resolve) => {
				websocket.Init(userId)

				// 在 WebSocket 连接成功时调用 resolve
				websocket.getWebSocket().onopen = () => {
					console.log('WebSocket连接成功')
					resolve()
				}
			})
		},
		// 发送信息
		sendWebSocketMessage (message) {
			websocket.getWebSocket().onmessage = (event) => {
				// 处理消息，这里你可以根据实际需求更新页面上的数据
				console.log('收到的消息WebSocket2:', event)
				// 更新收到的消息
				// receivedMessage.value = event.data
				if (this.currentUser) {
					this.fetchMessages(this.currentUser.userId)
				} else {
					this.fetchMessages()
				}
			}
		},
		handleMessage (message) {
			// 内容进行相应的处理
			const parsedMessage = JSON.parse(message)
			console.log('收到信息:', parsedMessage)
			if (this.currentUser) {
				this.fetchMessages(this.currentUser.userId)
			} else {
				this.fetchMessages()
			}
		},
		// 获取所有信息
		searchUserForForm () {
			if (this.loginUser !== null) {
				searchUserForForm(this.loginUser.userId, this.searchUserName).then(res => {
					if (res.header.code !== 0) {
						this.$message.error(res.header.message)
						return
					}
					this.messageForm = res.value
				})
			}
		},
		// 初始化websocket
		async connectWebSocket (userId) {
			await new Promise((resolve) => {
				websocket.Init(userId)

				// 在 WebSocket 连接成功时调用 resolve
				websocket.getWebSocket().onopen = () => {
					console.log('WebSocket连接成功')
					resolve()
				}
			})
		},
	},
	mounted () {
		websocket.setMessageCallback((res) => {
			this.handleMessage(res)
		})
	},
	created () {
	},
	beforeCreate () {
		// 获取登录用户userId,请根据自己实际项目获取
		let userId = ''
		this.connectWebSocket(userId)
		if (userId) {
			searchUserByUserId(userId).then(res => {
				if (res.header.code === 0) {
					if (res.value) {
						this.loginUser = res.value
					} else {
						this.loginUser.userId = userId
					}
				}
			}).then(() => {
				this.searchUserForForm()
			})
		}
	}
}
</script>

<style scoped>
.chat-container {
	display: flex;
	height: 100%;
	background: linear-gradient(to bottom right, #FFFFFF, #ECEFF1);
}

.left-side {
	position: relative; /* Position relative for absolute positioning */
	flex: 1;
	padding: 20px;
	border-right: 1px solid #eaeaea;
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.search-input {
	position: absolute;
	top: 20px;
	left: 20px;
	width: calc(100% - 40px);
	max-width: 300px;
}

.user-list-scroll {
	top: 40px;
	height: calc(100% - 40px);
	overflow-y: auto;
}

.user-avatar-wrapper {
	position: relative;
	display: inline-block;
}

.user-avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	margin-right: 10px;
	border: 1px solid #74ffd2;
}

.user-name {
	font-weight: 800;
	white-space: nowrap; /* 不换行 */
	overflow: hidden; /* 溢出隐藏 */
	padding-left: 15px;
	text-overflow: ellipsis; /* 超出显示省略号 */
	text-align: left; /* 添加左对齐属性 */
}

.user-last-message {
	color: #a19f9f;
	font-size: 14px;
	white-space: nowrap;
	overflow: hidden;
	padding-left: 15px;
	text-overflow: ellipsis;
	text-align: left; /* 添加左对齐属性 */
}

.right-side {
	flex: 3;
	display: flex;
	flex-direction: column;
}

.chat-header {
	padding: 20px;
	border-bottom: 1px solid #eaeaea;
	font-size: 1.2em;
	color: #37474F;
}

.chat-messages {
	flex: 1;
	overflow-y: auto;
	padding: 20px;
}

.chat-input {
	padding: 20px;
	display: flex;
	align-items: center;
}

.message-input {
	flex: 1;
	margin-right: 10px;
}

.send-button {
	flex-shrink: 0;
}

.user-item {
	display: flex;
	align-items: center;
	padding: 10px;
	border-bottom: 1px solid #f0f0f2;
}

.user-item:hover {
	background-color: #E0E0E0;
	cursor: pointer;
	transition: background-color 0.3s ease;
}

.user-details {
	flex-grow: 1; /* 填充剩余空间 */
}

.messageBox {
	display: flex;
	align-items: flex-start; /* 将头像和文本第一行对齐 */
	margin-bottom: 10px;
}

.messageBox img {
	width: 40px; /* 调整头像大小 */
	height: 40px;
	border-radius: 50%;
	margin-right: 10px;
	margin-left: 10px;
}

.messageContent {
	max-width: 70%; /* 调整发送信息宽度 */
	padding: 10px;
	border-radius: 8px;
	background-color: #f0f0f0;
	text-align: left; /* 文本左对齐 */
	word-wrap: break-word; /* 当文本过长时自动换行 */
}

.messageTime {
	font-size: 12px;
	color: #999;
	margin-left: 10px;
	margin-top: 5px; /* 将发送时间与文本分隔开 */
}

.ownMessage {
	flex-direction: row-reverse;
	align-items: flex-end; /* 将发送时间放置在最下方的贴右位置 */
}

.otherMessage {
	flex-direction: row;
	align-items: flex-end; /* 将发送时间放置在最下方的贴左位置 */
}

.online-dot {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 1;
	width: 10px;
	height: 10px;
	background-color: #01c201;
	border-radius: 50%;
}
.message-badge .el-badge__content {
	position: absolute;
	bottom: 5px; /* Adjust to your desired position */
	left: 5px; /* Adjust to your desired position */
	background-color: #f56c6c; /* Red background for visibility */
	color: white; /* White text color */
}
</style>

