import { ApiCall } from "tsrpc";
import { ReqFindEnemy, ResFindEnemy } from "../../cross/protocols/clsl/PtlFindEnemy";
import { formatNpcData } from '../../shared/fightControl/fightFun';
import { PublicShared } from "../../shared/public/public";

export default async function (call: ApiCall<ReqFindEnemy, ResFindEnemy>) {
    let p = PublicShared.randomNum(1, 1000);
    let starConf = getStarConf(call.req.myStasr);

    let enemy: { allStar: number, info: any };

    // 本次随机到npc概率判断
    if (p <= starConf.pro * 1000) {
        enemy = {
            allStar: call.req.myStasr,
            info: formatNpcData(starConf.npc)
        }
    } else {
        // 在自定范围内随机一个对手
        let others = await G.mongodb.collection("clslCrossUser").aggregate([
            {
                $match: {
                    allStar: { $gte: starConf.fighter[0], $lte: starConf.fighter[1] }
                }
            }, {
                $sample: { size: 1 }
            }

        ]).toArray();

        if (others.length <= 0) {
            enemy = {
                allStar: call.req.myStasr,
                info: formatNpcData(starConf.npc)
            }
        } else {
            enemy = {
                allStar: others[0].allStar,
                info: others[0].info,
            }
        }
    }

    call.succ({
        allStar: enemy.allStar,
        info: enemy.info || formatNpcData(starConf.npc)
    });
}

const endConf = Object.values(G.gc.clsl_dan).slice(-1)[0];

function getStarConf(star = 0) {
    return G.gc.clsl_dan[star] || endConf;
}