import {ApiCall} from "tsrpc";
import {PlayerFun} from '../../../public/player';
import {ReqReceive, ResReceive} from "../../../shared/protocols/event/shouchong/PtlReceive";
import {PublicShared} from '../../../shared/public/public';
import {HongDianChange} from "../../hongdian/fun";
import {PayFun} from "../../../public/pay";

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

    let conf = G.gc.shouchong[call.req.k];
    if (!conf) return call.error(globalThis.lng.pata_getprize_1);

    let payLog = await PayFun.getPayLog(call.uid, conf.payid)
    if (!payLog) return call.errorCode(-1)

    let data = await G.mongodb.cEvent('shouchongzhigou').findOne({ uid: call.uid, type: 'shouchongzhigou' });

    let recArr = data?.receive?.[call.req.k] || [];

    // if (call.conn.gud.payExp < conf.paynum) return call.error(globalThis.lng.event_kfkh_9);

    if (recArr.length >= conf.prize.length) return call.error(globalThis.lng.event_kfkh_3);

    if (recArr.slice(-1)[0] && PublicShared.getToDayZeroTime() < recArr.slice(-1)[0]) return call.error(globalThis.lng.event_kfkh_10);

    await PlayerFun.sendPrize(call, conf.prize[recArr.length]);
    await G.mongodb.cEvent('shouchongzhigou').updateOne(
        { uid: call.uid, type: 'shouchongzhigou' },
        { $push: G.mongodb.createTreeObj({ key: 'receive', k: call.req.k, val: G.time }) },
        { upsert: true }
    );

    let recLen = data != null ? Object.values(data.receive).map(arr => arr.length).reduce((a, b) => a + b) + 1 : 1;
    let allLen = Object.values(G.gc.shouchong).map(conf => conf.prize.length as number).reduce((a, b) => a + b);
    if (data && recLen >= allLen) {
        G.mongodb.collection('syncBtns').updateOne({ uid: call.uid }, { $set: { 'shouchong.active': false } }, { upsert: true });
    }
    HongDianChange.sendChangeKey(call.uid, ['shouchong'])

    call.succ({
        prize: conf.prize[recArr.length]
    });
}

export async function getShouChongRedPoint(call: ApiCall) {
    // let data = await G.mongodb.cEvent('shouchong').findOne({ uid: call.uid, type: 'shouchong' });
    //
    // for (let [id, conf] of Object.entries(G.gc.shouchong)) {
    //     let rec = data?.receive?.[id] || [];
    //     if (call.conn.gud.payExp / 10 < conf.paynum || rec.length >= conf.prize.length) continue;
    //     if (rec.length == 0 || rec.slice(-1)[0] < PublicShared.getToDayZeroTime(G.time)) {
    //         res = { show: true };
    //         break;
    //     }
    // }

    return {show: false};
}