import { maxDependencies } from "mathjs";
import { ApiCall } from "tsrpc";
import { FightFun } from "../../public/fight";
import { LingZhuLaiXifun } from "../../public/lingzhulaixi";
import { PlayerFun } from "../../public/player";
import { ReqPkBoss, ResPkBoss } from "../../shared/protocols/lingzhulaixi/PtlPkBoss";
import { PublicShared } from "../../shared/public/public";
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqPkBoss, ResPkBoss>) {
    let _con = await LingZhuLaiXifun.getCon(call.req.bid)
    if (!_con) {
        // 参数错误，无相关配置
        return call.error('', { code: -1, message: globalThis.lng.lingzhulaixi_1 })
    }

    if (call.conn.gud.lv < _con.lv) {
        // 等级不足
        return call.error('', { code: -2, message: globalThis.lng.lingzhulaixi_2 })
    }

    // 个人数据
    let _myData = await LingZhuLaiXifun.getUsePKNum(call)
    let _maxNum = G.gc.com.PiratesFight_ChallengesNum.value
    if (_myData.num >= _maxNum) {
        // 挑战次数不足
        return call.error('', { code: -3, message: globalThis.lng.lingzhulaixi_3 })
    }

    // boss信息
    let _bossData = await LingZhuLaiXifun.getBossData(call.req.bid)
    if (_bossData.passtime != 0) {
        // boss 未复活
        return call.error('', { code: -4, message: globalThis.lng.lingzhulaixi_4 })
    }

    let _bossMaxHp = _bossData.maxhp
    let _bossDelHp = _bossData.delhp
    /**格式化boss属性 */
    let hpjc =  Number(((_bossMaxHp - _bossDelHp) / _bossMaxHp).toFixed(2)) || 0.01  // 继承血量比
    let _bossFightId = _con.army     // boss 战斗id
    let _npcFightData = await LingZhuLaiXifun.getBossFightInof(_bossFightId, Number(hpjc))
    // let _npcFightData = await LingZhuLaiXifun.getBossFightInof(25, Number(hpjc))   // 测试数据
    let _myFightData = await call.conn.getDefaultFightData()    // 我的战斗信息
    const result = FightFun.fight([_myFightData, _npcFightData])
    let _dlz: number[]     // 掉落组id
    let _setData
    let _mySetDat = {}
    if (_bossData.delhp + result.totalDamage[0] > _bossData.maxhp) {
        // 胜利
        _dlz = _con.kill_drop
        _setData = {               // 设置的数据
            $set: {
                pkuser: {},
                delhp: 0,
                maxhp: await LingZhuLaiXifun.getBossMapHp(_bossData.bid),
                passtime: _con.member * 60 + G.time,
                randusernum: 0
            }
        }
        Object.assign(_bossData, _setData["$set"])
        await G.mongodb.cPlayerInfo('lingzhulaixi').updateMany(
            { type: 'lingzhulaixi' },
            { $set: G.mongodb.createTreeObj({ key: `maxdps.${call.req.bid}`, val: 0 }) }
        )

    } else {
        // 超过回合，直接赋值输
        result.winSide = 1
        _dlz = _con.drop
        // 更新伤害数据
        if (!_bossData.pkuser[call.uid]) {
            _bossData.pkuser[call.uid] = 0
        }
        _bossData.pkuser[call.uid] += result.totalDamage[0]
        let pkNum = Object.keys(_bossData.pkuser).length   // 实际pk人数
        if (pkNum >= 3 && !(pkNum - 1 <= _bossData.randusernum && _bossData.randusernum <= 2 * pkNum)) {
            _bossData.randusernum = PublicShared.randomNum(pkNum - 1, 2 * pkNum)
        }
        _setData = {               // 设置的数据
            $inc: {
                delhp: result.totalDamage[0]
            },
            $set: {
                pkuser: _bossData.pkuser,
                randusernum: _bossData.randusernum
            }
        }
        // 放入伤害数据
        if (!_myData.maxdps[_bossData.bid] || _myData.maxdps[_bossData.bid] < result.totalDamage[0]) {
            _myData.maxdps[_bossData.bid] = result.totalDamage[0]
        }
        _mySetDat = {
            maxdps: _myData.maxdps,
            time: _myData.time,
            num: _myData.num + 1
        }
        _bossData.delhp += result.totalDamage[0]

    }
    // 设置boss数据
    await LingZhuLaiXifun.setBossData(_bossData.bid, _setData)
    await LingZhuLaiXifun.setMyData(call, { $set: _mySetDat })

    // 发奖
    let prize = PublicShared.mergePrize(await LingZhuLaiXifun.getPrize(_dlz))
    await PlayerFun.sendPrize(call, prize);

    // 扣除挑战次数
    _myData.num += 1

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

    call.succ({
        mydata: _myData,
        bossdata: _bossData,
        prize: prize,
        result: result
    });
}