----------------------------
-- 彈窗禮包
----------------------------
local BuyExcel = require("excel.buy").buy
local GiftExcel = require("excel.buy").gift
local ItemDefine = require("bag.ItemDefine")
local Grid = require("bag.Grid")
local NewLogic = require("role.NewLogic")
local BagLogic = require("bag.BagLogic")
local BuyLogic = require("topup.BuyLogic")
local Util = require("common.Util")

-- 推送协议类型
local GC_GIFT_GENERATE = 50 
local GC_QUERY_GIFT = 51

-- 次类型
GIFT_SEC_TYPE1 = 1
GIFT_SEC_TYPE2 = 2
GIFT_SEC_TYPE3 = 3

-- 礼包触发事件
local PRINCIPAL_LINE_EVNET = 1 -- 主线推图
local EVAL_TOWER_EVENT = 2 -- 恶魔之塔
local Upgrade_HERO_EVENT = 3 -- 英雄升星

GIFT_UPGRADE_LV_EVENT = 4           -- 玩家升级
GIFT_TALISMAN_UPGRADE_STAR = 5      -- 秘宝升星
GIFT_WINNERRELIC_UPGRADE_STAR = 6   -- 圣遗物升星
GIFT_ELF_UPGRADE_STAR = 7           -- 精灵升星
GIFT_HERO_UPGRADE_STAR_DAILY = 8    -- 英雄升星, 每日只可触发一次, 可与 Upgrade_HERO_EVENT 同时触发

GIFT_HEROSEED_UPGRADE_STAR = 9      -- 英雄种子
GIFT_HEROTIANYUAN_UPGRADE_STAR = 10 -- 英雄天元
GIFT_HEROWEAPON_UPGRADE_STAR = 11   -- 英雄专属武器
GIFT_ARTIFACTS_UPGRADE_STAR = 12    -- 英雄神威灵装升星
GIFT_REALM_UPGRADE_STAR = 13        -- 境界提升

GIFT_TALISMAN_OPEN = 15           -- 开启秘宝玩法
GIFT_WINNERRELIC_OPEN = 16        -- 开启圣遗物玩法
GIFT_ELF_OPEN = 17                -- 开启精灵玩法
GIFT_ARTIFACTS_OPEN = 18          -- 开启神威灵装玩法

-- 每日只触发一次的礼包类型
local dailyEventList = {
    [GIFT_HERO_UPGRADE_STAR_DAILY] = 1,
}


--[[
    human.db.gift = {
        [id] = startTimeStamp
    }
]]

local function genGiftData(human, id,startTime,region,isNew)
    local cfg = GiftExcel[id]
    local buyCfg = BuyExcel[cfg.buyID]
    -- 获取礼包信息
    local buyItem = {}
    BuyLogic.fontBuyItem(human, buyItem, cfg.buyID)

    -- 获取礼包content
    local itemData = {}
    for _,item in ipairs(cfg.content) do 
        local data = {
            getway = {},
            suipian = {},
            equip = {},
            fuwen = {},
        }
        if not ItemDefine.isEquip(item[1]) then
            Grid.makeItem(data, item[1], item[2])
        end
        itemData[#itemData+1] = data
    end
    return {
        id = id,
        buyItem = buyItem,
        startTimeStamp = startTime,
        restTime = cfg.ttl - (os.time() - startTime),
        isNew = isNew,
        itemData = itemData,
    }
end

local function genGift(human,id)
    local giftCfg = GiftExcel[id]
    local gitftType = giftCfg and giftCfg.trigger or 0

    -- 已经触发过礼包了
    -- 新修改: 类型8不受这个影响
    if human.db.gift.unlock[id] and GIFT_HERO_UPGRADE_STAR_DAILY ~= gitftType then
        return
    end
    human.db.gift.unlock[id] = true
    local now = os.time()
    human.db.gift.online[id] = now
    local giftData = genGiftData(human, id,now,human.region or "CN",1)
    return NewLogic.PushClient(human,GC_GIFT_GENERATE,{gift = giftData})
end

local function cleanGift(human)
    local nowTime = os.time()
    local gift = human.db.gift.online
    for id,ts in pairs(gift) do 
        local cfg = GiftExcel[id]  -- 是否需要判断cfg
        if  nowTime - ts >= cfg.ttl then 
            gift[id] = nil
        end
    end
    human.db.gift.online = gift
end

local function sendHumanGift(human)
    local gift = human.db.gift.online
    local list = {}
    -- 数据太大不好控制大小，分批次传送
    for id,ts in pairs(gift) do 
        list[#list + 1] = genGiftData(human, id,ts,human.region or "CN")
        --[[if #list >= 5 then 
            NewLogic.PushClient(human,GC_QUERY_GIFT,{
                list = list,
                isFinish = 1,
            })
            list = {}
        end]]
    end
    -- 通知客户端
    NewLogic.PushClient(human,GC_QUERY_GIFT,{
        list = list,
        isFinish = 2,
    })
end

-- 每日只触发一次的礼包
local function dailyEventCheck(human, giftId)
    if not human.db.gift or not human.db.gift.dailyEventRecord then
        return true
    end

    local dailyEventRecord = human.db.gift.dailyEventRecord
    if dailyEventRecord[giftId] then
        local lastGenGiftTime = dailyEventRecord[giftId]
        if Util.isSameDay(lastGenGiftTime) then
            return false
        end
    end

    return true
end

local function updateDailyEventRecord(human, giftId)
    human.db.gift.dailyEventRecord = human.db.gift.dailyEventRecord or {}
    human.db.gift.dailyEventRecord[giftId] = os.time()
end


local handler = {
    [PRINCIPAL_LINE_EVNET] = function(human,param)
        for id,cfg in pairs(GiftExcel) do 
            -- 触发新礼包
            if cfg.trigger == PRINCIPAL_LINE_EVNET and cfg.param[1] <= param.id then 
                genGift(human,id)
            end
        end
    end,
    [EVAL_TOWER_EVENT] = function(human,param)
        for id,cfg in pairs(GiftExcel) do 
            -- 触发新礼包
            if cfg.trigger == EVAL_TOWER_EVENT and cfg.param[1] <= param.id then 
                genGift(human,id)
            end
        end
    end,
    [Upgrade_HERO_EVENT] = function(human,param)
        -- 检测是否是第一个星级的英雄
        local star = param.star
        --[[local HeroLogic = require("hero.HeroLogic")
        local maxStar,cnt = HeroLogic.getHeroMaxStarCtn(human)
        if maxStar ~= star then 
            return 
        end
        if cnt ~= 1 then 
            return
        end]]
        for id,cfg in pairs(GiftExcel) do 
            -- 触发新礼包
            if cfg.trigger == Upgrade_HERO_EVENT and cfg.param[1] == star then 
                genGift(human,id)
            end
        end
    end,
}

local handler2 = {
    [GIFT_SEC_TYPE1] = function (human, param, eventType)
        for id,cfg in pairs(GiftExcel) do
            -- 触发新礼包
            if cfg.trigger == eventType and cfg.param[1] == param.currentVal and (not dailyEventList[eventType] or dailyEventCheck(human, id)) then
                genGift(human,id)

                if dailyEventList[eventType] then
                    updateDailyEventRecord(human, id)
                end
            end
        end
    end,

    [GIFT_SEC_TYPE2] = function (human, param, eventType)
        for id,cfg in pairs(GiftExcel) do
            -- 触发新礼包
            if cfg.trigger == eventType then
                genGift(human,id)
            end
        end
    end,

    [GIFT_SEC_TYPE3] = function (human, param, eventType)
        for id,cfg in pairs(GiftExcel) do
            -- 触发新礼包
            if cfg.trigger == eventType and cfg.param[1] <= param.currentVal and (not dailyEventList[eventType] or dailyEventCheck(human, id)) then
                genGift(human,id)

                if dailyEventList[eventType] then
                    updateDailyEventRecord(human, id)
                end
            end
        end
    end,
}

---------------------------------------------------------------

function onLogin(human)
    -- 登录清楚过期礼包
    cleanGift(human)
    -- 开启事件监听！？
    return sendHumanGift(human)
end

function trigger(human,type,param, extraType)
    local f
    if not extraType then
        f = handler[type]
    else
        f = handler2[extraType]
    end

    if not f then
        return
    end

    return f(human, param, type)
end

function buy(human,giftId) 
    -- 清楚一次过期的弹窗礼包
    print("recieve gift id is ",giftId)
    cleanGift(human)
    if not human.db.gift.online[giftId] then
        print("not found gift ",giftId)
        return
    end
    local cfg = GiftExcel[giftId]

    
    --[[local content = {}
    for _,item in pairs(cfg.content) do 
        content[#content + 1] = {
            id = item[1],
            cnt = item[2]
        }
    end]]
    BagLogic.addItemList(human,cfg.content,"gift_buy")
    human.db.gift.online[giftId] = nil
    return sendHumanGift(human)
end

-- function GetRemainNum(human, nBuyID)
--     local nChoseID = nil
-- 	for id,cfg in pairs(GiftExcel) do
-- 		if cfg.buyID == nBuyID then 
-- 			nChoseID = id
-- 			break
-- 		end
-- 	end

--     if not nChoseID then
--         return 0
--     end

--     if not human.db.gift.online[nChoseID] then
--         return 0
--     else
--         return 1
--     end
-- end