<template>
	<el-row :gutter="20" class="chat-container">
		<!-- 用户姓名列 -->
		<el-col :span="6" class="patient-list-col">
			<div class="patient-list-header">
				<h3>患者列表</h3>
				<el-tag type="success">聊天用户量 {{ state.userList.length }} 人</el-tag>
			</div>
			<ul class="patient-list">
				<li v-for="user in state.userList"
						:key="user.id"
						:class="['patient-item', { 'active': state.jiaoliu.userId === user.id }]"
						@click="selectUser(user)">
					<el-avatar :size="40" :src="user.profile" />
					<div class="patient-info">
						<div class="name">{{ user.nickName }}</div>
						<div class="status">
							<el-icon :color="user.online ? '#67C23A' : '#909399'">
								<CircleFilled />
							</el-icon>
						</div>
					</div>
				</li>
			</ul>
		</el-col>
		<!-- 聊天内容列 -->
		<el-col :span="18" class="chat-main-col">
			<!-- 消息区域 -->
			<div class="message-area">
				<div v-for="(item, index) in state.msg"
						 :key="index"
						 :class="['message-bubble', item.senderType === 'patient' ? 'patient' : 'doctor']">
					<div class="message-header">
						<span class="sender">{{ item.senderType === 'doctor' ? '我' : state.jiaoliu.userName }}</span>
						<span class="time">{{ item.createTime }}</span>
					</div>
					<div class="message-content">{{ item.content }}</div>
				</div>
			</div>
			<el-divider />
			<div class="input-area">
				<el-input
					v-model="state.jiaoliu.content"
					type="textarea"
					:rows="4"
					placeholder="请输入医疗沟通内容"
					resize="none"
				/>
				<div class="action-bar">
					<el-button type="primary" @click="sendMessage">发送</el-button>
				</div>
			</div>
		</el-col>
	</el-row>
</template>

<script setup lang="ts">
import { reactive, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
// 获取当前登录的医生用户信息
const user = userStore().doctorUserInfo;

const state = reactive({
	jiaoliu: {
		userName: "",
		userId: null,
		doctorsId: user.id,
		content: "",
		senderType: "doctor",
		type: 0,
		score: 'A'
	},
	query: {
		doctorsId: user.id.toString()
	},
	userList: [] as any[],
	msg: [] as any[],
	msgForm:{
		doctorsId: user.id,
		userId:""
	}
});

let pollingInterval: number | null = null;
// 选择用户
const selectUser = (user: any) => {
	state.jiaoliu.userId = user.id;
	state.jiaoliu.userName = user.nickName;
	state.msgForm.userId = user.id; // 同步更新查询参数
	fetchMsgList();
};

// 发送消息（使用 async/await 方式）
const sendMessage = async () => {
	if (!state.jiaoliu.content.trim()) return;
	try {
		await frontRequest.post("/api/comment/send", state.jiaoliu);
		state.jiaoliu.content = '';
		ElMessage.success("发送成功");
		fetchMsgList();
	} catch (error) {
		console.error("发送失败", error);
		ElMessage.error("发送失败，请重试！");
	}
};

// 拉取聊天记录
const fetchMsgList = async () => {
	try {
		const response = await frontRequest.get("/api/comment/listmsg", {
			params: state.msgForm
		});
		state.msg = response.data;
		// 若消息不为空，则更新当前会话的 userId（防止数据不一致）
		if (state.msg.length > 0) {
			state.jiaoliu.userId = state.msg[0].userId;
		}
	} catch (error) {
		console.error("获取消息失败", error);
	}
};

// 初始化：获取用户列表和当前会话消息
const init = async () => {
	try {
		const response = await frontRequest.get("/api/comment/listUser", {
			params: state.query
		});
		state.userList = response.data;
		if (state.userList.length > 0) {
			const firstUser = state.userList[0];
			state.jiaoliu.userId = firstUser.id; // 假设接口返回的是 id 字段
			state.jiaoliu.userName = firstUser.nickName;
			state.msgForm.userId = firstUser.id; // 保持参数一致
			await fetchMsgList();
		}
	} catch (error) {
		console.error("获取用户列表失败", error);
	}
};

// 轮询获取最新消息（例如每 5 秒刷新一次）
const startPolling = () => {
	pollingInterval = window.setInterval(() => {
		// 只有当有选中的用户时，才进行消息刷新
		if (state.jiaoliu.userId) {
			fetchMsgList();
		}
	}, 5000);
};

onMounted(async () => {
	await init();
	startPolling();
});

onBeforeUnmount(() => {
	if (pollingInterval) {
		clearInterval(pollingInterval);
	}
});
</script>

<style scoped lang="scss">
.chat-container {
	height: calc(100vh - 120px);
	background: #f5f7fa;

	.patient-list-col {
		background: #fff;
		border-right: 1px solid #ebeef5;

		.patient-list-header {
			padding: 16px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1px solid #ebeef5;
		}

		.patient-list {
			height: calc(100vh - 180px);
			overflow-y: auto;

			.patient-item {
				display: flex;
				align-items: center;
				padding: 12px 16px;
				cursor: pointer;
				transition: background 0.3s;

				&:hover {
					background: #f5f7fa;
				}

				&.active {
					background: #e8f4ff;
				}

				.patient-info {
					margin-left: 12px;

					.name {
						font-weight: 500;
						color: #303133;
					}

					.status {
						font-size: 12px;
						color: #909399;
						display: flex;
						align-items: center;

						.el-icon {
							margin-right: 4px;
						}
					}
				}
			}
		}
	}

	.chat-main-col {
		display: flex;
		flex-direction: column;

		.message-area {
			flex: 1;
			padding: 20px;
			overflow-y: auto;
			background: #f0f2f5;

			.message-bubble {
				max-width: 70%;
				margin-bottom: 16px;
				padding: 12px 16px;
				border-radius: 8px;
				position: relative;

				&.doctor {
					background: #409eff;
					color: white;
					margin-left: auto;

					.message-header {
						color: rgba(255, 255, 255, 0.8);
					}
				}

				&.patient {
					background: white;
					border: 1px solid #ebeef5;
				}

				.message-header {
					font-size: 12px;
					margin-bottom: 6px;
					display: flex;
					justify-content: space-between;
					color: #909399;
				}

				.message-content {
					line-height: 1.5;
					white-space: pre-wrap;
				}
			}
		}

		.input-area {
			border-top: 1px solid #ebeef5;
			padding: 16px;
			background: white;

			.action-bar {
				margin-top: 12px;
				display: flex;
				justify-content: flex-end;
			}
		}
	}
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
	width: 6px;
	height: 6px;
}

::-webkit-scrollbar-thumb {
	background-color: rgba(144, 147, 153, 0.3);
	border-radius: 3px;
}
</style>

<route lang="json">
{
"meta": {
"layout": "doctor"
}
}
</route>
