
import { ApiCall } from 'tsrpc';
import { MsgChat } from '../shared/protocols/msg_s2c/MsgChat';
import { player } from '../shared/protocols/user/type';
import { chatLog, chatMsgLog } from '../shared/protocols/type'

const msgListLen = {
    'cross': 30,
    'local': 30,
    'guild': 20
};

export class ChatFun {
    /**新增消息 */
    static async newMsg(sendData: MsgChat) {
        G.mongodb.collection('chat').updateOne(
            { type: `${sendData.type}${sendData.type == 'guild' ? (sendData.sender as player)?.ghId : ''}` },
            { $push: { list: { $each: [sendData], $slice: -msgListLen[sendData.type] } } },
            { upsert: true }
        );

        if (sendData.type == 'guild') {
            G.server.broadcastClusterMsg('msg_s2c/Chat', sendData,{ghId:(sendData.sender as player)?.ghId});
        }else if(sendData.type == 'cross'){
            //所有的子进程都会收到，不需要集群内分别广播
            G.server.broadcastMsg('msg_s2c/Chat', sendData);
        }else{
            G.server.broadcastClusterMsg('msg_s2c/Chat', sendData);
        }
        
    }
    /**获取私聊列表 */
    static async getPrivateList(uid: string) {
        let privateIds = await G.redis.get('chatPrivate', uid) || [];

        if (privateIds.length < 1) return {};

        let privateList = await G.mongodb.collection('chat').find({ type: { $in: privateIds } }).toArray();

        return Object.fromEntries(privateList.map((p, i) => [p?.type, p?.list || []]));
    }
    /**写入私聊id */
    static async writePrivateId(uid: string, privateId: string) {
        G.redis.get('chatPrivate', uid).then(v => {
            if (v == null) {
                G.redis.set('chatPrivate', uid, [privateId]);
            } else {
                if (!v.includes(privateId)) {
                    G.redis.arrAppend('chatPrivate', uid, privateId);
                }
            }
        });
    }

    /**记录日志 */
    static async setChatLog(call: ApiCall, data: chatMsgLog ){
        // 整理数据
        let logData:chatLog = {
            uid: call.uid,
            ip: call.conn.ip,
            game: 'heijiao',
            owner: call.conn.gud.bindUid,
            name: call.conn.gud.name,
            type: data.type,
            toUid: data.toUid || '',
            content: data.content,
            ctime: G.time,
            vip: call.conn.gud.vip,
            lv: call.conn.gud.lv,
            sid: call.conn.gud.sid
        }
        // 写入记录
        G.mongodb.collection('chatLog').insertOne(logData)
        return 
    }
}