import { ApiCall } from "tsrpc";
import { FightFun } from '../../../public/fight';
import { PlayerFun } from '../../../public/player';
import { Rank } from '../../../public/rank/rank';
import { ReqFight, ResFight } from "../../../shared/protocols/hbzb/jfs/PtlFight";
import { PublicShared } from '../../../shared/public/public';
import { HongDianChange } from "../../hongdian/fun";
import { checkIsOpen } from './ApiOpen';
import { getMyRank, getWinScore } from "./fun";

export default async function (call: ApiCall<ReqFight, ResFight>) {
    if (!checkIsOpen()) return call.error(globalThis.lng.hbzb_7);
    let dbData = await G.mongodb.cPlayerInfo('hbzb').findOne({ uid: call.uid, type: 'hbzb' });
    let data = dbData.data;

    if (data.useFightNum >= data.buyFightNum + G.gc.hbzb.jfsFightNum) return call.errorCode(-3);

    let enemy = data.enemy.find(e => e.data.player.uid == call.req.uid);
    if (!enemy) return call.errorCode(-2);
    if (enemy.result != null) return call.errorCode(-1);

    let myData = await call.conn.getDefaultFightData();
    let result = FightFun.fight([myData, enemy.data]);
    enemy.result = result.winSide;

    //通过双方战力计算得分
    
    // let myMaxPower = call.conn.gud?.maxpower || call.conn.gud?.power;
    // let enemyMaxPower = enemy.data.player.maxpower || enemy.data.player.power;
    // let score = getWinScore(myMaxPower,enemyMaxPower);
    // let addJf = score;//PublicShared.randomNum(30, 35);

    //刷出怪的时候，已算过一次积分了，如果这里取当前gud重算积分，可能会导致
    //实际获得的积分跟提前看到的积分不一致
    //所以，这里增加的积分，直接以enemy里刷出来时的积分为准
    
    let addJf = enemy.jifen;
    if (result.winSide == 0){
        addJf = addJf;
    }else{
        //输了给一半
        addJf = Math.ceil(addJf*0.5);
    }

    // result.winSide == 0 && Rank.list.hbzbLocal.addNew({
    //     ...myData,
    //     valArr: [data.jifen + addJf]
    // });

    //let prize = result.winSide == 0 ? G.gc.hbzb.jfsFightWinPrize.map(i => { return { ...i, n: addJf }; }) : [];

    //无论输赢都给
    let prize = G.gc.hbzb.jfsFightWinPrize.map(i => { return { ...i, n: addJf }; });
    await PlayerFun.sendPrize(call, prize);

    let change: ResFight['change'] = { enemy: data.enemy, useFightNum: data.useFightNum + 1, jifen: data.jifen + addJf };
    if (data.enemy.filter(e => e.result === 0).length == 3) {
        let callRes = await G.clientCross.callApi('hbzb/jfs/GetEnemy', { uid: call.uid, auto: true });
        change.enemy = callRes.res.enemy.map(e => { return { ...e, result: null }; });
    }

    await G.mongodb.cPlayerInfo('hbzb').updateOne(
        { uid: call.uid, type: 'hbzb' },
        { $set: { 'data.enemy': change.enemy, 'data.useFightNum': change.useFightNum, 'data.jifen': change.jifen }, $inc: { 'data.winNum': result.winSide == 0 ? 1 : 0 } }
    );

    G.clientCross.sendMsg('msg_cross/HbzbJfsLog', {
        uid: call.conn.uid,
        toUid: enemy.data.player.uid,
        log: result
    });

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

    call.succ({
        result: result,
        prize: prize,
        change: {
            ...change,
            rank: await getMyRank(call.uid)
        }
    });
}