import { ApiCall } from "tsrpc";
import { HuoDongFun } from "../../../public/huodongfun";
import { PayFun } from "../../../public/pay";
import { ReqOpen, ResOpen } from "../../../shared/protocols/event/chuanshuozhilu/PtlOpen";
import { player } from '../../../shared/protocols/user/type';
import { PublicShared } from '../../../shared/public/public';
import { Queue } from '../../../shared/public/queue';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    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 db = await G.mongodb.cEvent(`chuanshuozhilu${call.req.hdid}`).findOne({ uid: call.uid, type: `chuanshuozhilu${call.req.hdid}` });

    call.succ({
        info: db?.info || {},
        hdinfo: _hdinfo
    });
}

type P = Pick<ResOpen['info'][''], 'lv' | 'jieji'>;

const cache: k_v<k_v<P>> = {};
const quene = new Queue();

/**传说之路任务记录 */
export async function event_cszl_record(player: player, hid: string | number, v: number, type: 'lv' | 'jieji') {
    let call = await PayFun.getCall(player);
    // @ts-ignore    // 此活动的唯一标识 htype 为 3
    let _hdList = await HuoDongFun.gethdList(call, 3)
    for (let index = 0; index < _hdList.length; index++) {
        const element = _hdList[index];
        if (hid != element.data.hid) continue;

        quene.enqueue(async () => {
            let _dbType: `chuanshuozhilu${number}` = `chuanshuozhilu${element.hdid}`
            if (!cache[player.uid]) cache[player.uid] = (await G.mongodb.cEvent(_dbType).findOne({ uid: player.uid, type: _dbType }))?.info || {};
    
            if (!cache[player.uid][hid] || !cache[player.uid][hid][type] || cache[player.uid][hid][type] < v) {
                await G.mongodb.cEvent(_dbType).updateOne(
                    { uid: player.uid, type: _dbType },
                    { $set: G.mongodb.createTreeObj({ key: `info.${hid}.${type}`, val: v }) },
                    { upsert: true }
                );
            }
    
            if (!cache[player.uid][hid]) cache[player.uid][hid] = { lv: 0, jieji: 0 };
            if (cache[player.uid][hid][type] < v) cache[player.uid][hid][type] = v;
    
            G.server.sendMsgByUid(player.uid, 'msg_s2c/HongDianChange', ['huodonghd']);
        });

    }
}