import store from "@/store";
import {CustomType,GroupSystemMessageTypes,noticeMessageTypes} from "@/constant";
import IMSDK, {GroupAtType,MessageType,SessionType} from "openim-uniapp-polyfill";
import dayjs from "dayjs";
import {isThisYear} from "date-fns";

import calendar from "dayjs/plugin/calendar";
import relativeTime from "dayjs/plugin/relativeTime";
import updateLocale from "dayjs/plugin/updateLocale";
import "dayjs/locale/zh-cn";

dayjs.extend(calendar);
dayjs.extend(relativeTime);
dayjs.extend(updateLocale);
dayjs.locale("zh-cn");

dayjs.updateLocale("en", {
	calendar: {
		sameElse: "YYYY-MM-DD",
	},
});
dayjs.updateLocale("zh-cn", {
	calendar: {
		sameDay: "HH:mm",
		nextDay: "[明天]",
		nextWeek: "dddd",
		lastDay: "[昨天] HH:mm",
		lastWeek: "dddd HH:mm",
		sameElse: "YYYY年M月D日 HH:mm",
	},
});

export const date = (timestemp, fmt = 'YYYY-MM-DD HH:mm:ss') => {
	if (!timestemp) return "";
	return dayjs(timestemp).format(fmt)
};
export const formatMessageTime = (timestemp, keepSameYear = false) => {
	if (!timestemp) return "";
	const isRecent = dayjs().diff(timestemp, "day") < 7;
	const keepYear = keepSameYear || !isThisYear(timestemp);

	if (!isRecent && !keepYear) {
		return dayjs(timestemp).format("M月D日 HH:mm");
	}

	return dayjs(timestemp).calendar();
};

export const conversationSort = (conversationList) => {
	const arr = [];
	const filterArr = conversationList.filter(
		(c) => !arr.includes(c.conversationID) && arr.push(c.conversationID),
	);
	filterArr.sort((a, b) => {
		if (a.isPinned === b.isPinned) {
			const aCompare =
				a.draftTextTime > a.latestMsgSendTime ?
				a.draftTextTime :
				a.latestMsgSendTime;
			const bCompare =
				b.draftTextTime > b.latestMsgSendTime ?
				b.draftTextTime :
				b.latestMsgSendTime;
			if (aCompare > bCompare) {
				return -1;
			} else if (aCompare < bCompare) {
				return 1;
			} else {
				return 0;
			}
		} else if (a.isPinned && !b.isPinned) {
			return -1;
		} else {
			return 1;
		}
	});
	return filterArr;
};


export const sec2Time = (seconds) => {
	var theTime1 = 0; // min
	var theTime2 = 0; // hour
	var theTime3 = 0; // day
	if (seconds > 60) {
		theTime1 = parseInt(seconds / 60);
		seconds = parseInt(seconds % 60);
		if (theTime1 > 60) {
			theTime2 = parseInt(theTime1 / 60);
			theTime1 = parseInt(theTime1 % 60);
			if (theTime2 > 24) {
				theTime3 = parseInt(theTime2 / 24);
				theTime2 = parseInt(theTime2 % 24);
			}
		}
	}
	var result = "";
	if (seconds > 0) {
		result = "" + parseInt(seconds) + "秒";
	}
	if (theTime1 > 0) {
		result = "" + parseInt(theTime1) + "分钟" + result;
	}
	if (theTime2 > 0) {
		result = "" + parseInt(theTime2) + "小时" + result;
	}
	if (theTime3 > 0) {
		result = "" + parseInt(theTime3) + "天" + result;
	}
	return result;
};

export const parseMessageByType = (pmsg) => {
	const getName = (user) => {
		return user.userID === store.getters.storeCurrentUserID ?
			"你" :
			user.nickname;
	};

	switch (pmsg.contentType) {
		case MessageType.TextMessage:
			return pmsg.textElem.content;
		case MessageType.AtTextMessage:
			return pmsg.AtElem.text;
			//atUsersInfo
			//isAtSelf
			//isAtAll
		case MessageType.PictureMessage:
			return `[图片]`;
		case MessageType.VoiceMessage:
			return `[语音]`;
		case MessageType.VideoMessage:
			return `[视频]`;
		case MessageType.FileMessage:
			return `[文件]`;
		case MessageType.MergeMessage:
			return `[合并消息]`;
		case MessageType.CardMessage:
			return `[名片]`;
		case MessageType.LocationMessage:
			return `[位置]`;
		case MessageType.CustomMessage:
			return `[自定义消息]`;
		case MessageType.TypingMessage:
			return `[TypingMessage]`;
		case MessageType.QuoteMessage:
			return `[QuoteMessage]`;
		case MessageType.FaceMessage:
			return `[FaceMessage]`;
		case MessageType.MarkdownMessage:
			return `[MarkdownMessage]`;
		case MessageType.MsgPinned:
			//消息置顶
			return `[MsgPinned]`;
		case MessageType.BurnMessageChange:
			//阅后即焚开启或关闭通知
			//console.log(pmsg);
			return `阅后即焚已经开启`;
		case MessageType.OANotification:
			return `[OANotification]`;
		case MessageType.FriendAdded:
		case MessageType.GroupCreated:
		case MessageType.GroupInfoUpdated:
		case MessageType.MemberQuit:
		case MessageType.GroupOwnerTransferred:
		case MessageType.MemberKicked:
		case MessageType.MemberInvited:
		case MessageType.MemberEnter:
		case MessageType.GroupMemberMuted:
		case MessageType.GroupMemberCancelMuted:
		case MessageType.GroupMuted:
		case MessageType.GroupCancelMuted:
		case MessageType.GroupDismissed:
		case MessageType.GroupAnnouncementUpdated:
		case MessageType.GroupNameUpdated:
		case MessageType.RevokeMessage:
		case 2001:
			return tipMessaggeFormat(pmsg,store.getters.storeCurrentUserID);
		default:
			//console.log(pmsg);
			return "[暂未支持的消息类型]";
	}
};


export const formatConversionTime = (timestemp) => {
	const fromNowStr = dayjs(timestemp).fromNow();

	if (fromNowStr.includes("秒")) {
		return "刚刚";
	}

	if (!fromNowStr.includes("秒") && !fromNowStr.includes("分钟")) {
		return dayjs(timestemp).calendar();
	}

	return fromNowStr;
};

export const secFormat = (sec) => {
	let h;
	let s;
	h = Math.floor(sec / 60);
	s = sec % 60;
	h += "";
	s += "";
	h = h.length === 1 ? "0" + h : h;
	s = s.length === 1 ? "0" + s : s;
	return h + ":" + s;
};

export const bytesToSize = (bytes) => {
	if (bytes === 0) return "0 B";
	var k = 1024,
		sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
		i = Math.floor(Math.log(bytes) / Math.log(k));

	return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
};
export const tipMessaggeFormat = (msg, currentUserID) => {
	const getName = (user) =>
		user.userID === currentUserID ? "你" : user.nickname;

	let notificationDetail = {};
	if(msg?.notificationElem?.detail){
		notificationDetail = JSON.parse(msg.notificationElem.detail);
	}
	switch (msg.contentType) {
		case MessageType.FriendAdded:
			return `你们已经是好友了~`;
		case MessageType.GroupCreated:
			return `${getName(notificationDetail.opUser)}创建了群聊`;
		case MessageType.GroupInfoUpdated:
			return `${getName(notificationDetail.opUser)}修改了群信息`;
		case MessageType.MemberQuit:
			const quitUser = notificationDetail.quitUser;
			return `${getName(quitUser)}退出了群组`;
		case MessageType.GroupOwnerTransferred:
			const transferOpUser = notificationDetail.opUser;
			const newOwner = notificationDetail.newGroupOwner;
			return `${getName(transferOpUser)}转让群主给${getName(newOwner)}`;
		case MessageType.MemberKicked:
			const kickOpUser = notificationDetail.opUser;
			const kickdUserList = notificationDetail.kickedUserList ?? [];
			let kickStr = "";
			kickdUserList.find(
				(user, idx) => (kickStr += getName(user) + "、") && idx > 3,
			);
			kickStr = kickStr.slice(0, -1);
			return `${getName(kickOpUser)} 踢出了${kickStr}${kickdUserList.length > 3 ? "..." : ""}`;
		case MessageType.MemberInvited:
			const inviteOpUser = notificationDetail.opUser;
			const invitedUserList = notificationDetail.invitedUserList ?? [];
			let inviteStr = "";
			invitedUserList.find(
				(user, idx) => (inviteStr += getName(user) + "、") && idx > 3,
			);
			inviteStr = inviteStr.slice(0, -1);
			return `${getName(inviteOpUser)} 邀请了${inviteStr}${invitedUserList.length > 3 ? "..." : ""}加入群聊`;
		case MessageType.MemberEnter:
			return `${getName(notificationDetail.entrantUser)}加入了群聊`;
		case MessageType.GroupDismissed:
			return `${getName(notificationDetail.opUser)}解散了群聊`;
		case MessageType.GroupMemberMuted:
			return `${getName(notificationDetail.opUser)}禁言了${getName(notificationDetail.mutedUser)}`;
		case MessageType.GroupMemberCancelMuted:
			return `${getName(notificationDetail.opUser)}取消了${getName(notificationDetail.mutedUser)}的禁言`;
		case MessageType.GroupMuted:
			return `${getName(notificationDetail.opUser)}设置了全员禁言`;
		case MessageType.GroupCancelMuted:
			return `${getName(notificationDetail.opUser)}取消了全员禁言`;
		case MessageType.GroupAnnouncementUpdated:
			return `${getName(notificationDetail.opUser)}更新了群公告`;
		case MessageType.GroupNameUpdated:
			return `${getName(notificationDetail.opUser)}修改了群名称为${notificationDetail.group.groupName}`;
		case MessageType.RevokeMessage:
			return `${notificationDetail.revokerNickname}撤回了一条消息`;
		case 2001:
			let data = JSON.parse(notificationDetail.data);
			return parseMessageByType(data);
		default:
			console.log(msg.contentType,notificationDetail);
			return `[不支持的消息类型: ${msg.contentType}]`;
	}
};


export const markConversationAsRead = (conversation, fromChating = false) => {
	if (conversation.unreadCount !== 0) {
		IMSDK.asyncApi(
			IMSDK.IMMethods.MarkConversationMessageAsRead,
			IMSDK.uuid(),
			conversation.conversationID,
		);
	}
};

export const prepareConversationState = (conversation, back2Tab = false) => {
	markConversationAsRead(conversation);

	if (conversation.conversationType === SessionType.WorkingGroup) {
		store.dispatch("conversation/getCurrentGroup", conversation.groupID);
		store.dispatch(
			"conversation/getCurrentMemberInGroup",
			conversation.groupID,
		);
	}
	store.dispatch("message/resetMessageState");
	store.commit("conversation/SET_CURRENT_CONVERSATION", conversation);

	let url = `/pages/conversation/chating/index?back2Tab=${back2Tab}`;
	setTimeout(() => {
		uni.navigateTo({
			url,
		});
	}, 300)
};

export const navigateToDesignatedConversation = (sourceID,sessionType,back2Tab = false,) => {
	return new Promise(async (resolve, reject) => {
		try {
			const {
				data
			} = await IMSDK.asyncApi(
				IMSDK.IMMethods.GetOneConversation,
				IMSDK.uuid(), {
					sessionType,
					sourceID,
				},
			);
			prepareConversationState(data, back2Tab);
			resolve();
		} catch (e) {
			reject(e);
		}
	});
};

export const offlinePushInfo = {
	title: "you have a new message",
	desc: "you have a new message",
	ex: "",
	iOSPushSound: "",
	iOSBadgeCount: true,
};

export const getConversationContent = (message) => {
	if(noticeMessageTypes.includes(message.contentType)){
		return `${parseMessageByType(message)}`;
	}
	if (
		!message.groupID ||
		message.sendID === store.getters.storeCurrentUserID
	) {
		return parseMessageByType(message);
	}
	if(message.senderNickname){
		return `${message.senderNickname}：${parseMessageByType(message)}`;
	}
	return parseMessageByType(message);
};
export const updateDot = (index,count) =>{
	if(count>0){
		uni.setTabBarBadge({
			index:index,
			text:(count<100?count:'99+')+'',
		});
	}else{
		uni.hideTabBarRedDot({index:index})
	}
}
export const updateTabbar = (index)=>{
	if(index===0 || index === undefined){
		updateDot(0,store.getters.storeUnReadCount);
	}
	if(index===1 || index === undefined){
		updateDot(1,store.getters.storeUnHandleFriendApplicationNum+store.getters.storeUnHandleGroupApplicationNum);
	}
	if(index===2 || index === undefined){
		updateDot(2,store.getters.storeCircleUnreadCount);
	}

};