import {
	MESSAGE_TYPE,
	MESSAGE_STATUS
} from '@/common/enums/im.ts';
import { useIMUserStore } from './imUserStore';
import {
	defineStore
} from 'pinia';

export const useChatStore = defineStore('chat', {
	state: () => {
		return {
			activeIndex: -1,
			chats: [],
			privateMsgMaxId: 0,
			groupMsgMaxId: 0,
			loadingPrivateMsg: false,
			loadingGroupMsg: false,
		}
	},
	actions: {
		initChats(chatsData) {
			this.chats = chatsData.chats || [];
			this.privateMsgMaxId = chatsData.privateMsgMaxId || 0;
			this.groupMsgMaxId = chatsData.groupMsgMaxId || 0;
			// 防止图片一直处在加载中状态
			this.chats.forEach((chat) => {
				chat.messages.forEach((msg) => {
					if (msg.loadStatus == "loading") {
						msg.loadStatus = "fail"
					}
				})
			})
		},
		openChat(chatInfo) {
			let chat = null;
			for (let idx in this.chats) {
				if (this.chats[idx].type == chatInfo.type &&
					this.chats[idx].targetId === chatInfo.targetId) {
					chat = this.chats[idx];
					// 放置头部
					this.moveTop(idx)
					break;
				}
			}
			// 创建会话
			if (chat == null) {
				chat = {
					targetId: chatInfo.targetId,
					type: chatInfo.type,
					showName: chatInfo.showName,
					headImage: chatInfo.headImage,
					lastContent: "",
					lastSendTime: new Date().getTime(),
					unreadCount: 0,
					messages: [],
					atMe: false,
					atAll: false
				};
				this.chats.unshift(chat);
			}
			this.saveToStorage();
		},
		activeChat(idx) {
			this.activeIndex = idx;
			if (idx >= 0) {
				this.chats[idx].unreadCount = 0;
			}
		},
		resetUnreadCount(chatInfo) {
			for (let idx in this.chats) {
				if (this.chats[idx].type == chatInfo.type &&
					this.chats[idx].targetId == chatInfo.targetId) {
					this.chats[idx].unreadCount = 0;
					this.chats[idx].atMe = false;
					this.chats[idx].atAll = false;
				}
			}
			this.saveToStorage();
		},
		readedMessage(pos) {
			for (let idx in this.chats) {
				if (this.chats[idx].type == 'PRIVATE' &&
					this.chats[idx].targetId == pos.friendId) {
					this.chats[idx].messages.forEach((m) => {
						if (m.selfSend && m.status != MESSAGE_STATUS.RECALL) {
							// pos.maxId为空表示整个会话已读
							if (!pos.maxId || m.id <= pos.maxId) {
								m.status = MESSAGE_STATUS.READED
							}

						}
					})
				}
			}
			this.saveToStorage();
		},
		removeChat(idx) {
			this.chats.splice(idx, 1);
			this.saveToStorage();
		},
		removeGroupChat(groupId) {
			for (let idx in this.chats) {
				if (this.chats[idx].type == 'GROUP' &&
					this.chats[idx].targetId == groupId) {
					this.removeChat(idx);
				}
			}
		},
		removePrivateChat(userId) {
			for (let idx in this.chats) {
				if (this.chats[idx].type == 'PRIVATE' &&
					this.chats[idx].targetId == userId) {
					this.removeChat(idx);
				}
			}
		},
		moveTop(idx) {
			// 加载中不移动，很耗性能
			if (this.loadingPrivateMsg || this.loadingGroupMsg) {
				return;
			}
			if (idx > 0) {
				let chat = this.chats[idx];
				this.chats.splice(idx, 1);
				this.chats.unshift(chat);
				this.saveToStorage();
			}
		},
		insertMessage(msgInfo) {
			// 获取对方id或群id
			let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
			let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
			let chat = null;

			for (let idx in this.chats) {
				if (this.chats[idx].type == type &&
					this.chats[idx].targetId == targetId) {
					chat = this.chats[idx];
					this.moveTop(idx)
					break;
				}
			}
			if (!chat) return

			// 会话列表内容
			if (!this.loadingPrivateMsg && !this.loadingPrivateMsg) {
				if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
					chat.lastContent = "[图片]";
				} else if (msgInfo.type == MESSAGE_TYPE.FILE) {
					chat.lastContent = "[文件]";
				} else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
					chat.lastContent = "[语音]";
				} else {
					chat.lastContent = msgInfo.content;
				}
				chat.lastSendTime = msgInfo.sendTime;
				chat.sendNickName = msgInfo.sendNickName;
			}
			// 未读加1
			if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED) {
				chat.unreadCount++;
			}
			// 是否有人@我
			if (!msgInfo.selfSend && chat.type == "GROUP" && msgInfo.atUserIds
				&& msgInfo.status != MESSAGE_STATUS.READED) {
				let userId = useIMUserStore().userInfo.id;
				if (msgInfo.atUserIds.indexOf(userId) >= 0) {
					chat.atMe = true;
				}
				if (msgInfo.atUserIds.indexOf(-1) >= 0) {
					chat.atAll = true;
				}
			}
			// 记录消息的最大id
			if (msgInfo.id && type == "PRIVATE" && msgInfo.id > this.privateMsgMaxId) {
				this.privateMsgMaxId = msgInfo.id;
			}
			if (msgInfo.id && type == "GROUP" && msgInfo.id > this.groupMsgMaxId) {
				this.groupMsgMaxId = msgInfo.id;
			}
			// 如果是已存在消息，则覆盖旧的消息数据
			for (let idx in chat?.messages) {
				if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
					Object.assign(chat.messages[idx], msgInfo);
					this.saveToStorage();
					return;
				}
				// 正在发送中的消息可能没有id,通过发送时间判断
				if (msgInfo.selfSend && chat.messages[idx].selfSend &&
					chat.messages[idx].sendTime == msgInfo.sendTime) {
					Object.assign(chat.messages[idx], msgInfo);
					this.saveToStorage();
					return;
				}
			}
			// 间隔大于10分钟插入时间显示
			if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
				chat.messages.push({
					sendTime: msgInfo.sendTime,
					type: MESSAGE_TYPE.TIP_TIME,
				});
				chat.lastTimeTip = msgInfo.sendTime;
			}
			// 新的消息
			chat.messages.push(msgInfo);
			this.saveToStorage();

		},
		deleteMessage(msgInfo) {
			// 获取对方id或群id
			let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
			let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
			let chat = null;
			for (let idx in this.chats) {
				if (this.chats[idx].type == type &&
					this.chats[idx].targetId === targetId) {
					chat = this.chats[idx];
					break;
				}
			}

			for (let idx in chat.messages) {
				// 已经发送成功的，根据id删除
				if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
					chat.messages.splice(idx, 1);
					break;
				}
				// 正在发送中的消息可能没有id，根据发送时间删除
				if (msgInfo.selfSend && chat.messages[idx].selfSend &&
					chat.messages[idx].sendTime == msgInfo.sendTime) {
					chat.messages.splice(idx, 1);
					break;
				}
			}
			this.saveToStorage();
		},
		updateChatFromFriend(friend) {
			for (let i in this.chats) {
				let chat = this.chats[i];
				if (chat.type == 'PRIVATE' && chat.targetId == friend.id) {
					chat.headImage = friend.headImageThumb;
					chat.showName = friend.nickName;
					break;
				}
			}
			this.saveToStorage();
		},
		updateChatFromGroup(group) {
			for (let i in this.chats) {
				let chat = this.chats[i];
				if (chat.type == 'GROUP' && chat.targetId == group.id) {
					chat.headImage = group.headImageThumb;
					chat.showName = group.remark;
					break;
				}
			}
			this.saveToStorage();
		},
		updateLoadingPrivateMsg(loadding) {
			this.loadingPrivateMsg = loadding;
			if (!this.loadingPrivateMsg && !this.loadingGroupMsg) {
				this.refreshChats()
			}
		},
		updateLoadingGroupMsg(loadding) {
			this.loadingGroupMsg = loadding;
			if (!this.loadingPrivateMsg && !this.loadingGroupMsg) {
				this.refreshChats()
			}
		},
		refreshChats(state) {
			this.chats.forEach((chat) => {
				if (chat.messages.length > 0) {
					let msgInfo = chat.messages[chat.messages.length - 1];
					if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
						chat.lastContent = "[图片]";
					} else if (msgInfo.type == MESSAGE_TYPE.FILE) {
						chat.lastContent = "[文件]";
					} else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
						chat.lastContent = "[语音]";
					} else {
						chat.lastContent = msgInfo.content;
					}
					chat.lastSendTime = msgInfo.sendTime;
				} else {
					chat.lastContent = "";
					chat.lastSendTime = new Date()
				}
			})
			this.chats.sort((chat1, chat2) => {
				return chat2.lastSendTime - chat1.lastSendTime;
			});
		},
		saveToStorage(state) {
			let userId = useIMUserStore().userInfo.id;
			let key = "chats-" + userId;
			let chatsData = {
				privateMsgMaxId: this.privateMsgMaxId,
				groupMsgMaxId: this.groupMsgMaxId,
				chats: this.chats
			}
			uni.setStorage({
				key: key,
				data: chatsData
			})
		},
		clear(state) {
			this.chats = [];
			this.activeIndex = -1;
			this.privateMsgMaxId = 0;
			this.groupMsgMaxId = 0;
			this.loadingPrivateMsg = false;
			this.loadingGroupMsg = false;
		},
		loadChat() {
			const self = this
			return new Promise((resolve, reject) => {
				let userId = useIMUserStore().userInfo.id;
				uni.getStorage({
					key: "chats-" + userId,
					success(res) {
						self.initChats(res.data)
						resolve()
					},
					fail(e) {
						resolve()
					}
				});
			})
		}
	},
}) 