import {ApiCall} from "tsrpc";
import {GHManage} from '../../public/gonghui/manage';
import {ReqGetList, ResGetList} from "../../shared/protocols/gonghui/PtlGetList";

async function getGongHuiZhanli(ghId:string):Promise<number>{
    //如果redis里有，则直接返回
    let zhanliRes = await G.ioredis.get(`gongHuiZhanLi:${ghId}`);
    if(zhanliRes){
        return parseInt(zhanliRes);
    }

    let GHData = await GHManage.getGHList();
    let ghs = Object.values(GHData).map(item => item.data).filter(i => !!i.players);
    let fuids = R.flatten(ghs.map(i => i.players.map(j => j.uid)))
    let allRoles = await G.mongodb.find('user',{uid: {$in: fuids}},['uid','power'])
    let zhanlis = Object.fromEntries(allRoles.map(r => [r.uid, r.power]));

    
    for (let gh of ghs) {
        let uids = gh.players.map(p => p.uid);
        let zhanli = uids.map(u => (zhanlis[u] || 0)).reduce((a, b) => a + b);
        //重设redis的值，有效期1小时
        G.ioredis.setex(`gongHuiZhanLi:${gh._id}`,3600, zhanli);

        if(gh._id == ghId){
            zhanliRes = zhanli;
        }
    }

    return parseInt(zhanliRes||"0");
}

export default async function (call: ApiCall<ReqGetList, ResGetList>) {

    let arr: ResGetList['list'] = [];
    let GHData = await GHManage.getGHList();
    let ghs = Object.values(GHData).map(item => item.data).filter(i => !!i.players);
    // let fuids = R.flatten(ghs.map(i => i.players.map(j => j.uid)))
    // let allRoles = await G.mongodb.find('user',{uid: {$in: fuids}},['uid','power'])
    // let zhanlis = Object.fromEntries(allRoles.map(r => [r.uid, r.power]));
    for (let gh of ghs) {
        //let uids = gh.players.map(p => p.uid);
        //let zhanli = uids.map(u => (zhanlis[u] || 0)).reduce((a, b) => a + b);
        let zhanli = await getGongHuiZhanli(gh._id);
        arr.push({
            gh: gh,
            zhanli: zhanli
        });
    }

    call.succ({
        list: arr
    });
}