import { ApiCall, WsClientStatus } from "tsrpc";
import { ActionLog } from '../../public/actionLog/actionLog';
import { ChatFun } from '../../public/chat';
import { ReqSend, ResSend } from "../../shared/protocols/chat/PtlSend";
import { chatMsgLog } from "../../shared/protocols/type"
import { getGud } from "../../public/gud";


export default async function (call: ApiCall<ReqSend, ResSend>) {
    let status_chat = (await getGud(call.uid))['status_chat'];
    // 验证是否被禁言
    if(status_chat == 1) return call.error(lng.chat_4);
    let data = call.req;
    if (data.msg.length < 1 || data.msg.length > 30) return call.error('', { code: -1 });

    if (data.otherData?.helpIndex != undefined) {
        let num = await ActionLog.getDayLog(call.uid, 'resHelp');
        if (num > 0) return call.errorCode(-2);
        ActionLog.addDayLog(call.uid, { key: 'resHelp', val: 1 });
        data.otherData.helpUis = [];
        // 我助力别人次数 初始10
        data.otherData.myhelpless = 10;
    }

    let gud = call.conn.gud;
    let sendData = {
        ...data,
        time: G.time,
        sender: gud
    };
    // 写入聊天记录
    let msgLog:chatMsgLog = {
        content: call.req.msg,
        type: call.req.type
    }
    //往chatLog表插入记录
    ChatFun.setChatLog(call, msgLog)
    
    if (sendData.type == 'guild' && !gud.ghId) return call.error('', { code: -3, message: globalThis.lng.chat_3 });

    if (sendData.type == 'cross' && G.clientCross?.status == WsClientStatus.Opened) {
        //如果是跨服的话，调用跨服API的这条协议
        G.clientCross.sendMsg('msg_cross/CrossChat', sendData);
        call.succ({});
        return;
    }

    ChatFun.newMsg(sendData);
    
    call.succ({});
}