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, MSG_TYPE, MSG_SOURCE, PUSH_ROUTE, FRIEND_RELATION_TYPE } from '../consts';
import { getRoleOnlineInfo } from './redisService';
import { ChatInfoModel } from '../db/ChatInfo';
import { AccuseRecModel, AccueseParam } from '../db/AccuseRec';
import { getSimpleRoleInfo, getSimpleRoleInfos } from './roleService';
import { sendMessageToAllWithSuc, sendMessageToCityWithSuc, sendMessageToGuildWithSuc,  sendMessageToServerWithSuc, sendMessageToTeam, sendMessageToUserWithSuc } from './pushService';
import { comBtlLvInvalid } from './comBattleService';
import { gameData } from '../pubUtils/data';
import { RegionModel } from '../db/Region';
import { getGroupIdOfServer, getServersByGroupId } from './gvg/gvgService';
import { GVGLeagueModel } from '../db/GVGLeague';

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 channelId?`${channel}_${channelId}`: `${channel}`;
}

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

/**
 * @description 设置群消息和私聊消息的公共字段
 * @param {(PrivateMessageParam | GroupMessageParam)} msg
 */
async function setupBaseMsgParm(msg: PrivateMessageParam | GroupMessageParam ) {
    msg.msgCode = genCode(MSG_CODE_LEN);
    if(!msg.status) 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, relation: number) {
    const result: PrivateMessageParam = {roleId, roleName, type, source, content, targetRoleId, targetMsgCode};
    result.roomId = privateRoomId(roleId, targetRoleId);
    result.status = relation == FRIEND_RELATION_TYPE.HAS_BLOCKED? MSG_STATUS.BLOCKED: MSG_STATUS.NORMAL;
    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, otherInfo = '') {
    const result: GroupMessageParam = {roleId, roleName, channel, channelId, type, source, content, targetRoleId, targetMsgCode, otherInfo };
    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, relation: number) {
    const msgData: PrivateMessageParam = await createPrivateMsgData(roleId, roleName, type, source, content, targetRoleId, targetMsgCode, relation);
    const result: PrivateMessageType = await PrivateMessageModel.createMsg(msgData);

    const curTime = new Date();
    await updateRecentChats(true, roleId, targetRoleId, curTime);
    if(result.status == MSG_STATUS.NORMAL) {
        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, otherInfo = '') {
    const msgData: GroupMessageParam = await createGroupMsgData(roleId, roleName, channel, channelId, type, source, content, targetRoleId, targetMsgCode, otherInfo);
    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!;
    if(msg.status == MSG_STATUS.BLOCKED) return;
    
    const { sid } = await getRoleOnlineInfo(targetRoleId);
    if (sid) {
        const roleInfo = await getSimpleRoleInfo(msg.roleId);
        sendMessageToUserWithSuc(targetRoleId, PUSH_ROUTE.PRIVATE_MSG, { ...msg, roleInfo }, sid);
    }
}

/**
 * @description 给某个群组发送消息
 * @export
 * @param {GroupMessageType} msg 群消息体
 * @returns
 */
export async function pushGroupMsgToRoom(msg: GroupMessageType) {
    if (!msg) return;
    const roleInfo = await getSimpleRoleInfo(msg.roleId);
    if(msg.channel == CHANNEL_PREFIX.WORLD || msg.channel == CHANNEL_PREFIX.SYS || msg.channel == CHANNEL_PREFIX.WORLD_AUCTION) {
        let serverId = parseInt(msg.channelId);
        await sendMessageToServerWithSuc(serverId, PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo });
    } else if(msg.channel == CHANNEL_PREFIX.GUILD || msg.channel == CHANNEL_PREFIX.GUILD_AUCTION) {
        let guildCode = msg.channelId;
        await sendMessageToGuildWithSuc(guildCode, PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo })
    } else if (msg.channel == CHANNEL_PREFIX.TEAM) {
        let teamCode = msg.channelId;
        await sendMessageToTeam(teamCode, PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo });
    } else if (msg.channel == CHANNEL_PREFIX.CITY) {
        let arr = msg.channelId.split('_');
        await sendMessageToCityWithSuc(parseInt(arr[0]), parseInt(arr[1]), PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo });
    } else if (msg.channel == CHANNEL_PREFIX.GVG) {
        let groupId = parseInt(msg.channelId);
        let serverIds = await getServersByGroupId(groupId);
        for(let serverId of serverIds) {
            await sendMessageToServerWithSuc(serverId, PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo });
        }
    } else if (msg.channel == CHANNEL_PREFIX.LEAGUE) {
        let guildCodes = msg.otherInfo? msg.otherInfo.split('|'): [];
        for(let guildCode of guildCodes) {
            await sendMessageToGuildWithSuc(guildCode, PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo });
        }
    } 
}

export async function pushGroupMsgToAll(msg: GroupMessageType, filterCb?: ({ lv, topLineupCe }) => boolean) {
    if (!msg) return;
    const roleInfo = await getSimpleRoleInfo(msg.roleId);
    await sendMessageToAllWithSuc(PUSH_ROUTE.GROUP_MSG, { ...msg, roleInfo }, filterCb);
}

/**
 * @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.filter(cur => cur) || [];
}

/**
 * @description 获取最近的战区聊天消息
 * @export
 * @param {number} serverId 用区服编号做房间标识
 * @param {number} [count]
 * @returns
 */
export async function recentServerGroupMsgs(serverId: number, count?: number) {
    let groupId = await getGroupIdOfServer(serverId);
    const result = await recentGroupMsgs(groupRoomId(CHANNEL_PREFIX.GVG, groupId), count);
    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 获取最近的联军聊天消息
 * @export
 * @param {string} guildCode 用区服编号做房间标识
 * @param {number} [count]
 * @returns
 */
export async function recentLeagueMsgs(guildCode: string, count?: number) {
    if(!guildCode) return [];
    let myLeague = await GVGLeagueModel.findLeagueByGuild(guildCode);
    if(!myLeague) return [];
    const result = await recentGroupMsgs(groupRoomId(CHANNEL_PREFIX.LEAGUE, myLeague.leagueCode), 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 chatInfo = await roleChatInfos(roleId);
    let recentPrivateChats: PrivateChatRec[] = chatInfo?.recentPrivateChats||[]
    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) {
    if(!roleName) {
        let role = await RoleModel.findByRoleId(roleId, 'roleName');
        roleName = role.roleName;
    }
    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 [];

    const roleInfos = await RoleModel.findByRoleIds(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, blueprtId: number, blueprtLv: number, ceLimit: number) {
    let msgDataWorld = await createGroupMsg(roleId, roleName, CHANNEL_PREFIX.WORLD, `${serverId}`, MSG_TYPE.RICH_TEXT, MSG_SOURCE.TEAM_INVITE, JSON.stringify({ roleName, teamCode, blueprtId }), null, null);
    await pushGroupMsgToAll(msgDataWorld, (data: {lv: number, topLineupCe: number}) => {
        return data.topLineupCe >= ceLimit && !comBtlLvInvalid(data.lv, [blueprtLv]);
    });
    return { msgDataWorld };
}

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


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

/*
const client = new FCClient('1475752363809339', {
    accessKeyID: 'LTAI5tFTwE7vwH5HGL7eV8xr',
    accessKeySecret: 'HZznAZfOrmXttBMevhA55jQX3OGw9j',
    region: 'cn-zhangjiakou',
});

export async function checkFilterWords(word: string) {
    const resp = await client.post('/proxy/bantuUtils/filterWords/check',{
        word,
        salt: "bantu1filter2word3test"
    }, {});
    let hasBlock = true;
    try {
        let data = JSON.parse(resp.data);
        hasBlock = data.status != 0;
    } catch (e) {
        console.log(e);
    }

    return hasBlock;
}
*/

export function isApiClose() {
    return pinus.app.get('apiIsClose');
}

export async function checkAndSetApiIsClose() {
    let region = await RegionModel.findRegionByEnv(pinus.app.get('env'));
    setApiIsClose(region?.isCloseApi??false);
}

export function setApiIsClose(isClose: boolean) {
    pinus.app.set('apiIsClose', isClose);
}

export async function setApiIsCloseToRemote(isClose: boolean) {
    await pinus.app.rpc.activity.activityRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.battle.battleRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.chat.chatRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.connector.connectorRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.guild.guildRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.order.orderRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.role.roleRemote.setApiIsClose.broadcast(isClose);
    await pinus.app.rpc.systimer.systimerRemote.setApiIsClose.broadcast(isClose);
} 