import {ApiCall} from "tsrpc";
import {ReqReceive, ResReceive} from "../../shared/protocols/kaifujingsai/PtlReceive";
import {RankKfjs} from "../../public/rank/rank_kfjs";
import kfjsFun from "../../public/kaifujingsai";
import {PlayerFun} from "../../public/player";
import {HongDianChange} from "../hongdian/fun";

export default async function (call: ApiCall<ReqReceive, ResReceive>) {

    // 取奖励列表，判断是否有可领取奖励
    let prize = kfjsFun.getPrize(call.req.type)
    if (prize.length == 0) return call.errorCode(-1)

    let data = await G.mongodb.cEvent('kaifujingsai').findOne({uid: call.uid, type: 'kaifujingsai'})
    if (data?.record?.[call.req.type]) return call.errorCode(-2)

    // 查询自己排名，发奖
    let rankKfjs = RankKfjs(call.req.type)
    let myRank = await rankKfjs.getRankSortByOne(call.uid)

    let conf = R.find(i => i.rank[0] <= myRank + 1 && i.rank[1] >= myRank + 1)(prize)

    await PlayerFun.sendPrize(call, conf.prize);

    await G.mongodb.cEvent('kaifujingsai').updateOne({uid: call.uid, type: 'kaifujingsai'}, {
        $inc: {[`record.${conf.type}`]: 1}
    },{ upsert: true })

    call.succ({})

    HongDianChange.sendChangeKey(call.uid, ['kaifujingsai']);
}
