import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { Rank } from '../../public/rank/rank';
import { fightResult } from '../../shared/fightControl/fightType';
import { ReqFight, ResFight } from "../../shared/protocols/slzd/PtlFight";
import { player } from '../../shared/protocols/user/type';
import { PublicShared } from "../../shared/public/public";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqFight, ResFight>) {
    let dbData = await G.mongodb.collection('slzdUser').findOne({ uid: call.uid });
    let data = dbData.data;
    let fort = call.req.fort;
    let index = call.req.index;

    if (data.fightNum < 1) return call.error(globalThis.lng.slzd_3);
    if (data.enemy[fort]?.[index]?.result == 0) return call.error(globalThis.lng.shiwu_6);

    let _zeroTime = PublicShared.getToWeekMondayZeroTime(G.time)
    if (!(_zeroTime + G.gc.slzd.openTime[0] <= G.time && G.time <= _zeroTime + G.gc.slzd.openTime[1])) return call.error('', { code: -1, message: globalThis.lng.slzd_4 });

    let change: ResFight['change'] = {};
    let my = await call.conn.getDefaultFightData();
    let enemy = data.enemy[fort][index];
    let result = FightFun.fight([my, enemy.data]);
    let myAdd = 0;
    let selfAdd = 0;

    if (result.winSide == 0) {
        myAdd = 5;
        selfAdd = -2;
        change.winNum = ++data.winNum;
    } else {
        myAdd = 1;
    }

    add(call.conn.gud, fort, myAdd, result);
    add(enemy.data.player, fort, selfAdd, result);
    FightFun.saveLog(call.conn.gud.ghId, 'slzd', result)

    enemy.result = result.winSide;
    data.replyCd = G.time;
    change.enemy = data.enemy;
    change.replyCd = data.replyCd;
    change.fightNum = --data.fightNum;

    G.mongodb.collection('slzdUser').updateOne(
        { uid: call.uid },
        { $set: { data: data, info: { ...my } }, $inc: { recordFightNum: 1 } }
    );

    HongDianChange.sendChangeKey(call.uid, ['slzdhd'])

    call.succ({
        result: result,
        change: change
    });
}

async function add(player: Partial<player>, fort: string, add: number, result: fightResult) {
    if (player.uid.indexOf('npc') != -1) return;
    let user = await G.mongodb.collection('slzdUser').findOne({ uid: player.uid });
    let gh = await G.mongodb.collection('slzdGh').findOne({ ghid: player.ghId });

    let myVal = (user.val?.[fort] || 0) + add <= 0 ? 0 : (user.val?.[fort] || 0) + add;
    let ghVal = (gh?.val[fort] || 0) + add <= 0 ? 0 : (gh?.val[fort] || 0) + add;

    G.mongodb.collection('slzdUser').updateOne(
        { uid: player.uid },
        { $set: G.mongodb.createTreeObj({ key: 'val.' + fort, val: myVal }) }
    );

    G.mongodb.collection('slzdGh').updateOne(
        { ghid: player.ghId },
        { $set: G.mongodb.createTreeObj({ key: 'val.' + fort, val: ghVal }, { key: 'ghName', val: player.ghName }) },
        { upsert: true }
    );

    (Rank.list[`slzd${fort}`] as Rank).addNew(
        {
            player: {
                ghId: player.ghId,
                ghName: player.ghName
            },
            valArr: [ghVal]
        }
    );
    // FightFun.saveLog(player.ghId, 'slzd', result);
}