import {ApiCall} from "tsrpc";
import {FightFun} from '../../public/fight';
import {PlayerFun} from "../../public/player";
import {QjzzdFun} from "../../public/qjzzd";
import {Rank} from '../../public/rank/rank';
import {ReqFight, ResFight} from "../../shared/protocols/qjzzd/PtlFight";
import {PublicShared} from "../../shared/public/public";
import {HongDianChange} from "../hongdian/fun";

export default async function (call: ApiCall<ReqFight, ResFight>) {
    // 获取配置数据
    let data = await G.mongodb.collection('scheduler').findOne({type: 'qjzzd'});
    if (!data) return call.error('', {code: -1, message: globalThis.lng.qjzzd_5});
    // 获取个人次数等数据
    let myData = await G.mongodb.cPlayerInfo('qjzzd').findOne({uid: call.uid, type: 'qjzzd'});
    let _zeroTime = PublicShared.getToDayZeroTime(G.time)

    if (await QjzzdFun.chkSetBoosId()) {
        if (!(_zeroTime + G.gc.qjzzd.time[0] <= G.time && G.time <= _zeroTime + G.gc.qjzzd.time[1])) {
            return call.error('', {code: -1, message: globalThis.lng.qjzzd_5});
        }
    }

    // 战斗
    let result = await FightFun.fightNpc(call, data.boss, 'qjzzd');
    // 次数消耗计算
    let change: ResFight['change'] = {};
    change.useFightNum = myData.useFightNum + 1;
    // 获取当前maxDps
    let currentMaxDps = await Rank.list.qjzzd.getRankScore(call.uid);
    // 最高dps计算
    change.maxDps = result.totalDamage[0] > currentMaxDps ? result.totalDamage[0] : currentMaxDps;
    if (result.totalDamage[0] > currentMaxDps) {
        Rank.list['qjzzd'].addNew({
            player: call.conn.gud,
            valArr: [change.maxDps]
        });
    }

    G.mongodb.cPlayerInfo('qjzzd').updateOne(
        {uid: call.uid, type: 'qjzzd'},
        {$inc: {useFightNum: 1}},
        {upsert: true}
    );

    let _prize = await QjzzdFun.getFightPrize(change.useFightNum)
    _prize && await PlayerFun.sendPrize(call, _prize);
    HongDianChange.sendChangeKey(call.uid, ['qjzzdhd', 'taskhd', 'huodonghd'])

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