import math from "mathjs";
import { ApiCall } from "tsrpc";
import { FightFun } from '../../public/fight';
import { PlayerFun } from '../../public/player';
import { ReqFight, ResFight } from "../../shared/protocols/gonglukuangbiao/PtlFight";
import { PublicShared } from '../../shared/public/public';
import { HongDianChange } from "../hongdian/fun";

export default async function (call: ApiCall<ReqFight, ResFight>) {
    let conf = G.gc.gonglukuangbiao.config[call.req.index];
    if (!conf) return call.error('', { code: -1 });

    let db = await G.mongodb.collection('wanted').findOne({ uid: call.uid });
    if (db.toDayUseNum >= G.gc.gonglukuangbiao.fightNum + db.toDayBuyNum) return call.error('', { code: -2 });

    let enemy = db.enemys[call.req.index];
    let result = FightFun.fight([await call.conn.getDefaultFightData(), enemy]);
    let res: ResFight = { result: result };
    let addWanted = 0;

    let _wanted = enemy["wanted"] || 0;
    let _indexConf = Object.values(G.gc.gonglukuangbiao.wanted).filter(e => e.wanted[0] <= _wanted && _wanted <= e.wanted[1]);
    if (!_indexConf) return call.error('', { code: -2 });
    let _qdSuccess: boolean = false
    let _prize: atn[]

    if (result.winSide == 0) {
        let lv = enemy.player.lv
        _prize = [{ a: "attr", t: "jinbi", n: Math.floor(eval(_indexConf[0].jinbi)) }]

        let _fA = Math.max(0, 1 - (db?.toDayBeiFightNum || 0) * 0.1)
        let _fB = 1 - (Math.max(0, Number(((call.conn.gud.lv - enemy.player.lv) * 0.1).toFixed(1))))
        let _qdPro = Math.max(_indexConf[0].fightsppro[1], _indexConf[0].fightsppro[0] * _fA * _fB)
        _qdSuccess = PublicShared.randomNum(1, 100) > _qdPro ? false : true
        // npc
        if (enemy.player.isNpc && _qdSuccess) {
            _prize = _prize.concat(G.gc.gonglukuangbiao.drop1.map(dlz => PublicShared.randomDropGroup(dlz)).reduce((a, b) => a.concat(b)))
        }

        if (!enemy.player.isNpc) {
            if (_qdSuccess) {
                let _userSP = await G.mongodb.collection('item').find({ uid: enemy.player.uid, itemId: { $in: G.gc.gonglukuangbiao.qdusersp } }).toArray()
                _qdSuccess = _userSP && _userSP.length > 0 ? true : false
                if (_qdSuccess) _prize = _prize.concat([{ a: "item", t: _userSP.random().itemId, n: 1 }])
            }
            G.mongodb.collection('wanted').findOne({ uid: enemy.player.uid }).then(db => {
                let w = db.wanted - 2 < 0 ? 0 : db.wanted - 2;
                let num = db?.toDayBeiFightNum ? (db?.toDayBeiFightNum + 1) : 1
                G.mongodb.collection('wanted').updateOne({ uid: enemy.player.uid }, { $set: { wanted: w, toDayBeiFightNum: num } });
            });

        }

        // addWanted = conf.killHonor;
        // if (enemy.player.isNpc || call.conn.gud.lv - enemy.player.lv <= 10) {
        //     let winNum = db.toDayWin[call.req.index] * 10;
        //     let round = conf.round.default - winNum < conf.round.min ? conf.round.min : conf.round.default;
        //     let isRound = PublicShared.randomNum(1, 100) <= round;
        //     let dropArr = isRound ? G.gc.gonglukuangbiao.drop1 : G.gc.gonglukuangbiao.drop2;
        //     if (dropArr.length > 0) {
        //         let prize = dropArr.map(id => PublicShared.randomDropGroup(id)).reduce((a, b) => a.concat(b));
        //         prize = PublicShared.mergePrize(prize);
        //         res.prize = prize;
        //         await PlayerFun.sendPrize(call, prize);
        //     }
        // }

        // if (!enemy.player.isNpc) {
        //     G.mongodb.collection('wanted').findOne({ uid: enemy.player.uid }).then(db => {
        //         let w = db.wanted - 2 < 0 ? 0 : db.wanted - 2;
        //         G.mongodb.collection('wanted').updateOne({ uid: enemy.player.uid }, { $set: { wanted: w } });
        //     });
        // }

        G.mongodb.collection('wanted').updateOne({ uid: call.uid }, { $inc: G.mongodb.createTreeObj({ key: `toDayWin.${_indexConf[0].index}`, val: 1 }) });
        _prize && await PlayerFun.sendPrize(call, _prize);
    }

    addWanted = _qdSuccess ? _indexConf[0].spwanted : _indexConf[0].addwanted
    G.mongodb.collection('wanted').updateOne({ uid: call.uid }, { $inc: { wanted: addWanted, toDayUseNum: 1 } });

    HongDianChange.sendChangeKey(call.uid, ['taskhd', 'huodonghd'])
    res.prize = _prize || []
    call.succ(res);
}