import { ApiCall } from "tsrpc";
import { ReqGetEnemy, ResGetEnemy } from "../../../cross/protocols/hbzb/jfs/PtlGetEnemy";
import { Rank } from '../../../public/rank/rank';
import { formatNpcData } from '../../../shared/fightControl/fightFun';
import { PublicShared } from "../../../shared/public/public";
import { rankInfo } from "../../../shared/protocols/type";
import { getWinScore } from "../../../api_s2c/hbzb/jfs/fun";

export default async function (call: ApiCall<ReqGetEnemy, ResGetEnemy>) {
    // // TODO ### debug allPlayer����������
    // let allPlayers:rankInfo[] = <rankInfo[]>await Rank.list.hbzbCross.getRankListRange();
    // let user:rankInfo = <rankInfo>await Rank.list.hbzbCross.getRankData(call.req.uid);
    // if(!user?.player) {
    //     // 写入默认参数到数据库
    //     user = {
    //         player: call.req.gud,
    //         valArr: [1000]
    //     }
    //     await Rank.list.hbzbCross.addNew(user)
    // }
    // if(!user?.player) return call.succ({ enemy: [] });

    let user = await G.mongodb.findOne('hbzb_user_cross', { uid: call.req.uid });
    if(!user){
        //玩家不存在
        return call.error('', { code: -1, message: 'user is null' })
    }

    let conf = G.gc.hbzb.jfsMatchingHand;
    let rang = conf.map(val => {
        return [PublicShared.eval(val.min, { zhanli: user.data.player.power }), PublicShared.eval(val.max, { zhanli: user.data.player.power })] as [number, number];
    });
    /**
    0:[1029550, 1489437]
    1:[936254, 1302845]
    2:[656366, 1116254]
     */
    let enemy =[];
    //已经刷到过的uid
    let blackUids = [call.req.uid];

    for(let i=0;i<rang.length;i++){
        let r = rang[i];
        let randRs = await G.mongodb.collection('hbzb_user_cross').aggregate([
            {
              $match: {
                $and: [
                  {"data.player.power": {$gte: r[0]}},
                  {"data.player.power": {$lte: r[1]}},
                  {uid: {$nin: blackUids}}
                ]
              }
            },
            { $sample: { size: 1 } }
        ]).toArray();
        
        
        
        if (randRs.length>0) {
            blackUids.push(randRs[0].uid);
            let score = getWinScore(user.data.player.power,randRs[0].data.player.power);

            enemy[i] = {
                data: {
                    player: randRs[0].data.player,
                    roles: randRs[0].data.roles
                },
                //这里的积分，只是战斗胜利时增加的积分
                jifen: score 
            };
        } else {
            let npcData = getNpc(user.data.player.lv, i);
            let score = getWinScore(user.data.player.power,npcData.player.power);
            enemy[i] = {
                data: npcData,
                jifen: score
            };;
        }
    }
    
    call.succ({ enemy: enemy });

    
    // let min = rang.slice(-1)[0][0];
    // let max = rang[0][1];
    // let players = allPlayers.filter(p => {
    //     return p.player.power >= min && p.player.power <= max && p.player.uid != call.req.uid;
    // });
    // let select: string[] = [];
    // let enemy = rang.map((r, index) => {
    //     let es = players.filter(p => p.player.power >= r[0] && p.player.power <= r[1] && !select.includes(p.player.uid));
    //     if (es.length > 0) {
    //         let ops = es.random();
    //         players.removeOne(x => x.player.uid == ops.player.uid); // 删除已经出现的对手，避免重复刷到。
    //         if(ops) {
    //             let data:any = {
    //                 data: {
    //                     player: ops.player,
    //                     roles: ops.roles
    //                 },
    //                 jifen: ops.valArr[0]
    //             }
    //             return data;
    //         }
    //     } else {
    //         return {
    //             data: getNpc(user.player.lv, index),
    //             jifen: 1000
    //         };
    //     }
    // });
    //call.succ({ enemy: enemy });
}

function getNpc(lv: number, index: number) {
    let rang = G.gc.hbzb.jfsRefreshNpcId.find(v => lv >= v.lvs[0] && lv <= v.lvs[1]);
    let res = formatNpcData(rang.npcs[index].random())
    return res;
}