<template>
	<view>
		<view class="notice">
			<up-notice-bar text="为了您的交易安全和售后保障，请您务必在平台内完成交易！" icon=""></up-notice-bar>
		</view>
		<view class="container" :style="pageHeight">
			<view class="box-1">
				<scroll-view scroll-y refresher-background="transparent" style="height: 100%;"
					@refresherrefresh="refresherrefresh" :refresher-enabled="true" :scroll-with-animation="false"
					:refresher-triggered="scrollView.refresherTriggered" :scroll-into-view="scrollView.intoView">
					<view class="talk-list">
						<view v-for="(item, index) in talkList" :key="item.msgSendTime" :id="'msg-' + item.msgSendTime">
							<view v-if="showTimeLabel(item, index)" class="time-label"> {{ showTimeLabel(item, index) }}</view>
							<view class="item flex-col" :class="item.senderId == this.userId ? 'push' : 'pull'">
								<!-- <image :src="item.pic" mode="aspectFill" class="pic"></image> -->
								<img v-if="item.senderId !== this.userId"
									:src="orderInfo.conversationAvatar || '/static/serverImg/mine/user.png'" alt=""
									class="pic" mode="aspectFill" />
								<img src="/static/serverImg/mine/user.png" alt="" class="pic" mode="aspectFill"
									v-else />
								<view class="content">
									<template v-if="item.msgType === '2'">
										<image :src="item.msgContent" mode="widthFix" style="width: 400rpx;"></image>
									</template>
									<template v-else>
										{{ item.msgContent }}
									</template>
								</view>
							</view>
						</view>

					</view>
				</scroll-view>
			</view>
			<view class="box-2">
				<view class="flex-col">
					<view style="margin-right: 20rpx;">
						<uni-icons type="image" size="24" color="#42b983" @tap="handleImageClick"></uni-icons>
					</view>
					<view class="flex-grow">
						<input type="text" class="content" v-model="content" placeholder="请输入聊天内容"
							placeholder-style="color:#DDD;" :cursor-spacing="6">
					</view>
					<button class="send" @tap="handleSendClick">发送</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { wxUploadFile, wxMakePhoneCall } from '@/utils/wxRequest.js'
import { sendMsg, getOrderConversationInfo, getListConversationInfo, setRead, getHistoryMsg,getHelpConversation } from '@/api/conversation.js';
import { onMounted } from "vue";
import dayjs from 'dayjs/esm/index'
import store from "@/store";
import { handleTime } from '../../request/dateTime';
export default {
	data() {
		return {
			// 滚动容器
			scrollView: {
				refresherTriggered: false,
				intoView: "",
				safeAreaHeight: 0
			},
			// 聊天列表数据
			talkList: [],
			// 请求参数
			ajax: {
				rows: 20,	//每页数量
				page: 1,	//页码
				flag: true,	// 请求开关
			},
			// 发送内容
			content: '',
			orderId: '',
			orderInfo: {},//订单信息
			userType: uni.getStorageSync('userType'), //读取本地存储
			system: '2',
			userId: uni.getStorageSync('userId'), //读取本地存储
			conversationRecordId: null,//会话id
			storeUser: store.state.user,
			store: store,
			isKg:false,
			conversationType:'2'
		}
	},
	computed: {
		// 页面高度
		pageHeight() {
			const safeAreaHeight = this.scrollView.safeAreaHeight;
			console.log('safeAreaHeight', safeAreaHeight);

			if (safeAreaHeight > 0) {
				return `height: calc(${safeAreaHeight}px - var(--window-top));`
			}
			return "";
		}
	},
	onLoad(options) {
		console.log("TCL: onLoad -> options", options)
		this.conversationType = options.conversationType;
		if (options.orderId) {
			this.orderId = options.orderId;

		}
		if (options.conversationRecordId) {
			this.conversationRecordId = options.conversationRecordId;
		}
	
		//1用户2志愿者3后台
		this.system = this.userType === 1 ? '1' : '2';
		//客服
		if(options.customerService){
			// this.system = 3;
			this.isKg = true;
		}
		
		// #ifdef H5
		this.scrollView.safeAreaHeight = uni.getSystemInfoSync().safeArea.height;
		// #endif


		this.getMessage();



	},
	onMounted() {
		// uni.onSocketMessage(function (parmas) {
		// 	const res = JSON.parse(parmas.data);
		// 	console.log("TCL: get -> res", res)
		// 	if (res.type === 'msgNew') {
		// 		this.talkList.unshift({ ...res.data, code: 200 });
		// 	}

		// 	console.log(' onMounted-收到服务器消息:', res, this.talkList);


		// });


	},
	methods: {
		// 下拉刷新
		refresherrefresh(e) {
			console.log("TCL: 下拉刷新 -> e", e)
			this.scrollView.refresherTriggered = true;
			// this.getMessage();
			const conversationMsgRecordId = this.talkList[this.talkList.length - 1].conversationMsgRecordId;
			console.log("TCL: refresherrefresh -> conversationMsgRecordId", conversationMsgRecordId, this.talkList[this.talkList.length - 1])
			const msgSendTime = this.talkList[this.talkList.length - 1].msgSendTime
			getHistoryMsg({ conversationMsgRecordId, conversationRecordId: this.conversationRecordId }).then(res => {
				console.log("TCL: refresherrefresh -> res", res)
				if (res.code === 200) {
					if (res.data.length === 0) {
						uni.showToast({
							title: '没有更多消息了',
							icon: 'none'
						})
						this.scrollView.refresherTriggered = false;
						return
					}
					this.talkList = [...this.talkList, ...res.data];
					this.scrollView.refresherTriggered = false;
					this.scrollView.intoView = `msg-${msgSendTime}`;
				}
			})
		},
		listsMessage() {
			console.log('-----listsMessage---->', this.storeUser, this.storeUser.wsManager);

			this.storeUser.wsManager.onMessage(res => {
				console.log('--------->', res)
				// 处理消息逻辑
				if (res.type === 'msgNew') {
					this.talkList.unshift({ ...res.data, code: 200 });
				}
			});

		},
		// 获取历史消息
		getMessage() {
			if (!this.ajax.flag) {
				return;
			}

			console.log('--------->', this.storeUser);
			if (!this.storeUser.wsManager) {
				store.dispatch('GetInfo').then((res) => {
					this.listsMessage();
				});
			} else {
				this.listsMessage();
			}

			// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
			let get = async () => {
				this.ajax.flag = false;

				const parmas = {
					system: this.system
				}
				const apiFun = this.orderId ? getOrderConversationInfo : (this.isKg?getHelpConversation:getListConversationInfo)
				if (this.orderId) {
					parmas.mainOrderId = this.orderId
				}
				if (this.conversationRecordId) {
					parmas.conversationRecordId = this.conversationRecordId
				}

				
				const res = await apiFun(parmas);
				console.log("TCL: getOrder -> res", res)
				await setRead({...parmas,conversationRecordId: res.data.conversationRecordId}); //设置已读
				if (res.code === 200) {
					const data = res.data.vos;
					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用。取当前消息数据的第一条信息元素
					const selector = `msg-${data?.[0]?.msgSendTime}`;
					// uni.setNavigationBarTitle({
					// 		title: userType === 1? res.data. :  // 根据业务逻辑调整 
					// 	});
					// 将获取到的消息数据合并到消息数组中
					this.talkList = data;
					console.log("TCL: getOrder -> talkList", this.talkList)
					this.orderInfo = res.data;

					// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.scrollView.intoView = selector;
						if (data.length < this.ajax.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.ajax.flag = true;
							this.ajax.page++;
						}
					})
				}


			}
			get();
		},
		// 发送信息
		handleSendClick() {
			if (!this.content) {
				uni.showToast({
					title: '请输入有效的内容',
					icon: 'none'
				})
				return;
			}
			this.sendMessage(this.content, 'text');

			// 清空内容框中的内容
			this.content = '';
		},
		// 处理图片点击
		async handleImageClick() {
			const res = await wxUploadFile('img');
			this.sendMessage(res[0].url, 'image');
			console.log("TCL: handleImageClick -> res", res)
		},
		async sendMessage(content, contentType = 'text') {
			// 将当前发送信息 添加到消息列表。
			let data = {
				conversationRecordId: "3",
				msgContent: content,
				msgSendTime: new Date().getTime(),
				senderId: this.userId,
				msgType: contentType == 'text' ? '1' : '2',//消息类型 1文字消息 2图片消息
			}
			console.log('发送消息',this.conversationType);
			
			const res = await sendMsg({
				...this.orderInfo,
				msgContent: content,
				system: this.system,
				msgType: data.msgType,
				conversationType: this.conversationType
			});
			this.talkList.unshift({ ...data, code: res.code });
			this.scrollView.intoView = `msg-${data.msgSendTime}`;
		},
		showTimeLabel(item, index) {
			const { talkList } = this;
			const isLastItem = index === talkList.length - 1;

			// 最后一条消息，强制显示时间
			if (isLastItem) {
				return handleTime(item.msgSendTime);
			}

			const nextItem = talkList[index + 1];

			// 如果没有下一条，不显示
			if (!nextItem) {
				return null;
			}

			const diffInMinutes = dayjs(nextItem.msgSendTime).diff(dayjs(item.msgSendTime), 'minute');
			
			// 如果下一条消息与当前消息间隔 >= 30 分钟，则由下一条显示时间
			if (Math.abs(diffInMinutes) >= 30) {
				return handleTime(item.msgSendTime);
			}

			return null;
		}

	},

}
</script>

<style lang="scss">
@import "../../lib/global.scss";

page {
	background-color: #F3F3F3;
	font-size: 28rpx;
}

.notice {
	height: 40px;
}

.container {
	height: calc(100vh - var(--window-top) - 40px);
	display: flex;
	flex-direction: column;
	flex-wrap: nowrap;
	align-content: center;
	justify-content: space-between;
	align-items: stretch;
}

/* 加载数据提示 */
.tips {
	position: fixed;
	left: 0;
	top: var(--window-top);
	width: 100%;
	z-index: 9;
	background-color: rgba(0, 0, 0, 0.15);
	height: 72rpx;
	line-height: 72rpx;
	transform: translateY(-80rpx);
	transition: transform 0.3s ease-in-out 0s;

	&.show {
		transform: translateY(0);
	}
}

.box-1 {
	width: 100%;
	height: 0;
	flex: 1 0 auto;
	box-sizing: content-box;
}

.box-2 {
	height: auto;
	z-index: 2;
	border-top: #e5e5e5 solid 1px;
	box-sizing: content-box;
	background-color: #F3F3F3;

	/* 兼容iPhoneX */
	padding-bottom: 0;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);

	>view {
		padding: 0 20rpx;
		height: 100rpx;
	}

	.content {
		background-color: #fff;
		height: 64rpx;
		padding: 0 20rpx;
		border-radius: 32rpx;
		font-size: 28rpx;
	}

	.send {
		background-color: #42b983;
		color: #fff;
		height: 64rpx;
		margin-left: 20rpx;
		border-radius: 32rpx;
		padding: 0;
		width: 120rpx;
		line-height: 62rpx;

		&:active {
			background-color: #5fc496;
		}
	}
}

.talk-list {
	padding-bottom: 20rpx;
	display: flex;
	flex-direction: column-reverse;
	flex-wrap: nowrap;
	align-content: flex-start;
	justify-content: flex-end;
	align-items: stretch;

	// 添加弹性容器，让内容自动在顶部
	&::before {
		content: '.';
		display: inline;
		visibility: hidden;
		line-height: 0;
		font-size: 0;
		flex: 1 0 auto;
		height: 1px;
	}


	/* 消息项，基础类 */
	.item {
		padding: 20rpx 20rpx 0 20rpx;
		align-items: flex-start;
		align-content: flex-start;
		color: #333;

		.pic {
			width: 92rpx;
			height: 92rpx;
			border-radius: 50%;
			border: #fff solid 1px;
		}

		.content {
			padding: 20rpx;
			border-radius: 4px;
			max-width: 500rpx;
			word-break: break-all;
			line-height: 52rpx;
			position: relative;
		}

		/* 收到的消息 */
		&.pull {
			.content {
				margin-left: 32rpx;
				background-color: #fff;

				&::after {
					content: '';
					display: block;
					width: 0;
					height: 0;
					border-top: 16rpx solid transparent;
					border-bottom: 16rpx solid transparent;
					border-right: 20rpx solid #fff;
					position: absolute;
					top: 30rpx;
					left: -18rpx;
				}
			}
		}

		/* 发出的消息 */
		&.push {
			/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
			flex-direction: row-reverse;

			.content {
				margin-right: 32rpx;
				background-color: #a0e959;

				&::after {
					content: '';
					display: block;
					width: 0;
					height: 0;
					border-top: 16rpx solid transparent;
					border-bottom: 16rpx solid transparent;
					border-left: 20rpx solid #a0e959;
					position: absolute;
					top: 30rpx;
					right: -18rpx;
				}
			}
		}
	}
}

.time-label {
	text-align: center;
	margin-top: 16rpx;
}
</style>