-- 送万元充值活动
-- 每个挡位礼包数量有限，全区共享

--db
--[=[
    human.db.levelGift = {
        record = nil, -- 领取记录, key为配置中的id
    }

]=]--

local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local LevelGiftCfg = require("excel.WanYuanReward").Sheet1
local YunYingLogic = require("yunying.YunYingLogic")
local CommonDB = require("common.CommonDB")
local CommonDefine = require("common.CommonDefine")
local YunYingExcel = require("excel.yunying")

local LOGTYPE = "LevelGift"
local ENTRANCE_ACT_ID = 36
local ACT_ID = 7601

local MAXNUM = 10000 --总额度


local function initData(human)
    human.db.levelGift = {}
    human.db.levelGift.record = {}
end

local function getData(human)
    return human.db.levelGift
end

local function updateData(human, idx)
    local levelGiftData = getData(human)
    if not levelGiftData then
        initData(human)
        levelGiftData = getData(human)
    end

    levelGiftData.record[idx] = true
end



-- 获取本服所有道具的领取记录
local function getItemSrvRecord()
    local recordList = CommonDB.getValueByKey(CommonDB.KEY_LEVELGIFT_GETRECORD)
    return recordList
end

-- 获取本服某个道具已经领取数量
local function getItmGetNum(idx)
    local num = 0
    local recordList = getItemSrvRecord()
    if recordList and recordList[idx] then
        num = recordList[idx]
    end

    return num
end

-- 更新本服某个道具的领取数量
local function updateItemRemaindeNum(idx)
    local recordList = getItemSrvRecord()
    recordList = recordList or {}
    recordList[idx] = (recordList[idx] or 0) + 1
    CommonDB.updateValue(CommonDB.KEY_LEVELGIFT_GETRECORD, recordList)
end

-- 更新本服多个道具的领取数量
local function updateItemsRemaindeNum(newRecordList)
    CommonDB.updateValue(CommonDB.KEY_LEVELGIFT_GETRECORD, newRecordList)
end

-- 计算已经领取的额度
local function calcGetWeight(human)
    local weight = 0
    local levelGiftData = getData(human)
    local recordData = levelGiftData and levelGiftData.record

    for idx in pairs(recordData or {}) do
        local cfg = LevelGiftCfg[idx]
        if cfg then
            weight = weight + cfg.count
        end
    end

    return weight
end


-- 获取道具状态
local function getAwardState(human, idx, giftCfg)
    local levelGiftData = getData(human)
    local recordData = levelGiftData and levelGiftData.record

    local state = CommonDefine.COMMON_PRIZE_STATE_NOGET
    if recordData and recordData[idx] then
        state = CommonDefine.COMMON_PRIZE_STATE_GET
    else
        if human.db.lv >= giftCfg.lv then
            -- local num = getItmGetNum(idx)
            local num = calcGetWeight(human)
            if giftCfg.count + num <= MAXNUM then
                state = CommonDefine.COMMON_PRIZE_STATE_CANGET
            end
        end
    end

    return state
end

-- 获取所有奖励的剩余份数
local function getItemsSubNum()
    local getNum, totalNum = 0,0

    for idx, v in ipairs(LevelGiftCfg) do
        getNum = getNum + getItmGetNum(idx)
        totalNum = totalNum + v.count
    end

    return math.max(totalNum-getNum, 0)
end

-- 填充协议
local function populateGiftMsg(human, net, idx, giftCfg)
    net.itemArr[0] = 0
    net.state = 0
    net.levelCond = 0
    -- net.remaindeNum = 0
    
    net.itemArr[0] = #giftCfg.reward
    for i, itemInfo in ipairs(giftCfg.reward) do
        Grid.makeItem(net.itemArr[i], itemInfo[1], itemInfo[2])
    end

    net.levelCond = giftCfg.lv
    net.state = getAwardState(human, idx, giftCfg)
    -- local num = getItmGetNum(idx)
    -- net.remaindeNum = math.max(giftCfg.count - num, 0)
end

-- 是否显示入口。没有能领取的奖励后关闭，如果奖励没领完且奖励份数>=1则不关闭
-- 新修改: 额度不足则关闭
local function isShowEntrance(human)
    local levelGiftData = getData(human)
    local recordData = levelGiftData and levelGiftData.record or {}

    local getWeight = calcGetWeight(human)
    if getWeight >= MAXNUM then
        return false
    end

    for idx, v in ipairs(LevelGiftCfg) do
        local state = getAwardState(human, idx, v)
        if state == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            return true
        end

        if not recordData[idx] then
            -- local num = getItmGetNum(idx)
            -- if num < v.count then
            --     return true
            -- end
            if v.count + getWeight <= MAXNUM then
                return true
            end
        end
    end

    return false
end

-- 是否有可领取奖励
local function isCanGet(human)
    for idx, v in ipairs(LevelGiftCfg) do
        local state = getAwardState(human, idx, v)
        if state == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            return true
        end
    end

    return false
end

-- 主动刷新一次红点
local function updateRedDot(human)
    local config = YunYingExcel.func[ACT_ID]
    YunYingLogic.sendGroupUpdate(YYInfo[ACT_ID], human, config.panelID)
    -- YunYingLogic.sendIconUpdate(ENTRANCE_ACT_ID, human)
    YunYingLogic.updateIcon(YYInfo[ACT_ID], human, true)
end



-- 升级
function onLevelUp(human, oldLv, newLv, funcID)
    updateRedDot(human)
end

function isOpen(human, YYInfo, funcConfig)
    return isShowEntrance(human)
end

function isRed(human)
    if not isOpen(human) then
        return false
    end

    return isCanGet(human)
end


-- 查询
function LevelGift_Query(human)
    local msgRet = Msg.gc.GC_LEVELGIFT_QUERY
    msgRet.list[0] = 0
    msgRet.levelNow = human.db.lv
    msgRet.isStart = 1
    msgRet.isEnd = 0
    msgRet.remaindeNum = 0

    local getWeight = calcGetWeight(human)
    msgRet.remaindeNum = math.max(MAXNUM - getWeight, 0)

    local len = 0
    local msgOnceLen = 10
    local cfgNum = #LevelGiftCfg

    for idx, v in ipairs(LevelGiftCfg) do
        len = len + 1
        msgRet.list[0] = len
        populateGiftMsg(human, msgRet.list[len], idx, v)

        if len >= msgOnceLen then
            cfgNum = cfgNum - len
            if cfgNum <= 0 then
                msgRet.isEnd = 1
                return Msg.send(msgRet, human.fd)
            end

            Msg.send(msgRet, human.fd)
            len = 0
            msgRet.isStart = 0
        end
    end

    if len > 0 then
        msgRet.isEnd = 1
        Msg.send(msgRet, human.fd)
    end
end

-- 领奖
function LevelGift_GetReward(human)
    local itemList = {}
    -- local recordList = getItemSrvRecord()

    for idx, v in ipairs(LevelGiftCfg) do
        local state = getAwardState(human, idx, v)
        if state == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            -- recordList = recordList or {}
            -- recordList[idx] = (recordList[idx] or 0) + 1
            updateData(human, idx)

            for _, itemInfo in ipairs(v.reward) do
                local itemId, itemNum = itemInfo[1], itemInfo[2]
                itemList[itemId] = (itemList[itemId] or 0) + itemNum
            end
        end
    end

    if not next(itemList) then
        return Broadcast.sendErr(human, Lang.HO_NO_CAN_GET)
    end

    -- updateItemsRemaindeNum(recordList)

    -- 发放道具
    BagLogic.addItemList(human, itemList, LOGTYPE)

    LevelGift_Query(human)

    updateRedDot(human)
end