import {ApiCall} from "tsrpc";
import {FightFun} from '../../public/fight';
import {PlayerFun} from '../../public/player';
import {ReqFind, ResFind} from "../../shared/protocols/conglinshoulie/PtlFind";
import {PublicShared} from '../../shared/public/public';
import {addStar, clslDb} from './ApiOpen';

export default async function (call: ApiCall<ReqFind, ResFind>) {
    let weekZeroTime = PublicShared.getToWeekMondayZeroTime();
    if (G.time < weekZeroTime + G.gc.clsl_com.fightTime[0] || G.time > weekZeroTime + G.gc.clsl_com.fightTime[1]) return call.errorCode(-1);

    let db = await clslDb().findOne({uid: call.uid, type: 'clsl'});
    let curStar = db?.allStar || 0;
    let useNum = db?.useFightNum || 0;
    let buyNum = db?.buyFightNum || 0;
    let starConf = G.gc.clsl_dan[curStar] || Object.values(G.gc.clsl_dan).slice(-1)[0];

    if (useNum >= buyNum + G.gc.clsl_com.fightNum) return call.errorCode(-2);

    let my = await call.conn.getDefaultFightData();
    let other = (await G.clientCross.callApi('clsl/FindEnemy', {uid: call.uid})).res;
    let result = FightFun.fight([my, other.info]);

    if ((result.winSide != 0 && starConf.failCut) || result.winSide == 0) {
        addStar(call, result.winSide == 0 ? 1 : -starConf.failCut, my);
    }

    result.initData[0].star = curStar
    result.initData[1].star = other.allStar

    result.winSide == 0 && clslDb().updateOne({uid: call.uid, type: 'clsl'}, {$inc: {fightWinNum: 1}});
    clslDb().updateOne({uid: call.uid, type: 'clsl'}, {$inc: {useFightNum: 1}});

    await PlayerFun.sendPrize(call, starConf.fightPrize);

    G.clientCross?.callApi('clsl/Log', {uid: call.uid, result: result});
    G.clientCross?.callApi('clsl/Log', {uid: other.info.player.uid, result: result});

    call.succ({
        enemy: other,
        result: result
    });
}