import { ApiCall } from "tsrpc";
import { ActionLog } from '../../../public/actionLog/actionLog';
import { HuoDongFun } from "../../../public/huodongfun";
import { PlayerFun } from '../../../public/player';
import { ReqRecPrize, ResRecPrize } from "../../../shared/protocols/event/qiridenglu/PtlRecPrize";
import { HongDianChange } from "../../hongdian/fun";

export default async function (call: ApiCall<ReqRecPrize, ResRecPrize>) {
    let _hdinfo = await HuoDongFun.getHdidInfo(call, call.req.hdid)
    if (!_hdinfo || Object.keys(_hdinfo).length <= 0) {
        // 无此活动
        return call.error('', { code: -1, message: globalThis.lng.huodong_open_1 })
    }
    let conf = _hdinfo.data.arr
    let _dbType: `qiridenglu${number}` = `qiridenglu${call.req.hdid}`


    let recIndex = call.req.inedx;
    if (!conf[recIndex]) return call.error('', { code: -1 });

    let day = await ActionLog.getRetainLog(call.uid, `login_day_qiridenglu_${call.req.hdid}`);
    if (conf[recIndex].day > day) return call.error('', { code: -2 });

    let db = await G.mongodb.cEvent(_dbType).findOne({ uid: call.uid, type: _dbType });
    if (db?.recPrize?.includes(recIndex)) return call.error('', { code: -3 });

    await PlayerFun.sendPrize(call, conf[recIndex].prize);
    G.mongodb.cEvent(_dbType).updateOne(
        { uid: call.uid, type: _dbType },
        { $push: { recPrize: recIndex } },
        { upsert: true }
    );
    
    // 此活动可能有多个，此检测似乎不合适，先屏蔽
    // if (db?.recPrize?.length + 1 >= conf.length) {
    //     G.mongodb.collection('syncBtns').updateOne({ uid: call.uid }, { $set: { 'qiridenglu.active': false } }, { upsert: true });
    // }

    HongDianChange.sendChangeKey(call.uid, ['huodonghd'])

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