-- 寻星礼包
-- 逻辑：每日每种礼包有一定限购次数, 跨天后重置

local Msg = require("core.Msg")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local BuyLogic = require("topup.BuyLogic")
local ZhuanpanGiftConfig = require("excel.zhuanpan").gift
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")

local LOGTAG = "zhuanpanGift"


local function getCfg(buyId)
    for _, v in ipairs(ZhuanpanGiftConfig) do
        if buyId == v.buyID then
            return v
        end
    end
end


function ZhuanpanGift_Query(human)
    local zhuanpanGiftData = human.db.zhuanpanGiftData

    local msgRet = Msg.gc.GC_ZHUANPAN_GIFT_QUERY
    local giftArr = msgRet.giftArr
    giftArr[0] = 0

    for k, v in ipairs(ZhuanpanGiftConfig) do
        giftArr[0] = k
        giftArr[k].nowBuyCnt = zhuanpanGiftData and zhuanpanGiftData[v.buyID] or 0
        giftArr[k].maxBuyCnt = v.amount
        BuyLogic.fontBuyItem(human, giftArr[k].buyItem, v.buyID)

        giftArr[k].giftItem[0] = #v.rewards
        for idx, itemCfg in ipairs(v.rewards) do
            Grid.makeItem(giftArr[k].giftItem[idx], itemCfg[1], itemCfg[2])
        end
    end

    Msg.send(msgRet, human.fd)
end


function updateDaily(human)
    human.db.zhuanpanGiftData = nil
    ZhuanpanGift_Query(human)
end


function onCharge(human, buyId, buyNum)
    local zhuanpanGiftData = human.db.zhuanpanGiftData

    local giftCfg = getCfg(buyId)
    if not giftCfg then
        return Broadcast.sendErr(human, Lang.COMMON_COMFIG_ERROR)
    end

    -- if zhuanpanGiftData and (zhuanpanGiftData[buyId] or 0) >= giftCfg.amount then
    --     return
    -- end

    -- if buyNum + (zhuanpanGiftData[buyId] or 0) >= giftCfg.amount then
    --     return
    -- end

    if buyNum + (zhuanpanGiftData and zhuanpanGiftData[buyId] or 0) > giftCfg.amount then
        return Broadcast.sendErr(human, Lang.ABS_GIFT_BUY_LIMIT)
    end

    local itemArr = {}
    for idx, itemCfg in ipairs(giftCfg.rewards) do
        -- itemArr[idx] = {itemCfg[1], itemCfg[2]}
        itemArr[idx] = {itemCfg[1], itemCfg[2] * buyNum}
    end

    BagLogic.addItemList(human, itemArr, LOGTAG)

    zhuanpanGiftData = zhuanpanGiftData or {}
    -- zhuanpanGiftData[buyId] = (zhuanpanGiftData[buyId] or 0) + 1
    zhuanpanGiftData[buyId] = (zhuanpanGiftData[buyId] or 0) + buyNum
    human.db.zhuanpanGiftData = zhuanpanGiftData

    ZhuanpanGift_Query(human)
end

function GetRemainNum(human, nBuyID)
    local giftCfg = getCfg(nBuyID)

    if not giftCfg then
        return 0
    end

    local zhuanpanGiftData = human.db.zhuanpanGiftData
    if not zhuanpanGiftData or not zhuanpanGiftData[nBuyID] then
        return giftCfg.amount
    end

    return (giftCfg.amount > zhuanpanGiftData[nBuyID]) and (giftCfg.amount - zhuanpanGiftData[nBuyID]) or 0
end