--新商业化活动——超值豪礼
--db
--[=[
    human.db.absAct[id] = {
        recordData = {
            [1] = {             --key为任务ID
                [1] = 10,       --key为触发事件Id, value为进度
                [0] = 1,        --key为需要充值的ID, value为充值次数。key为0时, 表示免费
                isGet = nil,    --有值时表示已领取
            },
        }
    }
]=]--

local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local AbsActLogic = require("absAct.AbsActLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local YunYingLogic = require("yunying.YunYingLogic")
local AbsActExcel = require("excel.absAct")
local BuyLogic = require("topup.BuyLogic")
local CommonDefine = require("common.CommonDefine")
local ItemDefine = require("bag.ItemDefine")
local CycleActivityLogic = require("yunying.CycleActivity")

--本活动ID
local ACTID = 753
--日志标识
local LOGTAG = "AbsExcellentGiftLogic"
--完成任务消耗道具ID
local FINISH_TASK_COST_ID = ItemDefine.ITEM_ZUANSHI_ID
--完成任务消耗道具数量
local FINISH_TASK_COST_CNT = 500


local BATTLE_MOP_UP = 1            --冒险闯关扫荡
local LOSTTEMPLE_PASS = 2          --失落神庙通关
local YJTREASURE_PASS_LEVEL = 3    --遗迹探险层数
local FRIEND_COMBAT = 4            --好友切磋次数
local CHAT_TIMES = 5               --所有聊天频道发言次数
local MOZHU_CHALLENGE = 6         --魔王梼杌参数次数
local DRAWCALL_SERNIOR_CNT = 7      --高级召唤次数
local FUWEN_RECASTING = 8          --符文重铸次数
local UNION_DONATE = 9             --公会捐献次数
local ZHANBU_SYNTHESIS = 10         --占卜合成次数


---------------------------------各类事件处理接口----------------------------------
function onMopup(human, funcID, value)
    TriggerCbFunc(human, BATTLE_MOP_UP, value, true)
end

function friendCombat(human, funcID, value)
    TriggerCbFunc(human, FRIEND_COMBAT, value, true)
end


function lostTempleCombat(human, funcID, value)
    TriggerCbFunc(human, LOSTTEMPLE_PASS, value, true)
end

function YJTreasurePass(human, funcID, value)
    TriggerCbFunc(human, YJTREASURE_PASS_LEVEL, value, true)
end


function ChatTimes(human, funcID, value)
    TriggerCbFunc(human, CHAT_TIMES, value, true)
end

function MoZhuCombat(human, funcID, value)
    TriggerCbFunc(human, MOZHU_CHALLENGE, value, true)
end

function onDrawCard(human, funcID, value)
    TriggerCbFunc(human, DRAWCALL_SERNIOR_CNT, value, true)
end


function onFuwenChongZhu(human, funcID, value)
    TriggerCbFunc(human, FUWEN_RECASTING, value, true)
end

function onUnionDonate(human, funcID, value)
    TriggerCbFunc(human, UNION_DONATE, value, true)
end

function ZhanBuHecheng(human, funcID, value)
    TriggerCbFunc(human, ZHANBU_SYNTHESIS, value, true)
end

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



-- --订阅触发事件
-- local function registerTrigger(human)
--     local len = 0
--     local triggerTagVec = {}

--     local config = AbsActExcel.AbsExcellentGiftLogic
--     for _, v in ipairs(config) do
--         len = len + 1
--         triggerTagVec[len] = v.taskId
--     end

--     TriggerLogic.RegisterMoniter(triggerTagVec, TriggerCbFunc, human.db.newUniqueTag)
-- end

--获取任务ID
local function getTaskIdVec(triggerId, buyId)
    local ids = {}
    local len = 0
    local config = AbsActExcel.AbsExcellentGiftLogic
    for id, cfg in ipairs(config) do
        if triggerId and cfg.taskId == triggerId then
            len = len + 1
            ids[len] = id
        end

        if buyId and cfg.buyId == buyId then
            len = len + 1
            ids[len] = id
        end
    end
    return ids
end

--是否完成任务, 0-未完成, 1-可领取，2-已领取
local function getTaskState(taskId, taskData)
    if not taskData then
        return CommonDefine.COMMON_PRIZE_STATE_NOGET
    end

    if taskData.isGet then
        return CommonDefine.COMMON_PRIZE_STATE_GET
    end

    local config = AbsActExcel.AbsExcellentGiftLogic
    local singleCfg = config[taskId]
    local triggerId = singleCfg.taskId
    local triggerVal = singleCfg.taskVal

    local isFinish = true
    if not taskData[triggerId] or taskData[triggerId] < triggerVal then
        isFinish = false
    end

    if not isFinish then
        return CommonDefine.COMMON_PRIZE_STATE_NOGET
    end

    local condBuyId = singleCfg.buyId
    if condBuyId ~= 0 and not taskData[condBuyId] then
        return CommonDefine.COMMON_PRIZE_STATE_NOGET
    end

    if isFinish and not taskData.isGet then
        return CommonDefine.COMMON_PRIZE_STATE_CANGET
    end
end

--红点检查
local function redDotCheck(recordData)
    local redDotPageTb = {}
    local taskState = 0
    local config = AbsActExcel.AbsExcellentGiftLogic
    for taskId, data in pairs(recordData) do
        taskState = getTaskState(taskId, data)
        if taskState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            local taskCfg = config[taskId]
            redDotPageTb[taskCfg.page] = '1'
        end
    end

    if not next(redDotPageTb) then
        return false
    end

    return redDotPageTb
end


-- function onLogin(human, id)
--     local state = AbsActLogic.isStarted(human, id)
--     if not state then
--         return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
--     end

--     local actData = human.db.absAct[id]
--     if not actData then
--         return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
--     end

--     --registerTrigger(human)
-- end


--充值处理接口
function onCharge(human, price, funcID, buyID)
    -- local state = AbsActLogic.isStarted(human, funcID)
    local state = CycleActivityLogic.isStarted(human, funcID)
    if not state then
        return
    end

    local isChange = false
    local taskState = COMMON_PRIZE_STATE_NOGET
    local actData = human.db.absAct[ACTID]
    actData.recordData = actData.recordData or {}
    local recordData = actData.recordData

    local ids = getTaskIdVec(nil, buyID)
    local config = AbsActExcel.AbsExcellentGiftLogic

    for _, id in ipairs(ids) do
        if  not recordData[id] or not recordData[id].isGet then
            local singleCfg = config[id]
            local needBuyId = singleCfg.buyId

            recordData[id] = recordData[id] or {}
            recordData[id][needBuyId] = (recordData[id][needBuyId] or 0) + 1

            isChange = true
            if taskState ~= CommonDefine.COMMON_PRIZE_STATE_CANGET then
                taskState = getTaskState(id, recordData[id])
            end
        end
    end

    if isChange then
        Query(human, ACTID, human.nowPage or 0)
    end

    if taskState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
        --红点刷新
        YunYingLogic.sendBanner(human)
        local config = AbsActExcel.absActivity[ACTID]
        YunYingLogic.sendGroupUpdate(YYInfo[ACTID], human, config.panelID)
    end
end

--事件触发接口
function TriggerCbFunc(human, triggerTag, val, isAdd)
    -- local state = AbsActLogic.isStarted(human, ACTID)
    local state = CycleActivityLogic.isStarted(human, ACTID)
    if not state then
        return
    end

    --local isChange = false
    local taskState = COMMON_PRIZE_STATE_NOGET
    local actData = human.db.absAct[ACTID]
    actData.recordData = actData.recordData or {}
    local recordData = actData.recordData
    local ids = getTaskIdVec(triggerTag)

    for _, id in ipairs(ids) do
        if not recordData[id] or not recordData[id].isGet then
            recordData[id] = recordData[id] or {}

            if isAdd then
                recordData[id][triggerTag] = (recordData[id][triggerTag] or 0) + val
            else
                recordData[id][triggerTag] = val
            end

            --isChange = true
            if taskState ~= CommonDefine.COMMON_PRIZE_STATE_CANGET then
                taskState = getTaskState(id, recordData[id])
            end
        end
    end

    -- if isChange then
    --     Query(human, ACTID, nowPage)
    -- end

    if taskState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
        --红点刷新
        YunYingLogic.sendBanner(human)
        local config = AbsActExcel.absActivity[ACTID]
        YunYingLogic.sendGroupUpdate(YYInfo[ACTID], human, config.panelID)
    end
end


--红点判断
function isRed(human, YYInfo, funcConfig)
    local actData = human.db.absAct[funcConfig.funcID]
    if not actData then
        return false
    end

    local recordData = actData.recordData
    if not recordData then
        return false
    end

    if not redDotCheck(recordData) then
        return false
    end

    return true
end

function isOpen(human, YYInfo, funcConfig)
    -- local state, endTime, startTime = AbsActLogic.isStarted(human, funcConfig.funcID)
    local state, endTime, startTime = CycleActivityLogic.isStarted(human, funcConfig.funcID)

    return state, endTime, startTime
end


function isActive(human, YYInfo, funcConfig)
    local state = isOpen(human, YYInfo, funcConfig)
    return not state
end

--查询
function Query(human, id, page)
    -- local state = AbsActLogic.isStarted(human, id)
    local state = CycleActivityLogic.isStarted(human, id)

    if not state then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local actData = human.db.absAct[id]
    if not actData then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    actData.recordData = actData.recordData or {}
    local recordData = actData.recordData
    local config = AbsActExcel.AbsExcellentGiftLogic
    local msgRet = Msg.gc.GC_EXCELLENTGIFT_QUERY
    local len = 0
    local taskList = msgRet.taskList

    for taskId, v in ipairs(config) do
        if v.page == page then
            len = len + 1
            local taskData = recordData[taskId]
            taskList[len].state = getTaskState(taskId, taskData)
            taskList[len].idx = len
            taskList[len].taskDesc = v.taskDes
    
            taskList[len].taskMaxProgress = v.taskVal
            taskList[len].taskNowProgress = taskData and taskData[v.taskId] or 0
    
            BuyLogic.fontBuyItem(human, taskList[len].buyMsg, v.buyId)
            taskList[len].buyState = taskData and taskData[v.buyId] or 0
            if v.buyId == 0 then
                taskList[len].buyState = 1
            end
    
            local awardVec = taskList[len].award
            awardVec[0] = #v.award
            for j, itemInfo in ipairs(v.award) do
                Grid.makeItem(awardVec[j], itemInfo[1], itemInfo[2])
            end
        end
    end
    taskList[0] = len

    --完成任务消耗
    Grid.makeItem(msgRet.finishTaskCost, FINISH_TASK_COST_ID, FINISH_TASK_COST_CNT)

    --红点
    local redDotList = msgRet.redDotList
    redDotList[0] = 0
    local redDotPageTb = redDotCheck(recordData)
    if redDotPageTb then
        len = 0
        for redPage in pairs(redDotPageTb) do
            len = len + 1
            redDotList[len] = redPage
        end
        redDotList[0] = len
    end

    Msg.send(msgRet, human.fd)

    human.nowPage = page
end

--领奖
function GetReward(human, id, taskIdx, page)
    -- local state = AbsActLogic.isStarted(human, id)
    local state = CycleActivityLogic.isStarted(human, id)
    if not state then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local actData = human.db.absAct[id]
    if not actData then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local len = 0
    local taskIdList = {}
    local recordData = actData.recordData
    local config = AbsActExcel.AbsExcellentGiftLogic

    -- for k, v in ipairs(config) do
    --     if v.page == page then
    --         len = len + 1
    --         if len == taskIdx then
    --             taskId = k
    --             break
    --         end
    --     end
    -- end

    for k, v in ipairs(config) do
        if v.page == page then
            if getTaskState(k, recordData and recordData[k]) == CommonDefine.COMMON_PRIZE_STATE_CANGET then
                len = len + 1
                taskIdList[len] = k
            end
        end
    end

    if len == 0 then
        return Broadcast.sendErr(human, Lang.ABS_ANSWER_ITEM_IS_GET)
    end


    local awardtbl = {}

    for _, taskId in ipairs(taskIdList) do
        recordData[taskId].isGet = '1'
        local taskCfg = config[taskId]
        for _, itemInfo in ipairs(taskCfg.award) do
            awardtbl[#awardtbl+1] = itemInfo
        end
    end

    BagLogic.addItemList(human, awardtbl, LOGTAG)


    --BagLogic.addItemList(human, taskCfg.award, LOGTAG)

    Query(human, id, page)

    --红点
    if not redDotCheck(recordData) then
        YunYingLogic.sendBanner(human)
        local otherConfig = AbsActExcel.absActivity[ACTID]
        YunYingLogic.sendGroupUpdate(YYInfo[ACTID], human, otherConfig.panelID)
    end
end

--消耗古玉完成任务
function FinishTaskByDiamond(human, id, taskIdx, page)
    -- local state = AbsActLogic.isStarted(human, id)
    local state = CycleActivityLogic.isStarted(human, id)
    if not state then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local actData = human.db.absAct[id]
    if not actData then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    local recordData = actData.recordData
    local len = 0
    local taskId = 0
    local taskCfg = nil
    local config = AbsActExcel.AbsExcellentGiftLogic
    for k, v in ipairs(config) do
        if v.page == page then
            len = len + 1
            if len == taskIdx then
                taskId = k
                taskCfg = v
                break
            end
        end
    end

    if taskId == 0 then
        return Broadcast.sendErr(human, Lang.COMMON_ARGUMENT_ERROR)
    end

    if recordData and recordData[taskId] and recordData[taskId].isGet then
        return Broadcast.sendErr(human, Lang.FRIEND_HEART_GET_HAD)
    end

    if getTaskState(taskId, recordData and recordData[taskId]) == CommonDefine.COMMON_PRIZE_STATE_CANGET then
        return Broadcast.sendErr(human, Lang.COMMON_FINISH)
    end

    if BagLogic.getItemCnt(human, FINISH_TASK_COST_ID) < FINISH_TASK_COST_CNT then
        return Broadcast.sendErr(human, Lang.COMMON_ITEM_NOT_ENOUGH)
    end
    --扣消耗
    BagLogic.delItem(human, FINISH_TASK_COST_ID, FINISH_TASK_COST_CNT, LOGTAG)

    recordData[taskId] = recordData[taskId] or {}
    recordData[taskId][taskCfg.taskId] = taskCfg.taskVal

    --红点
    YunYingLogic.sendBanner(human)
    local otherConfig = AbsActExcel.absActivity[ACTID]
    YunYingLogic.sendGroupUpdate(YYInfo[ACTID], human, otherConfig.panelID)

    --更新
    Query(human, id, page)
end

-- function GetRemainNum(human, nBuyID)
--     local actData = human.db.absAct[ACTID]
--     if not actData or not actData.recordData then
--         return 1
--     end

--     local ids = getTaskIdVec(nil, nBuyID)
--     local config = AbsActExcel.AbsExcellentGiftLogic

--     for _, id in ipairs(ids) do
--         if not actData.recordData[id]  then
--             return 1
--         else 
--             local singleCfg = config[id]
--             local needBuyId = singleCfg.buyId
--             if not actData.recordData[id][needBuyId] then
--                 return 1
--             else
--                 return 0
--             end
--         end
--     end
-- end