import { CHAT_SYSTEM } from './../pubUtils/dicParam';
import { PrivateChatRec } from './../db/ChatInfo';
import { RoleModel } from './../db/Role';
import { GroupMessageModel } from './../db/GroupMessage';
import { CounterModel } from './../db/Counter';
import { STATUS } from './../consts/statusCode';
import { PrivateMessageModel, PrivateMessageParam, PrivateMessageType } from './../db/PrivateMessage';
import { GroupMessageParam, GroupMessageType } from '../db/GroupMessage';
import { genCode, resResult } from '../pubUtils/util';
import { pinus } from 'pinus';
import { CHANNEL_PREFIX, MSG_CODE_LEN, MSG_STATUS, ON_PRIVATE_MSG_ROUTE, MSG_TYPE, MSG_SOURCE } from '../consts';
import { getRoleOnlineInfo } from './redisService';
import { ChatInfoModel } from '../db/ChatInfo';
import { channelServer } from './chatChannelService';
import { AccuseRecModel, AccueseParam } from '../db/AccuseRec';
import { getSimpleRoleInfo, getSimpleRoleInfos } from './roleService';

export * from './chatChannelService';
export * from './sysChatService';

/**
 * @description 生成私聊房间号
 * @export
 * @param {string[]} roleIds
 * @returns
 */
export function privateRoomId(roleId: string, targetRoleId: string) {
    return [roleId, targetRoleId].sort().join('_');
}

/**
 * @description 生成群聊房间号
 * @export
 * @param {string} channel
 * @param {string} channelId
 * @returns
 */
export function groupRoomId(channel: string, channelId: string | number) {
    return `${channel}_${channelId}`;
}

function msgCounterName(roomId: string) {
    return `chat_${roomId}`;
}

/**
 * @description 设置群消息和私聊消息的公共字段
 * @param {(PrivateMessageParam | GroupMessageParam)} msg
 */
async function setupBaseMsgParm(msg: PrivateMessageParam | GroupMessageParam ) {
    msg.msgCode = genCode(MSG_CODE_LEN);
    msg.status = MSG_STATUS.NORMAL;
    if (!msg.roomId) {
        console.error('roomId needed while setup msg parameter');
        return;
    }
    msg.seqId = await CounterModel.getNewCounter({name: msgCounterName(msg.roomId), def: 1});
}

/**
 * @description 生成私聊消息数据
 */
async function createPrivateMsgData(roleId: string, roleName: string, type: number, source: number, content: string, targetRoleId: string, targetMsgCode: string) {
    const result: PrivateMessageParam = {roleId, roleName, type, source, content, targetRoleId, targetMsgCode};
    result.roomId = privateRoomId(roleId, targetRoleId);
    await setupBaseMsgParm(result);
    return result;
}

/**
 * @description 生成群聊消息数据
 */
async function createGroupMsgData(roleId: string, roleName: string, channel: string, channelId: string, type: number, source: number, content: string, targetRoleId: string, targetMsgCode: string) {
    const result: GroupMessageParam = {roleId, roleName, channel, channelId, type, source, content, targetRoleId, targetMsgCode};
    result.roomId = groupRoomId(channel, channelId);
    await setupBaseMsgParm(result);
    return result;
}

/**
 * @description 数据库中创建私聊数据，需要更新聊天双方的聊天时间和未读消息数
 * @export
 * @param {string} roleId
 * @param {string} roleName
 * @param {number} type
 * @param {number} source
 * @param {string} content
 * @param {string} targetRoleId 消息接收者
 * @param {string} targetMsgCode 回复某条消息的唯一标识
 * @returns
 */
export async function createPrivateMsg(roleId: string, roleName: string, type: number, source: number, content: string, targetRoleId: string, targetMsgCode: string) {
    const msgData: PrivateMessageParam = await createPrivateMsgData(roleId, roleName, type, source, content, targetRoleId, targetMsgCode);
    const result: PrivateMessageType = await PrivateMessageModel.createMsg(msgData);

    const curTime = new Date();
    await updateRecentChats(true, roleId, targetRoleId, curTime);
    await updateRecentChats(false, targetRoleId, roleId, curTime);
    return result;
}

/**
 * @description 数据库中创建群聊数据
 * @export
 * @param {string} roleId
 * @param {string} roleName
 * @param {string} channel
 * @param {string} channelId
 * @param {number} type 消息类型
 * @param {number} source 消息来源，根据配表
 * @param {string} content 富文本的 content 为 JSON.stringfy 的对象
 * @param {string} targetRoleId
 * @param {string} targetMsgCode
 * @returns
 */
export async function createGroupMsg(roleId: string, roleName: string, channel: string, channelId: string, type: number, source: number, content: string, targetRoleId: string, targetMsgCode: string) {
    const msgData: GroupMessageParam = await createGroupMsgData(roleId, roleName, channel, channelId, type, source, content, targetRoleId, targetMsgCode);
    const result: GroupMessageType = await GroupMessageModel.createMsg(msgData);
    return result;
}

/**
 * @description 给某个玩家发送消息
 * @export
 * @param {string} targetRoleId 
 * @param {(PrivateMessageType | GroupMessageType)} msg
 */
export async function pushMsgToRole(msg: PrivateMessageType | GroupMessageType) {
    const targetRoleId = msg.targetRoleId!;
    const { sid } = await getRoleOnlineInfo(targetRoleId);
    if (sid) {
        const roleInfo = await getSimpleRoleInfo(msg.roleId);
        pinus.app.get('channelService').pushMessageByUids(ON_PRIVATE_MSG_ROUTE, resResult(STATUS.SUCCESS, { ...msg, roleInfo }), [{ uid: targetRoleId, sid }]);
    }
}

/**
 * @description 给某个群组发送消息
 * @export
 * @param {GroupMessageType} msg 群消息体
 * @returns
 */
export async function pushGroupMsgToRoom(msg: GroupMessageType) {
    if (!msg) return;
    const roomId = msg.roomId!;
    const channelSid = await channelServer(roomId);
    const roleInfo = await getSimpleRoleInfo(msg.roleId);
    await pinus.app.rpc.chat.chatRemote.sendGroupMsg.toServer(channelSid, roomId, { ...msg, roleInfo });
}

/**
 * @description 获取私聊历史消息
 * @export
 * @param {string} roleId
 * @param {string} targetRoleId
 * @param {number} fromSeqId 翻页时已经获取的最新消息标识
 * @param {number} count 期望获取的消息数量
 * @returns
 */
export async function getPrivateMessages(roleId: string, targetRoleId: string, fromSeqId: number, count: number) {
    const result = await PrivateMessageModel.getMsgs(privateRoomId(roleId, targetRoleId), fromSeqId, count);
    return result;
}

function sendFromRole(msg: GroupMessageParam) {
    return msg.source === MSG_SOURCE.ROLE_SEND_TEXT;
}

/**
 * @description 最近群聊消息
 * @param {string} roomId 群聊房间标识
 * @param {number} [count] 期望获取的消息数
 * @returns
 */
async function recentGroupMsgs(roomId: string, count?: number) {
    const msgs = await GroupMessageModel.getMsgs(roomId, Infinity, count || CHAT_SYSTEM.RECENT_GROUP_MSGS_CNT);
    const roleIds = msgs
        .map(msg => { return sendFromRole(msg) ? msg.roleId : null })
        .filter(roleId => !!roleId);
    const roleInfos = await getSimpleRoleInfos(roleIds);
    const result = roleInfos ?
        msgs.map(msg => {
            if (!sendFromRole(msg)) return msg;
            for (let roleInfo of roleInfos) {
                if (roleInfo.roleId === msg.roleId) {
                    return { ...msg, roleInfo };
                }
            }
        })
        : msgs;
    return result || [];
}

/**
 * @description 获取最近的世界聊天消息
 * @export
 * @param {number} serverId 用区服编号做房间标识
 * @param {number} [count]
 * @returns
 */
export async function recentWorldMsgs(serverId: number, count?: number) {
    const result = await recentGroupMsgs(groupRoomId(CHANNEL_PREFIX.WORLD, serverId), count);
    return result;
}

/**
 * @description 获取最近的系统聊天消息
 * @export
 * @param {number} serverId 用区服编号做房间标识
 * @param {number} [count]
 * @returns
 */
export async function recentSysMsgs(serverId: number, count?: number) {
    const result = await recentGroupMsgs(groupRoomId(CHANNEL_PREFIX.SYS, serverId), count);
    return result;
}

/**
 * @description 获取最近的军团聊天消息
 * @export
 * @param {string} guildCode 用军团编号作为房间标识
 * @param {number} [count]
 * @returns
 */
export async function recentGuildMsgs(guildCode: string, count?: number) {
    if(!guildCode) return [];
    const result = await recentGroupMsgs(groupRoomId(CHANNEL_PREFIX.GUILD, guildCode), count);
    return result;
}

/**
 * @description 创建新的私聊记录
 * @param {boolean} sender 给发送者还是接收者创建，发送者发消息的时候也阅读了消息
 * @param {Date} curTime 当前时间
 * @param {*} targetRoleId 聊天对象
 * @returns
 */
function createChatRec(sender: boolean, curTime: Date, targetRoleId) {
    const result: PrivateChatRec = {
        // 接收者没有阅读时间，发送者未读数为 0
        targetRoleId, lastChatTime: curTime, lastReadTime: sender ? curTime : null, unreadCnt: sender ? 0 : 1, isTop: false, setTopTime: curTime
    };
    return result;
}

/**
 * @description 更新最近聊天记录
 * @param {boolean} sender 同 createChatRec 接口参数
 * @param {string} roleId 更新此玩家的聊天记录
 * @param {string} targetRoleId roleId 的聊天对象
 * @param {Date} curTime
 */
async function updateRecentChats(sender: boolean, roleId: string, targetRoleId: string, curTime: Date) {
    const { recentPrivateChats } = await ChatInfoModel.findInfo(roleId);
    const recIdx = recentPrivateChats.findIndex(chat => { return chat.targetRoleId === targetRoleId });
    if (recIdx === -1) {
        recentPrivateChats.push(createChatRec(sender, curTime, targetRoleId));
    } else {
        recentPrivateChats[recIdx].lastChatTime = curTime;
        const { lastReadTime, unreadCnt } = recentPrivateChats[recIdx];
        // 发送者的最后阅读时间也更新，接收者的未读消息数增加
        recentPrivateChats[recIdx].lastReadTime = sender ? curTime : lastReadTime;
        recentPrivateChats[recIdx].unreadCnt = sender ? 0 : unreadCnt + 1;
    }
    await ChatInfoModel.updateInfo({ roleId, recentPrivateChats});
}

/**
 * @description 获取聊天信息
 */
export async function roleChatInfos(roleId: string, roleName: string) {
    let result = await ChatInfoModel.findInfo(roleId);
    if (!result) {
        result = await ChatInfoModel.createInfo({ roleId, roleName });
    }
    return result;
}

/**
 * @description 获取最近聊天记录，需要组织最近聊天玩家的信息
 */
export async function recentPrivateChatInfos(roleId: string, roleName: string) {
    const { recentPrivateChats } = await roleChatInfos(roleId, roleName);
    recentPrivateChats
        .sort((a, b) => {
            if(a.isTop || b.isTop) {
                if(a.isTop && b.isTop) {
                    return b.setTopTime.getTime() - a.setTopTime.getTime()
                } else {
                    return (b.isTop?1:0) - (a.isTop?1:0);
                }
            } else {
                return b.lastChatTime.getTime() - a.lastChatTime.getTime()
            }
        })
        .splice(CHAT_SYSTEM.RECENT_PRIVATE_CHATS_CNT);
    if (!recentPrivateChats || !recentPrivateChats.length) return null;

    const roleInfos = await RoleModel.findRoleByField('roleId', recentPrivateChats.map(chat => { return chat.targetRoleId }));
    const chatInfos = recentPrivateChats.map( chat => {
        for (let { roleId: targetRoleId, quitTime, loginTime, roleName: targetRoleName, title, guildName, head, frame, spine, lv } of roleInfos) {
            if (targetRoleId === chat.targetRoleId) {
                return { ...chat, quitTime, targetRoleName, title, guildName, head, frame, spine, lv, isOnline: quitTime === loginTime };
            }
        }
    });
    return chatInfos;
}

/**
 * @description 查看消息时更新查看时间和未读消息数
 */
export async function updatePrivateMsgReadInfo(roleId: string, targetRoleId: string) {
    const time = new Date();
    const chatInfo = await ChatInfoModel.updateReadInfo(roleId, targetRoleId, time);
    if (!chatInfo || !chatInfo.recentPrivateChats) {
        return null;
    }
    const chatRec = chatInfo.recentPrivateChats.find(rec => { return rec.targetRoleId === targetRoleId });
    return chatRec;
}

/**
 * @description 查看消息时更新查看时间和未读消息数
 */
export async function updatePrivateMsgIsTop(roleId: string, targetRoleId: string, isTop: boolean) {
    const time = new Date();
    const chatInfo = await ChatInfoModel.setTop(roleId, targetRoleId, isTop, time);
    if (!chatInfo || !chatInfo.recentPrivateChats) {
        return null;
    }
    const chatRec = chatInfo.recentPrivateChats.find(rec => { return rec.targetRoleId === targetRoleId });
    return chatRec;
}

/**
 * @description 查看消息时更新查看时间和未读消息数
 */
export async function delPrivateMsg(roleId: string, targetRoleId: string) {
    const chatInfo = await ChatInfoModel.delMsg(roleId, targetRoleId);
    if (!chatInfo || !chatInfo.recentPrivateChats) {
        return null;
    }
    return { targetRoleId };
}


/**
 * @description 发送组队一键邀请消息
 * @param {string} teamCode 队伍唯一标识
 */
export async function pushTeamInviteMsg(roleId: string, roleName: string, serverId: number, teamCode: string) {
    const msgDataWorld = await createGroupMsg(roleId, roleName, CHANNEL_PREFIX.WORLD, `${serverId}`, MSG_TYPE.RICH_TEXT, MSG_SOURCE.TEAM_INVITE, teamCode, null, null);
    const msgDataGuild = await createGroupMsg(roleId, roleName, CHANNEL_PREFIX.GUILD, `${serverId}`, MSG_TYPE.RICH_TEXT, MSG_SOURCE.TEAM_INVITE, teamCode, null, null);
    await pushGroupMsgToRoom(msgDataWorld);
    await pushGroupMsgToRoom(msgDataGuild);
    return { msgDataWorld, msgDataGuild };
}

/**
 * @description 发送组队私人邀请消息
 * @param {string} teamCode 队伍唯一标识
 */
 export async function pushFriendTeamInviteMsg(roleId: string, roleName: string, teamCode: string, targetRoleId) {
    const msgData = await createPrivateMsg(roleId, roleName, MSG_TYPE.RICH_TEXT, MSG_SOURCE.TEAM_INVITE, teamCode, targetRoleId, null);
    await pushMsgToRole(msgData);
    return msgData;
}


export async function createAccuseData(roleId: string, targetRoleId: string, targetMsgCode: string, reason: number) {
    const data: AccueseParam = {
        roleId, targetRoleId, targetMsgCode, reason
    };
    const result = await AccuseRecModel.createRec(data);
    return result;
}
