import {ApiCall} from "tsrpc";
import {FriendManage} from '../../public/friend/manage';
import {ReqList, ResList} from "../../shared/protocols/friend/PtlList";
import {player} from "../../shared/protocols/user/type";

export default async function (call: ApiCall<ReqList, ResList>) {
    const my = await FriendManage.getFriend(call.uid);
    var res:player[] = []
    switch (call.req) {
        case 'tuijian':
            let noFindList = [...my.data.friendList, ...my.data.blacklist, call.uid]
            res = <player[]> await G.mongodb.collection('user').aggregate([
                {$match: {uid: {$nin: noFindList}}},
                {$sample: {size: G.gc.friend.tuijianNum}}
            ]).toArray();
            break;
        case 'friend':
            res = (await G.mongodb.find('user',{uid:{$in:my.data.friendList}})) as any;
            break;
        case 'apply':
            // 预防申请列表出现脏数据（过滤已添加好友）
            res = (await G.mongodb.find('user',{uid:{$in: my.data.applyList.filter(uid => my.data.friendList.indexOf(uid) == -1) }})) as any
            break;
        case 'black':
            res = (await G.mongodb.find('user',{uid:{$in: my.data.blacklist}})) as any;
            break;

    }
    // 排序：在线 > 离线时间
    res.sort((a, b) => {
        let x = a.loginTime > a.logoutTime ? 1 : a.logoutTime
        let y = b.loginTime > b.logoutTime ? 1 : b.logoutTime
        return x - y
    })
    return call.succ(res)
}




