<template>
	<view scroll-y class="container chat-history-container">
		<!-- 自定义导航栏 -->
		<CustomNavbar
			title="聊天记录"
			type="center"
			:isLeft="true"
			bgColor="#94f2f1"
			@handleLeft="handleLeft"
		/>
		<!-- 聊天内容区域 -->
		<scroll-view
			scroll-y
			class="chat-content"
			:scrollTop="scrollTop"
			@scroll="viewScroll"
			id="chatListContainer"
			v-show="isShowChatList"
			@scrolltolower="handleScroll"
		>
			<!-- 替换为实际条件 -->
			<!-- 聊天记录列表 -->
			<view class="chat-list pd-32" :style="{ 'padding-top': '300rpx' }">
				<!-- 时间显示 -->
				<view v-for="(item, index) in chatList" :key="index" class="chat-item">
					<view class="time" v-if="index % 5 == 0 && item.role=='user'" >
						<text
							>{{ formatTimestamp(item.created) }}</text>
					</view>
					<!-- 本人（助手）消息 -->
					<view class="user" v-if="item.role === 'assistant'">
						<view class="user-content">
							<view class="flex-c right-box">
								<text class="f-colot-848D99 title-14-400">我</text>
								<text class="right">{{ item.msg }}</text>
								<view class="tool">
									<view @click="openTuningPopup(item.mid, item.tuningText)">
										<CustomIcon iconName="bianjipingjia" size="36rpx" />调优
									</view>
									<view @click="handleUpdateScorce('add', item.mid)">
										<CustomIcon
											iconName="thumb-up"
											size="36rpx"
											:color="item.score == 1 ? '#e6d5a9' : '#4E5969'"
										/>
									</view>
									<view @click="handleUpdateScorce('minus', item.mid)">
										<CustomIcon
											iconName="thumb-down"
											size="36rpx"
											:color="item.score == -1 ? '#e6d5a9' : '#4E5969'"
										/>
									</view>
								</view>
								<view class="after" v-if="item.tuningText">
									{{ item.tuningText }}
								</view>
							</view>
							<image
								src="https://ywt-image.oss-cn-shenzhen.aliyuncs.com/doctor/avatar/default.png"
								mode="aspectFill"
							/>
						</view>
					</view>
					<!-- 患者消息 -->
					<view class="ai" v-if="item.role === 'user'">
						<view class="ai-content">
							<image
								src="@/static/images/default_avatar.png"
								mode="aspectFill"
							/>
							<view class="flex-c right-box">
								<text class="f-colot-848D99 title-14-400">王元</text>
								<text class="right">{{ item.msg }}</text>
							</view>
						</view>
					</view>
				</view>
				<CustomLoadMore
					:status="loadStatus"
					style="transform: rotate(180deg)"
				/>
			</view>
			<view
				v-if="chatList.length == 0"
				style="text-align: center; padding-top: 200rpx; color: #d6d7dc"
			>
				暂无聊天记录</view
			>
		</scroll-view>
		<uv-loading-page
			:loading="true"
			loading-mode="spinner"
			v-if="!isShowChatList"
		></uv-loading-page>
	</view>

	<!-- 弹出窗 -->
	<uv-popup ref="popup" mode="bottom" round="5">
		<view class="popup-content">
			<view class="header">
				<text @click="handlePopupCancel">取消</text>
				<text @click="handlePopupConfirm">确定</text>
			</view>
			<uv-textarea
				v-model="tungData.tuningContent"
				count
				@confirm="handlePopupConfirm"
				placeholder="请输入调优方案"
				customStyle="height: 300rpx;
					background: #F5F7FA;
					border: unset;
					border-radius: 0rpx 0rpx 0rpx 0rpx;
				"
				:focus="true"
				countStyle="background: #F5F7FA;
						font-weight: 400;
						padding: 30rpx;
						font-size: 28rpx;
						color: #86909C;"
				maxlength="50"
			></uv-textarea>
		</view>
	</uv-popup>
</template>

<script lang="ts" setup>
import { ref, inject, nextTick, onMounted } from "vue";
import aichat from "@/api/aichat";
import { onDateChange } from "@/utils/common";
import { onLoad } from "@dcloudio/uni-app";
import useUserStore from "@/store/modules/user";
// 注入的 showToast 方法，用于显示提示
const $showToast: any = inject("$showToast");
const userStore = useUserStore();
// 当前患者信息
const currentPatient = ref({});
//页面查询数据
const paramsData = ref({
	userId: 0,
	pageSize: 30,
	pageNum: 1,
	doctorId: userStore.userData.userId,
});
const loadStatus = ref("nomore");
const pageTotal = ref(0);
// 弹窗引用
const popup = ref<any>(null);
const isShowChatList = ref(false);
// 调优内容
const tungData = ref({
	tuningContent: "", //消息内容
	tuningId: "", //当前更改的tunid
	msgId: 0, //消息id
});
const scrollTop = ref(0);
// 聊天记录
const chatList = ref<any>([]);
const isScroll = ref(true);
const scrollView = ref("");
/**
 * 打开调优弹窗
 */
const openTuningPopup = (mid: number, text: string = "") => {
	tungData.value.tuningContent = text;
	tungData.value.msgId = mid;
	popup.value.open();
};

/**
 * 关闭调优弹窗，清空内容
 */
const handlePopupCancel = () => {
	popup.value.close();

	tungData.value.tuningContent = "";
};
/**
 * 关闭调优弹窗，提交内容
 */
const handlePopupConfirm = () => {
	popup.value.close();
	sendTung();
	
};
/**
 * 发起调优
 */
const sendTung = async () => {
	await aichat.tuneMsg(tungData.value);
	chatList.value = chatList.value.map((item:any)=>{
		console.log(item.mid == tungData.value.msgId);
		if(item.mid == tungData.value.msgId) {
			item.tuningText = tungData.value.tuningContent
		}
		console.log(item.mid == tungData.value.msgId,item.tuningText,tungData.value.tuningContent);
		return item
	})
	tungData.value.tuningContent = "";
	// chatList.value = [];
	// getData();
	// scrollTop.value = currentScroll
};

const handleUpdateScorce = async (flag: "add" | "minus", id: number) => {
	let score = flag == "add" ? 1 : -1;
	let params = {
		msgId: id,
		score,
	};
	await aichat.addMsgScore(params);
	$showToast("更改成功");
	chatList.value = chatList.value.map((item:any)=>{
		if(item.mid == id) {
			item.score = score
		}
		return item
	})
	// getData()
	// sr
};

/**
 * 格式化时间戳
 * @param item - 时间戳
 * @returns 格式化后的时间
 */
const formatTimestamp = (created: number) => {
	// console.log("11111111111111111",created);

	return onDateChange(created);
};
const getData = async () => {
	const {
		data: { records, total },
	} = await aichat.msgList(paramsData.value);
	// records.reverse();
	chatList.value.push(...records);
	pageTotal.value = total;
	console.log(chatList.value);

	// updatePage()
	// setTimeout(() => {
	isShowChatList.value = true;
	// },500)
};
// 更新页面滚动
const updatePage = () => {
	nextTick(() => {
		const query = uni.createSelectorQuery();
		query.select("#chatListContainer").boundingClientRect();
		query.exec((res) => {
			const chatListContainer = res[0];
			console.log("22222", res);

			if (chatListContainer) {
				scrollTop.value = chatListContainer.height;
			}
		});
	});
};
// 节流状态
let isThrottling = false;
let currentScroll = 0;
// 处理滚动事件
const handleScroll = (event: any) => {
	loadStatus.value = "loading";
	setTimeout(() => {
		goTop();
		getData();
	}, 500);
};
const goTop = () => {
	// 解决view层不同步的问题
	scrollTop.value = currentScroll;
	nextTick(() => {
		// scrollTop.value = 0;
	});
};
const isScrollTop = ref(false);

const viewScroll = (event: any) => {
		currentScroll = event.detail.scrollTop;
};
/**
 * 处理返回按钮事件
 */
const handleLeft = () => {
	uni.navigateBack({ delta: 1 });
};
onLoad((option) => {
	paramsData.value.userId = option?.userId || 30;
	getData();

	// updatePage()
});
</script>

<style lang="scss">
@import "./index.scss";
page {
	background-color: #f5f7fa;
}
	.chat-content div::-webkit-scrollbar{
		display: none;
			width: 0;
			height: 0;
			-webkit-appearance: none;
			background: transparent;
			color: transparent;
		
	}
	
	.chat-content div{
	  -ms-overflow-style: none; /* IE 10+ */
	  scrollbar-width: none; /* Firefox */
	}
</style>
