import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { PlayerFun } from '../../public/player';
import { fightResult } from '../../shared/fightControl/fightType';
import { ReqFight, ResFight } from "../../shared/protocols/kbzz/PtlFight";
import { prizeType } from '../../shared/protocols/type';
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";
import { kbzzUserDb } from './ApiOpen';

export default async function (call: ApiCall<ReqFight, ResFight>) {
    let uids = call.req.uids;
    if (uids.length < 1 || uids.isDuplication()) return call.error(globalThis.lng.kbzz_1);

    let dbData = await kbzzUserDb().findOne({ uid: call.uid, type: 'kbzzUser' });
    if (dbData.fightNum < uids.length) return call.error(globalThis.lng.jjc_4);

    let enemys = dbData.enemy.filter(e => uids.includes(e.info.player.uid) && e.result == null);
    if (enemys.length < uids.length) return call.error(globalThis.lng.kbzz_1);

    let prize: prizeType[] = [];
    let result: fightResult[] = [];
    let change: ResFight['change'] = {};
    let addScore = 0;
    let myInfo = await call.conn.getDefaultFightData();

    enemys.forEach((enemy, index) => {
        let r = FightFun.fight([myInfo, enemy.info]);
        r.otherData = {
            troops: [dbData.troop, enemy.troop]
        };
        // FightFun.saveLog(call.uid, 'kbzz', r, 50);

        enemy.result = r.winSide;
        result.push(r);

        let getScore = 0;
        if (r.winSide == 0) {
            //getScore = 200 + Math.floor((enemy.info.player.power || 0) / 500000);
            //if (getScore > 400) getScore = 400;
            getScore = G.gc.kbzz.winScore;
        } else {
            //getScore = 100;
            getScore = G.gc.kbzz.failScore;
        }
        addScore += getScore;
        prize.push(...G.gc.kbzz[r.winSide == 0 ? 'winPrize' : 'failPrize']);

        G.clientCross.callApi('kbzz/UpUser', {
            uid: call.uid,
            group: dbData.group,
            troop: dbData.troop,
            info: index == enemys.length - 1 ? myInfo : null,
            allScore: dbData.score + addScore,
            addScore: getScore,
            log: {
                player: [myInfo.player, enemy.info.player],
                troop: [dbData.troop, enemy.troop],
                winSide: r.winSide
            }
        });
    });

    prize = PublicShared.mergePrize(prize);
    change.fightNum = dbData.fightNum - uids.length;
    change.toDayScore = dbData.toDayScore + addScore;
    change.enemy = dbData.enemy;
    change.score = dbData.score + addScore;

    await PlayerFun.sendPrize(call, prize);

    kbzzUserDb().updateOne({ uid: call.uid, type: 'kbzzUser' }, { $set: { ...change } });

    HongDianChange.sendChangeKey(call.uid, ['kbzzhd']);

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