import {ApiCall} from "tsrpc";
import {ReqOpen, ResOpen} from "../../../shared/protocols/event/xiaofeijingsai/PtlOpen";
import {HuoDongFun} from "../../../public/huodongfun";

/**
 * 消费竞赛
 * redis缓存60秒
 * 返回活动日期内的
 * @param call
 */
export default async function (call: ApiCall<ReqOpen, ResOpen>) {

    let ioList = await G.crossioredis.get(`rank:xiaofeijingsai`);
    if (ioList) {
        let myData = await getMyData(call, JSON.parse(ioList))
        return call.succ({list: JSON.parse(ioList), myData})
    }

    let _hd = (await HuoDongFun.gethdList(call, 11))[0]
    if (!_hd) return call.errorCode(-1)

    let limit = _hd.data?.rank?.slice(-1)?.[0]?.rank?.slice(-1)?.[0] || call.req.limit || 100

    let rmbuse = await G.crossmongodb.collection('rmbuse').find({
        time: {
            $gte: _hd.stime,
            $lte: _hd.etime + 10
        }
    }).sort({change: 1}).limit(limit).toArray()

    let list: any = rmbuse.map(i => ({...i, total: R.negate(i.change)}))

    let rankList = sortRankList(_hd.data.rank, list)

    let users = await G.crossmongodb.collection('huodong_user').find({uid: {$in: rankList.map(i => i._id).filter(i => i._id != 'system')}}).toArray()

    rankList = rankList.map(i => ({...i, player: users.find(v => v.uid == i._id) || {}}))

    // 活动结束前半小时，缓存过期时间改为10秒
    let exTime = (G.time + 1800) > _hd.etime ? 10 : 60

    G.crossioredis.setex(`rank:xiaofeijingsai`, exTime, JSON.stringify(rankList));

    let myData = await getMyData(call, rankList)

    call.succ({list: rankList, myData})
}

/**
 * 需要满足消耗条件才能添加到排行榜，不满足的时候排行榜加system占位
 * @param rank
 * @param list
 */
export function sortRankList(rank, list) {
    let rankList = []
    let ccc = 0
    rank.map(i => {
        for (let k = i.rank[0] - 1; k < i.rank[1]; k++) {
            if (list[k]?.total >= i.need[0].n) {
                rankList.push({...list[k - ccc], rank: k})
            } else {
                rankList.push({_id: 'system', total: i.need[0].n, rank: k, player: {}})
                ccc += 1
            }
        }
    })
    return R.sort((a, b) => a.rank - b.rank)(rankList)
}

// 获取自己的信息
async function getMyData(call, rankList) {
    let myData = rankList.find(i => i._id == call.uid)
    if (myData) return myData

    let myCut: any = await G.crossmongodb.collection('rmbuse').findOne({uid: call.uid})

    let myUser = await G.mongodb.collection('user').findOne({uid: call.uid})
    G.crossmongodb.collection('huodong_user').updateOne({uid: call.uid}, myUser, {upsert: true})

    if (!myCut) {
        myCut = {_id: myUser.uid, total: 0}
    }

    return {player: myUser, ...myCut, total: R.negate(myCut.total), rank: -1}
}