import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { PlayerFun } from '../../public/player';
import { formatNpcData } from '../../shared/fightControl/fightFun';
import { ReqFbFight, ResFbFight } from "../../shared/protocols/gonghui/PtlFbFight";
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqFbFight, ResFbFight>) {

    let gh = await call.conn.gonghui;
    let conf = G.gc.shili_fb[gh.data.fuben.id];

    if (!conf) return call.error(globalThis.lng.gonghui_11);

    let dbData = await G.mongodb.collection('gonghuiUser').findOne({ uid: call.uid });

    if (dbData.fuben.fightNum < 1) return call.error(globalThis.lng.gonghui_12);

    if (await gh.getIsFightBoss()) return call.error(globalThis.lng.gonghui_13);

    await gh.changeIsFightBoss(true);

    let npc = formatNpcData(conf.npc);
    Object.entries(gh.data.fuben.bossInfo).forEach(role => {
        Object.assign(npc.roles[role[0]].attr, role[1]);
    });

    let result = FightFun.fight([
        {
            ...await call.conn.getDefaultFightData()
        },
        npc
    ], 30, 'pve');
    if (!gh.data.fuben.dps[call.uid]) gh.data.fuben.dps[call.uid] = result.totalDamage[0];
    else gh.data.fuben.dps[call.uid] += result.totalDamage[0];
    // winSide == 0 战斗胜利
    if (result.winSide == 0) {

        await G.mongodb.collection('gonghuiFb').insertOne({ ghId: gh.data._id, fbId: gh.data.fuben.id, rankList: gh.data.fuben.dps });

        gh.sendeMail(gh.data.fuben.id, Object.keys(gh.data.fuben.dps).map(uid => [uid, gh.data.fuben.dps[uid]]));

        gh.data.fuben = {
            id: (Number(gh.data.fuben.id) + 1).toString(),
            dps: {},
            bossInfo: {},
        };

        gh.addExp(conf.gongxianprize, call.uid);
    } else {
        Object.entries(result.fightData[1].roles).forEach(role => {
            gh.data.fuben.bossInfo[role[0]] = { hp: role[1].attr.hp, maxHp: role[1].attr.maxHp };
        });
    }

    gh.updateDb({ $set: { fuben: gh.data.fuben } });
    gh.changeIsFightBoss(false);

    let prize = conf.fightPrize.map(v => PublicShared.randomDropGroup(v)).reduce((a, b) => a.concat(b));

    await PlayerFun.sendPrize(call, prize);
    G.mongodb.collection('gonghuiUser').updateOne({ uid: call.uid }, { $inc: { 'fuben.fightNum': -1 } });
    HongDianChange.sendChangeKey(call.uid, ['gonghuihd']);

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