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({type: `xfjs_${G.huodong.xfjsId}`}).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 != 'system')}}).toArray()

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

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

    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 = []
    rank.map(i => {
        for (let k = i.rank[0] - 1; k < i.rank[1]; k++) {
            if (list[0]?.total >= i.need[0].n) {
                rankList.push({...list[0], rank: k, _id: list[0].uid})
                list = R.tail(list)
            } else {
                rankList.push({_id: 'system', total: i.need[0].n, rank: k, player: {}})
            }
        }
    })
    return R.sort((a, b) => a.rank - b.rank)(rankList)
}

// 获取自己的信息
async function getMyData(call: ApiCall, 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,
        type: `xfjs_${G.huodong.xfjsId}`
    })

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

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

    return {player: myUser, ...myCut, total: R.negate(myCut.change) || 0, rank: -1, _id: myUser.uid}
}