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

export default async function (call: ApiCall<ReqFight, ResFight>) {

    const res: ResFight = {
        result: null,
        change: {}
    };
    const data = await JJCFun.getData(call);
    // ### globalDebug JJCFun 查询传参uid的排名
    const enemy = await JJCFun.getPlayerData(call.req.uid)

    if (!enemy) return call.error(globalThis.lng.jjc_2, { code: 2 });
    if (data.useFightNum >= data.buyFightNum + G.gc.jjc_com.fightNum) return call.error(globalThis.lng.jjc_4);
    if (await JJCFun.getLockPlayer(call.req.uid)) return call.error(globalThis.lng.jjc_7, { code: 2 });

    await JJCFun.setLockPlayer(enemy.player.uid, true);
    await JJCFun.setLockPlayer(call.uid, true);

    let result = res.result = await FightFun.fightJJc(call, enemy);

    if (result.winSide == 0) {
        res.prize = G.gc.jjc_com.fightWinPrize;
        await PlayerFun.sendPrize(call, G.gc.jjc_com.fightWinPrize);
        JJCFun.addRankInfo({ player: call.conn.gud }, enemy);
        res.change.recordWin = (data.recordWin || 0) + 1;
    }

    await JJCFun.getLockPlayer(enemy.player.uid);
    await JJCFun.getLockPlayer(call.uid);

    let userRank = await JJCFun.getRankSortByUid(call.uid)
    let enemyRank = await JJCFun.getRankSortByUid(enemy.player.uid)
    result.otherData = {userRank,enemyRank}

    JJCFun.saveFightLog(call.uid, result);
    JJCFun.saveFightLog(enemy.player.uid, result);

    res.change.useFightNum = data.useFightNum + 1;
    Object.assign(res.change, await JJCFun.randomEnemy(call.uid));

    JJCFun.changeData(call, res.change);
    HongDianChange.sendChangeKey(call.uid, ['jjchd', 'taskhd', 'huodonghd']);

    // (await call.conn.gonghui)?.addExp(5, call.uid);

    call.succ(res);

    await JJCFun.setLockPlayer(enemy.player.uid, false);
    await JJCFun.setLockPlayer(call.uid, false);

}