import { ApiCall } from "tsrpc";
import { g123_response_hdinfo_details, g123_response_hdinfo_details_accountingData, g123_response_hdinfo_details_taowa, Reqdetails, Resdetails } from "../../monopoly/protocols/hdinfo/Ptldetails";
import { HuoDongFun } from "../../public/huodongfun";
import { PayFun } from "../../public/pay";

export default async function (call: ApiCall<Reqdetails, Resdetails>) {
    let _where = call.req.uid ? { uid: call.req.uid } : {}

    // 无玩家  随便取一个玩家
    let gud = await G.mongodb.collection('user').findOne(_where);
    if (!gud) {
        return call.error('', { code: 1002, message: globalThis.lng.wuciwanjia });
    }
    let rescall = PayFun.getCall(gud);

    // 构造返回值
    let _data: g123_response_hdinfo_details[] = []

    // 目前游戏只有游戏 5 符合查询要求
    // @ts-ignore
    let _hds = await HuoDongFun.gethdList(rescall, 5)
    for (let index = 0; index < _hds.length; index++) {
        const element = _hds[index];

        let _dbType: `leijichongzhi${number}` = `leijichongzhi${element.hdid}`
        let _users = await G.mongodb.cEvent(_dbType).find({ type: _dbType }).toArray();

        let accountingData: g123_response_hdinfo_details_accountingData[] = []
        for (let index = 0; index < _users.length; index++) {

            const elementUser = _users[index];
            let _tmp = {
                ranking: index,
                participantId: elementUser.uid,
                value: await (await PayFun.getPayDaysAllPayNum(elementUser.uid, element.stime, element.etime)).toString()
            }
            accountingData.push(_tmp)
        }

        // 排序
        accountingData = accountingData.sort((b, a) => Number(a.value) - Number(b.value))
        accountingData.forEach((ele, index) => {
            ele.ranking = index + 1
        })

        let _pushiTmp: g123_response_hdinfo_details_taowa[] = []
        _pushiTmp.push({
            eventId: element.hdid.toString(),
            eventName: element.name,
            serverId: G.config.serverId,
            accountingTime: element.rtime * 1000,
            accountingData: accountingData
        })
        _data.push({
            total: index + 1,
            elemengts: _pushiTmp
        })
    }

    call.succ({ status: 0, message: "success", data: _data });
}