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

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

    // 查询活动是否是可领取状态
    let _hd = (await HuoDongFun.gethdList(call, 10))[0]

    let prize = [];
    let update = {};
    // 判断活动是否是最后一天
    if (PublicShared.chkSameDate(G.time, _hd.etime)) {
        let data = await G.mongodb.cEvent(`pobinglibao${_hd.hdid}`).findOne(
            { uid: call.uid, type: `pobinglibao${_hd.hdid}` }
        );

        for (let gift of _hd.data.gift) {
            // 查询购买状态
            let push = [];
            let payLog = await PayFun.getPayLog(call.uid, gift.payId)
            payLog = payLog?.filter(i => i.time >= _hd.stime && i.time <= _hd.etime) || []
            if (!payLog || !payLog.length) continue;

            for (let key of ["prize", "recPrize1", "recPrize2"]) {
                if (!data.record[gift.id] || !data.record[gift.id].includes(key)) {
                    push.push(key);
                    prize.push(...gift[key]);
                }
            }
            
            if (push.length > 0) {
                if (update["$push"]) {
                    update["$push"]["record." + gift.id] = { $each: push }
                } else {
                    update["$push"] = { ["record." + gift.id]: { $each: push } }
                }
            }
        }

        if (!prize.length) {
            return call.errorCode(-3)
        }
    } else {
        let gift = _hd?.data?.gift?.find(i => i.id == call.req.id);
        if (!gift || !call.req.recId) return call.errorCode(-1);

        // 查询购买状态
        let payLog = await PayFun.getPayLog(call.uid, gift.payId)
        payLog = payLog?.filter(i => i.time >= _hd.stime && i.time <= _hd.etime) || []

        if (!payLog || !payLog.length) return call.errorCode(-2);

        /**
         * 取奖励列表，判断是否有可领取奖励
         * 购买日起，每种礼包每天可领一次礼包，每种类型独立
         * 活动结束前的最后一天，可领取所有奖励
         */
        let data = await G.mongodb.cEvent(`pobinglibao${_hd.hdid}`).findOne(
            { uid: call.uid, type: `pobinglibao${_hd.hdid}` }
        )

        let rec = data?.record?.[call.req.id]?.length

        let _payDiff = PublicShared.getDiff(payLog[0].time)
        _payDiff = _payDiff > 3 ? 3 : _payDiff

        if (rec >= _payDiff || data?.record?.[gift.id] == call.req.recId) return call.errorCode(-3)

        prize.concat(gift[call.req.recId]);
        update = {
            $push: { [`record.${gift.id}`]: call.req.recId },
        }
    }

    await PlayerFun.sendPrize(call, prize);

    await G.mongodb.cEvent(`pobinglibao${_hd.hdid}`).updateOne(
        { uid: call.uid, type: `pobinglibao${_hd.hdid}` }, update, { upsert: true }
    );

    call.succ({ prize: prize });

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