--------------------------------
-- 文件名       :   BusThreeActTask.lua
-- 文件说明     :   新商业活动3-任务
-- 创建时间     :   2025/09/02
-- 创建人       :   FC
--------------------------------

local Util = require("common.Util")
local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local CommonDefine = require("common.CommonDefine")
local BusThreeActConf = require("excel.BusThreeActivity")
local ObjHuman = require("core.ObjHuman")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")
local ServerCommerceManager = require("serverCommerce.ServerCommerceManager")
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 BUSTHREETASKABSID = 7401        -- 对应ABS活动ID

----------------------------------------- 内部处理开始 -------------------------------------
-- 配置
local function BusThreeActTask_GetTaskCof()
    return BusThreeActConf.Task
end

local function BusThreeActTask_GetTaskPointCof()
    return BusThreeActConf.TaskPoint
end

-- 订阅事件
local function BusThreeActTask_SubEvent(uuid, nEventType)
    TriggerLogic.SubscribeEvent(nEventType, uuid, BusThreeActTask_EventCallBack)
end

-- 创建DB数据
local function CreatDB(human)
    human.db.absAct[BUSTHREETASKABSID].Task = {
        nTaskPoint = 0,             -- 任务积分
        TaskPrize = {},             -- 任务数据
        TaskPointPrize = {},        -- 任务积分奖励
    }

    local tConf = BusThreeActTask_GetTaskCof()
    local tEvnetType = {}
    local tDBTask = human.db.absAct[BUSTHREETASKABSID].Task.TaskPrize
    for nID, v in ipairs(tConf) do
        if not tDBTask[v.nTaskType] then
            tDBTask[v.nTaskType] = {
                nFinishNum = 0,     -- 完成次数
                taskStatus = {},    -- 任务状态
            }
        end

        tDBTask[v.nTaskType].taskStatus[nID] = CommonDefine.COMMON_PRIZE_STATE_NOGET

        if not tEvnetType[v.nTaskType] then
            BusThreeActTask_SubEvent(human.db._id, v.nTaskType)
            tEvnetType[v.nTaskType] = 1
        end
    end

    tConf = BusThreeActTask_GetTaskPointCof()
    local tDBTaskPointPrize = human.db.absAct[BUSTHREETASKABSID].Task.TaskPointPrize
    for nID, v in pairs(tConf) do
        if not tDBTaskPointPrize[nID] then
            tDBTaskPointPrize[nID] = CommonDefine.COMMON_PRIZE_STATE_NOGET
        end
    end

    print("[BusThreeActTask_CreatDB] 战区任务 初始化数据完成 name = "..human.db.name)
    return true
end

local function CheckAndCreatDB(human)
    if not human.db.absAct[BUSTHREETASKABSID] or nil == _G.next(human.db.absAct[BUSTHREETASKABSID]) 
        or not human.db.absAct[BUSTHREETASKABSID].Task then
            CreatDB(human)
    end
end

-- 获取任务奖励DB数据
local function BusThreeActTask_GetTaskDB(human)
    if not human.db.absAct[BUSTHREETASKABSID].Task then
        human.db.absAct[BUSTHREETASKABSID].Task = {}
        CreatDB(human)
    end

    return human.db.absAct[BUSTHREETASKABSID].Task
end

-- 获取任务状态
local function BusThreeActTask_GetTaskStatus(human, nID, nTaskType)
    local tDBData = BusThreeActTask_GetTaskDB(human)

    if not tDBData.TaskPrize or not tDBData.TaskPrize[nTaskType] or not tDBData.TaskPrize[nTaskType].taskStatus[nID] then
        print("[BusThreeActTask_GetTaskStatus] 不存在对应的DB数据!!! 没有初始化吗？")
        return CommonDefine.COMMON_PRIZE_STATE_NOGET
    end

    return tDBData.TaskPrize[nTaskType].taskStatus[nID]
end

-- 设置任务状态
local function BusThreeActTask_SetTaskStatus(human, nID, nTaskType, nValue)
    local tDBData = BusThreeActTask_GetTaskDB(human)

    tDBData.TaskPrize[nTaskType].taskStatus[nID] = nValue
end

-- 获取任务完成次数
local function BusThreeActTask_GetTaskFinishNum(human, nTaskType)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    if not tDBData.TaskPrize[nTaskType] then
        return -1
    end

    return tDBData.TaskPrize[nTaskType].nFinishNum
end

-- 增加任务完成次数
local function BusThreeActTask_AddTaskFinishNum(human, nTaskType, nAddNum)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    if not tDBData.TaskPrize[nTaskType] then
        return
    end

    tDBData.TaskPrize[nTaskType].nFinishNum = tDBData.TaskPrize[nTaskType].nFinishNum + nAddNum
end

-- 获取任务积分
local function BusThreeActTask_GetTaskPoint(human)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    return tDBData.nTaskPoint
end

-- 增加任务积分
local function BusThreeActTask_AddTaskPoint(human, nPoint)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    tDBData.nTaskPoint = tDBData.nTaskPoint + nPoint
end

-- 获取任务积分奖励状态
local function BusThreeActTask_GetTaskPointPrizeStatus(human, nID)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    if not tDBData.TaskPointPrize or not tDBData.TaskPointPrize[nID] then
        return CommonDefine.COMMON_PRIZE_STATE_NOGET
    end

    return tDBData.TaskPointPrize[nID]
end

-- 设置 任务积分奖励状态
local function BusThreeActTask_SetTaskPointPrizeStatus(human, nID, nValue)
    local tDBData = BusThreeActTask_GetTaskDB(human)
    tDBData.TaskPointPrize[nID] = nValue
end

-- 检查任务是否完成
local function BusThreeActTask_CheckTaskStatus(human, nTaskType)
    local tConf = BusThreeActTask_GetTaskCof()
    local nNowFinishNum = BusThreeActTask_GetTaskFinishNum(human, nTaskType)
    local nDay
    local bSendRed = false
    for nID, v in ipairs(tConf) do
        if v.nTaskType == nTaskType then
            if nNowFinishNum >= v.nValue then
                local nState = BusThreeActTask_GetTaskStatus(human, nID, nTaskType)
                if CommonDefine.COMMON_PRIZE_STATE_NOGET == nState then
                    bSendRed = true
                    BusThreeActTask_SetTaskStatus(human, nID, v.nTaskType, CommonDefine.COMMON_PRIZE_STATE_CANGET)
                    -- BusThreeActTask_AddPoint(human, 1)
                    if not nDay then
                        nDay = v.nDay
                    end
                end
            else
                break
            end
        end
    end

    if true == bSendRed then
        YunYingLogic.sendBanner(human)
        local config = AbsActExcel.absActivity[BUSTHREETASKABSID]
        YunYingLogic.sendGroupUpdate(YYInfo[BUSTHREETASKABSID], human, config.panelID)
    end
end

-- 检查任务点数奖励状态
local function BusThreeActTask_CheckTaskPointStatus(human)
    local nNowPoint = BusThreeActTask_GetTaskPoint(human)
    local tConf = BusThreeActTask_GetTaskPointCof()

    local bSendClient = false
    for nID, v in ipairs(tConf) do
        if nNowPoint >= v.nPoint then
            local nState = BusThreeActTask_GetTaskPointPrizeStatus(human, nID)
            if CommonDefine.COMMON_PRIZE_STATE_NOGET == nState then
                bSendClient = true
                BusThreeActTask_SetTaskPointPrizeStatus(human, nID, CommonDefine.COMMON_PRIZE_STATE_CANGET)
            end
        else
            break
        end
    end

    if true == bSendClient then
        BusThreeActTask_QueryTaskPoint(human)
    end
end

----------------------------------------回调处理---------------------------------------------------
-- 事件回调通用处理
local function BusThreeActTask_EvnentCommon(nEventType, uuid, nValue)
    print("[BusThreeActTask_EvnentCommon] 事件回调通用处理 nEventType = "..nEventType.." uuid = "..uuid)
    local human = ObjHuman.onlineUuid[uuid]
    if not human then
        print("[BusThreeActTask_EvnentCommon] 玩家不在线了？ nEventType = "..nEventType)
        return
    end

    print("[BusThreeActTask_EvnentCommon] nEventType = "..nEventType.." nValue = "..nValue.." name = "..human.db.name)

    local nOldNum = BusThreeActTask_GetTaskFinishNum(human, nEventType)

    print("[BusThreeActTask_EvnentCommon] 久的次数 nOldNum = "..nOldNum)

    -- 增加完成次数
    BusThreeActTask_AddTaskFinishNum(human, nEventType, nValue)

    -- 检查任务状态
    BusThreeActTask_CheckTaskStatus(human, nEventType)
end

-- 事件-获得英雄处理
local function BusThreeActTask_EvnentGetHero(nEventType, uuid, nValue1, nValue2)
    local human = ObjHuman.onlineUuid[uuid]
    if not human then
        return
    end
    
    local nNum = nValue1
    local nStar = nValue2

    print("[BusThreeActTask_EvnentGetHero] nEventType = "..nEventType.." nNum = "..nNum.." nStar = "..nStar.." name = "..human.db.name)

    local bCheck = false
    local tConf = BusThreeActTask_GetTaskCof()
    for nID, v in ipairs(tConf) do
        if v.nTaskType == nEventType then
            if not v.nTaskArgument or v.nTaskArgument == "" then
                print("[BusThreeActTask_EvnentGetHero] 获得英雄但是没有获取到对应的配置参数要求")
            else
                --print("[BusThreeActTask_EvnentGetHero] 存在对应参数 nTaskArgument = "..v.nTaskArgument)
                local tTaskArgument = Util.split(v.nTaskArgument , "|")
                -- table.print_lua_table(tTaskArgument)
                if 2 ~= #tTaskArgument then
                    print("[BusThreeActTask_EvnentGetHero] 获取的任务 参数数量不正确")
                else
                    if nNum >= tonumber(tTaskArgument[1]) and nStar == tonumber(tTaskArgument[2]) then
                        --print("BusThreeActTask_EvnentGetHero 条件满足")
                        BusThreeActTask_AddTaskFinishNum(human, nEventType, 1)
                        --local nNewNum = BusThreeActTask_GetTaskFinishNum(human, nEventType)
                        --print("BusThreeActTask_EvnentGetHero 条件满足, 新的数量为 nNewNum = "..nNewNum)
                        bCheck = true
                    end
                end
            end
        end
    end

    BusThreeActTask_CheckTaskStatus(human, nEventType)
end

-- 事件处理
local tEventHandler = nil
-- 起服处理
function Init()
    tEventHandler = {
        [TriggerDefine.EVENT_TYPE_SWEEP] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.CHAT_TIMES] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.FRIEND_COMBAT] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_FINDSTAR] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_FATESUMMON] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_OPENBOX] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_CHAMPIONSNUM] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_GETHERO] = BusThreeActTask_EvnentGetHero,
        [TriggerDefine.EVENT_TYPE_SHOPBUY] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.EVENT_TYPE_UNIONSKILLUP] = BusThreeActTask_EvnentCommon,
        [TriggerDefine.DRAWCALL_SERNIOR_CNT] = BusThreeActTask_EvnentCommon,
    }

    print("[CommerceActTask - Init] tEventHandler 初始化完成")
end

----------------------------------------- 外部调用开始 -------------------------------------
function BusThreeActTask_EventCallBack(nEventType, uuid, nValue1, nValue2)
    if not tEventHandler then
        Init()
    end

    if not tEventHandler or not tEventHandler[nEventType] then
        print("[BusThreeActTask_EventCallBack] 不存在对应的处理函数 nEventType = "..nEventType)
        return
    end

    print("[BusThreeActTask_EventCallBack] 收到事件触发回调 nEventType = "..nEventType)
    pcall(tEventHandler[nEventType], nEventType, uuid, nValue1, nValue2)
end

function BusThreeActTask_AddPoint(human, nAddPoint)
    -- 增加积分
    BusThreeActTask_AddTaskPoint(human, nAddPoint)

    -- 检查积分奖励状态
    BusThreeActTask_CheckTaskPointStatus(human)
end

----------------------------------------- 客户端请求 -------------------------------------
-- 请求战区集结任务信息
function BusThreeActTask_QueryTask(human, nDay)
    local state, nEndTime, nOpenTime = AbsActLogic.isStarted(human, BUSTHREETASKABSID)
    if not state then
        return Broadcast.sendErr(human, Lang.YUNYING_ERR_TIME)
    end

    print("[BusThreeActTask_QueryTask] 进入查询任务信息 nDay = "..nDay.." name = "..human.db.name)

    CheckAndCreatDB(human)

    local tConf = BusThreeActTask_GetTaskCof()

    local nDiffDay = Util.diffDay(nOpenTime) + 1
    local tMsgData = Msg.gc.GC_NEW_BUSTHREEACT_TASKQUERY
    tMsgData.nDay = nDay
    tMsgData.nNowDay = nDiffDay
    tMsgData.nNowPoint = BusThreeActTask_GetTaskPoint(human)
    tMsgData.leftTime = nEndTime - os.time()

    print("[BusThreeActTask_QueryTask] nDay = "..nDay.." nDiffDay = "..nDiffDay.." name = "..human.db.name)

    local tDay = {}
    local tRed = tMsgData.tRed
    tRed[0] = 0
    local tListData = tMsgData.list
    tListData[0] = 0
    for nID, v in ipairs(tConf) do
        if v.nDay == nDay then
            tListData[0] = tListData[0] + 1
            local tNode = tListData[tListData[0]]
            tNode.nID = nID
            tNode.nState = BusThreeActTask_GetTaskStatus(human, nID, v.nTaskType)
            tNode.nDay = v.nDay
            tNode.nValue = v.nValue
            -- tNode.nPoint = v.nPoint
            tNode.Desc = v.szDes
            tNode.nFinish = BusThreeActTask_GetTaskFinishNum(human, v.nTaskType)
            tNode.item[0] = #v.Prize

            for i, tItemData in ipairs(v.Prize) do
                Grid.makeItem(tNode.item[i], tItemData[1], tItemData[2])
            end
        end

        if not tDay[v.nDay] then
            tDay[v.nDay] = 1
            tRed[0] = tRed[0] + 1
            tRed[v.nDay] = 0
        end

        if tRed[v.nDay] == 0 and v.nDay <= nDiffDay then
            local nState = BusThreeActTask_GetTaskStatus(human, nID, v.nTaskType)
            if nState == CommonDefine.COMMON_PRIZE_STATE_CANGET then
                tRed[v.nDay] = 1
            end
        end
    end

    Msg.send(tMsgData, human.fd)
    print("[BusThreeActTask_QueryTask] 发送任务信息完成 name = "..human.db.name)
end

-- 请求领取任务奖励
function BusThreeActTask_GetTaskPrize(human, nDay)
    local tConf = BusThreeActTask_GetTaskCof()
    local tGoods = {}

    local nFinishNum = 0
    for nID, v in ipairs(tConf) do
        if v.nDay == nDay then
            local nState = BusThreeActTask_GetTaskStatus(human, nID, v.nTaskType)
            if CommonDefine.COMMON_PRIZE_STATE_CANGET == nState then
                for i, tItemData in ipairs(v.Prize) do
                    if not tGoods[tItemData[1]] then
                        tGoods[tItemData[1]] = 0
                    end

                    tGoods[tItemData[1]] = tGoods[tItemData[1]] + tItemData[2]
                end

                BusThreeActTask_SetTaskStatus(human, nID, v.nTaskType, CommonDefine.COMMON_PRIZE_STATE_GET)
                nFinishNum = nFinishNum + 1
            end
        end
    end

    if nil ~= _G.next(tGoods) then
        local tItem = {}
        for nID, nNum in pairs(tGoods) do
            table.insert(tItem, {nID, nNum})
        end

        BagLogic.addItemList(human, tItem, "BusThreeTask")

        BusThreeActTask_AddPoint(human, nFinishNum)

        BusThreeActTask_QueryTask(human, nDay)
     
        BusThreeActTask_QueryTaskPoint(human)

        YunYingLogic.sendBanner(human)
        local config = AbsActExcel.absActivity[BUSTHREETASKABSID]
        YunYingLogic.sendGroupUpdate(YYInfo[BUSTHREETASKABSID], human, config.panelID)
    end
end

-- 请求任务积分信息
function BusThreeActTask_QueryTaskPoint(human)
    print("[BusThreeActTask_QueryTaskPoint] 进入查询任务积分信息 name = "..human.db.name)
    local tConf = BusThreeActTask_GetTaskPointCof()

    local tMsgData = Msg.gc.GC_NEW_BUSTHREEACT_TASKPOINTQUERY
    tMsgData.nNowPoint = BusThreeActTask_GetTaskPoint(human)

    CheckAndCreatDB(human)

    local tListData = tMsgData.listPoint
    tListData[0] = 0
    for nID, v in ipairs(tConf) do
        tListData[0] = tListData[0] + 1
        local tNode = tListData[tListData[0]]
        tNode.nID = nID
        tNode.nNeedPoint = v.nPoint
        tNode.nState = BusThreeActTask_GetTaskPointPrizeStatus(human, nID)
        tNode.item[0] = #v.Prize

        for i, tItemData in ipairs(v.Prize) do
            Grid.makeItem(tNode.item[i], tItemData[1], tItemData[2])
        end
    end

    Msg.send(tMsgData, human.fd)
end

-- 领取任务积分奖励
function BusThreeActTask_GetTaskPointPrize(human)
    local tConf = BusThreeActTask_GetTaskPointCof()

    local tGoods = {}
    for nID, v in ipairs(tConf) do
        local nState = BusThreeActTask_GetTaskPointPrizeStatus(human, nID)
        if CommonDefine.COMMON_PRIZE_STATE_CANGET == nState then
            for i, tItemData in ipairs(v.Prize) do
                if not tGoods[tItemData[1]] then
                    tGoods[tItemData[1]] = 0
                end

                tGoods[tItemData[1]] = tGoods[tItemData[1]] + tItemData[2]
            end

            BusThreeActTask_SetTaskPointPrizeStatus(human, nID, CommonDefine.COMMON_PRIZE_STATE_GET)
        end
    end

    if nil ~= _G.next(tGoods) then
        local tItem = {}
        for nID, nNum in pairs(tGoods) do
            table.insert(tItem, {nID, nNum})
        end

        BagLogic.addItemList(human, tItem, "BusThreeTask")
        BusThreeActTask_QueryTaskPoint(human)

        YunYingLogic.sendBanner(human)
        local config = AbsActExcel.absActivity[BUSTHREETASKABSID]
        YunYingLogic.sendGroupUpdate(YYInfo[BUSTHREETASKABSID], human, config.panelID)
    end
end

function isRed(human)
    local tConf = BusThreeActTask_GetTaskCof()
    local state, nEndTime, nOpenTime = AbsActLogic.isStarted(human, BUSTHREETASKABSID)
    if not state then
        return false
    end

    CheckAndCreatDB(human)
    
    if 0 >= nOpenTime then
        print("[BusThreeActTask_isRed] 不正确的活动开启时间")
        return false
    end

    local nDiffDay = Util.diffDay(nOpenTime) + 1
    for nID, v in ipairs(tConf) do
        if v.nDay <= nDiffDay then
            local nState = BusThreeActTask_GetTaskStatus(human, nID, v.nTaskType)
            if CommonDefine.COMMON_PRIZE_STATE_CANGET == nState then
                return true
            end
        end
    end

    tConf = BusThreeActTask_GetTaskPointCof()
    for nID, v in ipairs(tConf) do
        local nState = BusThreeActTask_GetTaskPointPrizeStatus(human, nID)
        if CommonDefine.COMMON_PRIZE_STATE_CANGET == nState then
            return true
        end
    end

    return false
end

-- 订阅任务数据
function BusThreeActTask_HumanSubEvent(human)
    local tConf = BusThreeActTask_GetTaskCof()
    local tTaskType = {}

    for nID, v in ipairs(tConf) do
        if not tTaskType[v.nTaskType] then
            local nState = BusThreeActTask_GetTaskStatus(human, nID, v.nTaskType)
            -- 没有完成才订阅
            if nState == CommonDefine.COMMON_PRIZE_STATE_NOGET then
                tTaskType[v.nTaskType] = 1
            end
        end
    end

    -- 订阅事件
    for nTaskType, v in pairs(tTaskType) do
        BusThreeActTask_SubEvent(human.db._id, nTaskType)
        print("[BusThreeActTask_SubEvent] 玩家订阅了事件 nTaskType = "..nTaskType)
    end
end

function onLogin(human)
    local state, nEndTime, nOpenTime = AbsActLogic.isStarted(human, BUSTHREETASKABSID)
    if not state then
        return
    end

    BusThreeActTask_HumanSubEvent(human)
    print("[BusThreeActTask_onLogin] 玩家登录订阅事件完成 name = "..human.db.name)
end


function isOpen(human, YYInfo, funcConfig)
    print("[BusThreeActTask__isOpen] 进入判断")
    local state, endTime, startTime = AbsActLogic.isStarted(human, funcConfig and funcConfig.funcID or BUSTHREETASKABSID)
    if not state then 
        print("[BusThreeActTask_isOpen] 当前活动未开启")
        return 
    end
    print("[BusThreeActTask__isOpen] 进入判断 endTime = "..endTime.." startTime = "..startTime)
    return true, endTime, startTime
end

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