<template>
	<view class="page chat-box">
		<view class="header">
			<uni-icons class="btn-side left" type="back" size="20" @click="onNavBack()"></uni-icons>
			<text class="title">{{title}}</text>
			<!-- <uni-icons class="btn-side right" type="more-filled" size="30" @click="onShowMore()"></uni-icons> -->
		</view>
		<view class="chat-msg" @click="switchChatTabBox('none',true)">
			<scroll-view class="scroll-box" scroll-y="true" @scrolltoupper="onScrollToTop"
				:scroll-into-view="'chat-item-'+data.scrollMsgIdx">
				<view v-for="(msgInfo,idx) in data.chat.messages" :key="idx">
					<chat-message-item v-if="idx>=data.showMinIdx" :headImg="headImg(msgInfo)"
						:showName="showName(msgInfo)" @recall="onRecallMessage" @delete="onDeleteMessage"
						@longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile" :id="'chat-item-'+idx"
						:msgInfo="msgInfo">
					</chat-message-item>
				</view>
			</scroll-view>
		</view>
		<view v-if="data.atUserIds.length>0" class="chat-at-bar" @click="openAtBox()">
			<view class="iconfont icon-at">:&nbsp;</view>
			<scroll-view v-if="data.atUserIds.length>0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
				<view class="chat-at-items">
					<view v-for="m in atUserItems" class="chat-at-item">
						<head-image :name="m.aliasName" :url="m.headImage" :size="50"></head-image>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="send-bar">
			<view class="send-text">
				<textarea class="send-text-area" v-model="data.sendText" auto-height :show-confirm-bar="false"
					:adjust-position="false" @confirm="sendTextMessage()" @keyboardheightchange="onKeyboardheightchange"
					@input="onTextInput" confirm-type="send" confirm-hold :hold-keyboard="true"></textarea>
			</view>
			<!-- <view v-if="data.chat.type=='GROUP'" class="iconfont icon-at" @click="openAtBox()"></view> -->
			<view class="iconfont icon-icon_emoji" @click="switchChatTabBox('emo',true)"></view>
			<view v-if="data.sendText==''" class="iconfont icon-add" @click="switchChatTabBox('tools',true)">
			</view>
			<button v-if="data.sendText!=''||data.atUserIds.length>0" class="btn-send" type="primary"
				@touchend.prevent="sendTextMessage()" size="mini">发送</button>
		</view>

		<view class="chat-tab-bar" v-show="data.chatTabBox!='none' ||data.showKeyBoard " :style="{height:`${data.keyboardHeight}px`}">
			<view v-if="data.chatTabBox == 'tools'" class="chat-tools">
				<view class="chat-tools-item">
					<image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
						:onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
						<view class="tool-icon iconfont icon-picture"></view>
					</image-upload>
					<view class="tool-name">相册</view>
				</view>
				<view class="chat-tools-item">
					<image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
						:onError="onUploadImageFail">
						<view class="tool-icon iconfont icon-camera"></view>
					</image-upload>
					<view class="tool-name">拍摄</view>
				</view>
				<view class="chat-tools-item">
					<file-upload :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
						:onError="onUploadFileFail">
						<view class="tool-icon iconfont icon-folder"></view>
					</file-upload>
					<view class="tool-name">文件</view>
				</view>
			</view>
			<scroll-view v-if="data.chatTabBox==='emo'" class="chat-emotion" scroll-y="true">
				<view class="emotion-item-list">
					<image class="emotion-item" :title="emoText" :src="textToPath(emoText)"
						v-for="(emoText, i) in emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
						lazy-load="true"></image>
				</view>
			</scroll-view>
			<view v-if="data.showKeyBoard"></view>
		</view>
	</view>
</template>

<script setup>
	import { computed, watch, reactive, ref, nextTick } from 'vue'
	import { MESSAGE_TYPE, MESSAGE_STATUS } from '@/common/enums/im.ts';
	import { onLoad, onUnload } from '@dcloudio/uni-app';
	import { useChatStore } from "@/common/store/im/chatStore.js";
	import { useFriendStore } from '@/common/store/im/friendStore.js';
	import { useGroupStore } from '@/common/store/im/groupStore.js';
	import { useIMUserStore } from '@/common/store/im/imUserStore.js';
	import { textToPath, emoTextList} from '@/common/config/emotion.js';
	import http from '@/common/request/im.js';
	import chatMessageItem from "./chat-message-item.vue";
	import headImage from "../../components/head-image.vue";
	import imageUpload from "../../components/image-upload.vue";
	import fileUpload from "../../components/file-upload.vue";


	const friendStore = useFriendStore();
	const groupStore = useGroupStore();
	const chatStore = useChatStore();
	const imUserStore = useIMUserStore();
	const atBox = ref()
	const data = reactive({
		chat: {},
		friend: {},
		group: {},
		groupMembers: [],
		sendText: "",
		// showVoice: false, // 是否显示语音录制弹窗
		scrollMsgIdx: 0, // 滚动条定位为到哪条消息
		chatTabBox: 'none',
		showKeyBoard: false,
		keyboardHeight: 100,
		atUserIds: [],
		showMinIdx: 0 // 下标小于showMinIdx的消息不显示，否则可能很卡
	})
	function openAtBox() {
		atBox.value.init(data.atUserIds);
		atBox.value.open();
	}
	function onLongPressHead(msgInfo) {
		if (!msgInfo.selfSend && data.chat.type == "GROUP" && data.atUserIds.indexOf(msgInfo.sendId) < 0) {
			data.atUserIds.push(msgInfo.sendId);
		}
	}
	function headImg(msgInfo) {
		if (data.chat.type == 'GROUP') {
			let member = data.groupMembers.find((m) => m.userId == msgInfo.sendId);
			return member ? member.headImage : "";
		} else {
			return msgInfo.selfSend ? mine.value.headImageThumb : data.chat.headImage
		}
	}
	function showName(msgInfo) {
		if (data.chat.type == 'GROUP') {
			let member = data.groupMembers.find((m) => m.userId == msgInfo.sendId);
			return member ? member.aliasName : "";
		} else {
			return msgInfo.selfSend ? mine.value.nickName : data.chat.showName
		}
	}
	function sendTextMessage() {
		if (!data.sendText.trim() && data.atUserIds.length == 0) {
			return uni.showToast({
				title: "不能发送空白信息",
				icon: "none"
			});

		}
		let atText = createAtText()
		let msgInfo = {
			content: data.sendText + atText,
			atUserIds: data.atUserIds,
			type: 0
		}
		// 填充对方id
		fillTargetId(msgInfo, data.chat.targetId);
		data.sendText = "";
		http({
			url: messageAction.value,
			method: 'POST',
			data: msgInfo
		}).then((id) => {
			msgInfo.id = id;
			msgInfo.sendTime = new Date().getTime();
			msgInfo.sendId = imUserStore.userInfo.id;
			msgInfo.selfSend = true;
			msgInfo.status = MESSAGE_STATUS.UNSEND;
			chatStore.insertMessage(msgInfo);
			data.sendText = "";
		}).finally(() => {
			// 滚动到底部
			scrollToBottom();
			// 清空@用户列表
			data.atUserIds = [];
		});
	}
	function createAtText() {
		let atText = "";
		data.atUserIds.forEach((id) => {
			if (id == -1) {
				atText += ` @全体成员`;
			} else {
				let member = data.groupMembers.find((m) => m.userId == id);
				if (member) {
					atText += ` @${member.aliasName}`;
				}
			}
		})
		return atText;
	}
	function fillTargetId(msgInfo, targetId) {
		if (data.chat.type == "GROUP") {
			msgInfo.groupId = targetId;
		} else {
			msgInfo.recvId = targetId;
		}
	}
	function scrollToBottom() {
		let size = data.chat.messages.length;
		if (size > 0) {
			scrollToMsgIdx(size - 1);
		}
	}
	function scrollToMsgIdx(idx) {
		// 如果scrollMsgIdx值没变化，滚动条不会移动
		if (idx == data.scrollMsgIdx && idx > 0) {
			nextTick(() => {
				// 先滚动到上一条
				data.scrollMsgIdx = idx - 1;
				// 再滚动目标位置
				scrollToMsgIdx(idx);
			});
			return;
		}
		nextTick(() => {
			data.scrollMsgIdx = idx;
		});

	}
	function switchChatTabBox(chatTabBox, hideKeyBoard) {
		data.chatTabBox = chatTabBox;
		if (hideKeyBoard) {
			uni.hideKeyboard();
		}
	}
	function selectEmoji(emoText) {
		data.sendText += `#${emoText};`;
	}
	function onNavBack() {
		uni.reLaunch({
			url: "/pages/msg/im/chat/chat"
		})
	}
	function onKeyboardheightchange(e) {
		if (e.detail.height > 0) {
			data.showKeyBoard = true;
			switchChatTabBox('none', false)
			data.keyboardHeight = rpxTopx(e.detail.height);
		} else {
			data.showKeyBoard = false;
		}
	}
	function onUploadImageBefore(file) {
		let info = {
			originUrl: file.path,
			thumbUrl: file.path
		}
		let msgInfo = {
			id: 0,
			fileId: file.uid,
			sendId: mine.value.id,
			content: JSON.stringify(info),
			sendTime: new Date().getTime(),
			selfSend: true,
			type: MESSAGE_TYPE.IMAGE,
			loadStatus: "loading",
			status: MESSAGE_STATUS.UNSEND
		}
		// 填充对方id
		fillTargetId(msgInfo, data.chat.targetId);
		// 插入消息
		chatStore.insertMessage(msgInfo);
		// 借助file对象保存
		file.msgInfo = msgInfo;
		// 滚到最低部
		scrollToBottom();
		return true;
	}
	function onUploadImageSuccess(file, res) {
		let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
		msgInfo.content = JSON.stringify(res.data);
		http({
			url: messageAction.value,
			method: 'POST',
			data: msgInfo
		}).then((id) => {
			msgInfo.loadStatus = 'ok';
			msgInfo.id = id;
			chatStore.insertMessage(msgInfo);
		})
	}
	function onUploadImageFail(file, err) {
		let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
		msgInfo.loadStatus = 'fail';
		chatStore.insertMessage(msgInfo);
	}
	function onUploadFileBefore(file) {
		let info = {
			name: file.name,
			size: file.size,
			url: file.path
		}
		let msgInfo = {
			id: 0,
			sendId: mine.value.id,
			content: JSON.stringify(info),
			sendTime: new Date().getTime(),
			selfSend: true,
			type: MESSAGE_TYPE.FILE,
			loadStatus: "loading",
			status: MESSAGE_STATUS.UNSEND
		}
		// 填充对方id
		fillTargetId(msgInfo, data.chat.targetId);
		// 插入消息
		chatStore.insertMessage(msgInfo);
		// 借助file对象保存
		file.msgInfo = msgInfo;
		// 滚到最低部
		scrollToBottom();
		return true;
	}
	function onUploadFileSuccess(file, res) {
		let data = {
			name: file.name,
			size: file.size,
			url: res.data
		}
		let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
		msgInfo.content = JSON.stringify(data);
		http({
			url: messageAction.value,
			method: 'POST',
			data: msgInfo
		}).then((id) => {
			msgInfo.loadStatus = 'ok';
			msgInfo.id = id;
			chatStore.insertMessage(msgInfo);
		})
	}
	function onUploadFileFail(file, res) {
		let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
		msgInfo.loadStatus = 'fail';
		chatStore.insertMessage(msgInfo);
	}
	function onDeleteMessage(msgInfo) {
		uni.showModal({
			title: '删除消息',
			content: '确认删除消息?',
			success: (res) => {
				if (!res.cancel) {
					chatStore.deleteMessage(msgInfo);
					uni.showToast({
						title: "删除成功",
						icon: "none"
					})
				}
			}
		})
	}
	function onRecallMessage(msgInfo) {
		uni.showModal({
			title: '撤回消息',
			content: '确认撤回消息?',
			success: (res) => {
				if (!res.cancel) {
					let url = `/message/${data.chat.type.toLowerCase()}/recall/${msgInfo.id}`
					http({
						url: url,
						method: 'DELETE'
					}).then(() => {
						msgInfo = JSON.parse(JSON.stringify(msgInfo));
						msgInfo.type = MESSAGE_TYPE.RECALL;
						msgInfo.content = '你撤回了一条消息';
						msgInfo.status = MESSAGE_STATUS.RECALL;
						chatStore.insertMessage(msgInfo);
					})
				}
			}
		})
	}
	function onDownloadFile(msgInfo) {
		let url = JSON.parse(msgInfo.content).url;
		uni.downloadFile({
			url: url,
			success(res) {
				if (res.statusCode === 200) {
					var filePath = encodeURI(res.tempFilePath);
					uni.openDocument({
						filePath: filePath,
						showMenu: true
					});
				}
			},
			fail(e) {
				console.log(e);
				uni.showToast({
					title: "文件下载失败",
					icon: "none"
				})
			}
		});
	}
	function onScrollToTop() {
		// #ifdef MP
		// 防止滚动条定格在顶部，不能一直往上滚
		scrollToMsgIdx(data.showMinIdx);
		// #endif

		// 多展示10条信息
		data.showMinIdx = data.showMinIdx > 10 ? data.showMinIdx - 10 : 0;
	}
	function onTextInput(e) {
		let idx = e.detail.cursor - 1;
		if (data.chat.type == 'GROUP' && e.detail.value[idx] == '@') {
			openAtBox();
			let sendText = e.detail.value.replace("@", '');
			nextTick(() => {
				data.sendText = sendText;
			})
		}
	}
	function loadReaded(fId) {
		http({
			url: `/message/private/maxReadedId?friendId=${fId}`,
			method: 'get'
		}).then((id) => {
			chatStore.readedMessage({
				friendId: fId,
				maxId: id
			});
		});
	}
	function readedMessage() {
		if (data.chat.type == "GROUP") {
			var url = `/message/group/readed?groupId=${data.chat.targetId}`
		} else {
			url = `/message/private/readed?friendId=${data.chat.targetId}`
		}
		http({
			url: url,
			method: 'PUT'
		}).then(() => {
			chatStore.resetUnreadCount(data.chat)
			scrollToBottom();
		})
	}
	function loadGroup(groupId) {
		http({
			url: `/group/find/${groupId}`,
			method: 'GET'
		}).then((group) => {
			data.group = group;
			chatStore.updateChatFromGroup(group);
			groupStore.updateGroup(group);

		});

		http({
			url: `/group/members/${groupId}`,
			method: 'get'
		}).then((groupMembers) => {
			data.groupMembers = groupMembers;
		});
	}
	function loadFriend(friendId) {
		// 获取对方最新信息
		http({
			url: `/user/find/${friendId}`,
			method: 'GET'
		}).then((friend) => {
			data.friend = friend;
			chatStore.updateChatFromFriend(friend);
			friendStore.updateFriend(friend);
		})
	}
	function rpxTopx(rpx) {
		// px转换成rpx
		let info = uni.getSystemInfoSync()
		let px = info.windowWidth * rpx / 750;
		return Math.floor(rpx);
	}
	const mine = computed(()=> {
		return imUserStore.userInfo;
	})
	const title = computed(()=> {
		if (!data.chat) {
			return "";
		}
		let title = data.chat.showName;
		if (data.chat.type == "GROUP") {
			let size = data.groupMembers.filter(m => !m.quit).length;
			title += `(${size})`;
		}
		return title;
	})
	const messageAction = computed(()=> {
		return `/message/${data.chat.type.toLowerCase()}/send`;
	})
	const messageSize = computed(()=> {
		if (!data.chat || !data.chat.messages) {
			return 0;
		}
		return data.chat.messages.length;
	})
	const unreadCount = computed(()=> {
		return data.chat.unreadCount;
	})
	const atUserItems = computed(()=> {
		let atUsers = [];
		data.atUserIds.forEach((id) => {
			if (id == -1) {
				atUsers.push({
					id: -1,
					aliasName: "全体成员"
				})
				return;
			}
			let member = data.groupMembers.find((m) => m.userId == id);
			if (member) {
				atUsers.push(member);
			}
		})
		return atUsers;
	})
	watch(() => messageSize.value, (newSize, oldSize) => {
		if (newSize > oldSize) {
			scrollToBottom();
		}
	})
	watch(() => unreadCount.value, (newCount, oldCount) => {
		if (newCount > 0) {
			// 消息已读
			readedMessage()
		}
	})
			
	onLoad((options)=> {
		// 聊天数据
		data.chat = chatStore.chats[options.chatIdx];
		// 初始状态只显示30条消息
		let size = data.chat.messages.length;
		data.showMinIdx = size > 30 ? size - 30 : 0;
		// 激活当前会话
		chatStore.activeChat(options.chatIdx);
		// 页面滚到底部
		scrollToBottom();
		// 消息已读
		readedMessage()
		// 加载好友或群聊信息
		if (data.chat.type == "GROUP") {
			loadGroup(data.chat.targetId);
		} else {
			loadFriend(data.chat.targetId);
			loadReaded(data.chat.targetId)
		}
	})
	onUnload(()=> {
		chatStore.activeChat(-1);
	})
</script>

<style lang="scss" scoped>
	.chat-box {
		position: relative;
		border: #dddddd solid 1px;
		display: flex;
		flex-direction: column;
		height: 100%;

		.header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 60rpx;
			padding: 10px;
			background-color: white;
			line-height: 50px;
			font-size: 35rpx;
			font-weight: 600;
			border-bottom: #eee solid 1px;


			.btn-side {
				position: absolute;
				line-height: 60rpx;
				font-size: 28rpx;
				cursor: pointer;

				&.left {
					left: 30rpx;
				}

				&.right {
					right: 30rpx;
				}
			}
		}


		.chat-msg {
			flex: 1;
			padding: 0;
			border: #dddddd solid 1px;
			overflow: hidden;
			position: relative;
			background-color: #f4f6f8;

			.scroll-box {
				height: 100%;
			}
		}

		.chat-at-bar {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			border: #dddddd solid 1px;

			.icon-at {
				font-size: 35rpx;
				color: darkblue;
				font-weight: 600;
			}

			.chat-at-scroll-box {
				flex: 1;
				width: 80%;

				.chat-at-items {
					display: flex;
					align-items: center;
					height: 70rpx;

					.chat-at-item {
						padding: 0 3rpx;
					}
				}
			}

		}

		.send-bar {
			display: flex;
			align-items: center;
			padding: 20rpx;
			background-color: white;
			border-bottom: 1px solid #eee ;
			.iconfont {
				font-size: 60rpx;
				margin-left: 10rpx;
			}

			.send-text {
				flex: 1;
				background-color: #ebeef0;
				overflow: auto;
				padding: 20rpx;
				border-radius: 25rpx;
				max-height: 300rpx;
				min-height: 85rpx;
				font-size: 30rpx;
				box-sizing: border-box;

				.send-text-area {
					width: 100%;
				}
			}

			.btn-send {
				margin: 5rpx;
			}
		}


		.chat-tab-bar {
			height: 500rpx;
			background-color: #fff;

			.chat-tools {
				display: flex;
				flex-wrap: wrap;

				.chat-tools-item {
					width: 140rpx;
					padding: 15rpx;
					display: flex;
					flex-direction: column;
					align-items: center;

					.tool-icon {
						padding: 20rpx;
						font-size: 70rpx;
						background-color: #ebeef0;
						border-radius: 20%;
						color: #243853;
					}

					.tool-name {
						height: 60rpx;
						line-height: 60rpx;
						font-size: 25rpx;
						color: #9399a5;
					}
				}
			}

			.chat-emotion {
				height: 100%;

				.emotion-item-list {
					display: flex;
					flex-wrap: wrap;

					.emotion-item {
						width: 40px;
						height: 40px;
						text-align: center;
						cursor: pointer;
						padding: 6px;
					}
				}
			}

		}
	}
</style>