--------------------------------
-- 文件名       :   BusOneActivityTask.lua
-- 文件说明     :   新商业活动-任务
-- 创建时间     :   2025/08/05
-- 创建人       :   FC
--------------------------------

local tTaskConf = require("excel.BusoneActivity").Task
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 AbsActLogic = require("absAct.AbsActLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local TriggerLogic = require("trigger.TriggerLogic")
local TriggerDefine = require("trigger.TriggerDefine")
local ObjHuman = require("core.ObjHuman")
local BusOneActivityBuy = require("absAct.BusOneActivityBuy")
local BusOneActivityYuanZheng = require("absAct.BusOneActivityYuanZheng")
local BusOneActivityHero = require("absAct.BusOneActivityHeroYuanZheng")

local BUSONETASKABSID = 7201        -- 对应ABS活动ID
local BUSONECHOSETASKNUM = 5    -- 选择任务数量
-- 事件处理
local tEventHandler = nil
----------------------------------------- 内部处理开始 -------------------------------------
-- 获取任务DB数据
local function BusOneTask_GetAllTask(human)
    return human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask
end

local function BusOneTask_SubEvent(uuid, nEventType)
    print("[BusOneTask_SubEvent] 进入荣新商业活动-任务 订阅事件 注册 nEventType = "..nEventType)
    TriggerLogic.SubscribeEvent(nEventType, uuid, BusOneTask_EventCallBack)
end

-- 订阅任务
local function BusOneTask_BeginSubEvent(human)
    local uuid = human.db._id
    local tTaskDBData = BusOneTask_GetAllTask(human)
    for nID, v in pairs(tTaskDBData) do
        local tConfig = tTaskConf[nID]
        if tConfig then
            BusOneTask_SubEvent(uuid, tConfig.nType)
        end
    end
end

-- 清空任务数据
local function BusOneTask_ClearTask(human)
    human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask = {}
end

-- 选择任务操作
local function BusOneTask_ChoseTask(human)
    BusOneTask_ClearTask(human)

    local tType, tTypeTaskNum = {}, {}
    for nID, v in ipairs(tTaskConf) do
        if not tType[v.nType] then
            tType[v.nType] = 1
        end

        if not tTypeTaskNum[v.nType] then
            tTypeTaskNum[v.nType] = {}
        end

        table.insert(tTypeTaskNum[v.nType], nID)
    end

    local tChoseType, tChoseNum = {}, 0
    for i = 1, 100, 1 do
        if tChoseNum == BUSONECHOSETASKNUM then
            break
        end

        for nType, value in pairs(tType) do
            local nRandNum = math.random(1, 100)
            if 0 == nRandNum % 2 then
                if not tChoseType[nType] then
                    tChoseType[nType] = 1
                    tChoseNum = tChoseNum + 1
                    break
                end
            end
        end
    end

    if tChoseNum ~= BUSONECHOSETASKNUM then
        print("[BusOneTask_ChoseTask] 没有正确的选择出任务类型的个数")
        return
    end

    for nType, _ in pairs(tChoseType) do
        local nLen = #tTypeTaskNum[nType]
        local nIndex = math.random(1, nLen)
        local nChoseID = tTypeTaskNum[nType][nIndex]

        human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nChoseID] = {
            nStatus = CommonDefine.COMMON_PRIZE_STATE_NOGET,
            nFinish = 0,
        }
    end
end

-- 创建DB数据
local function BusOneTask_CreateDB(human)
    if not human.db.absAct[BUSONETASKABSID] then
        human.db.absAct[BUSONETASKABSID] = {}
    end

    human.db.absAct[BUSONETASKABSID].tTaskInfo = {
        nRefresh = os.time(),
        tChoseTask = {},
    }

    BusOneTask_ChoseTask(human)
    BusOneTask_BeginSubEvent(human)
end

-- 检测DB数据
local function BusOneTask_CheckDB(human)
    if not human.db.absAct[BUSONETASKABSID] or nil == _G.next(human.db.absAct[BUSONETASKABSID]) 
        or not human.db.absAct[BUSONETASKABSID].tTaskInfo then
        BusOneTask_CreateDB(human)
    end
end

-- 获取任务状态
local function BusOneTask_GetTaskStatus(human, nID)
    return human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nID].nStatus
end

-- 设置任务状态
local function BusOneTask_SetTaskStatus(human, nID, nStatus)
    human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nID].nStatus = nStatus
end

-- 获取任务完成次数
local function BusOneTask_GetTaskFinishNum(human, nID)
    return human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nID].nFinish
end

-- 设置任务状态
local function BusOneTask_AddTaskFinishNum(human, nID, nAddNum)
    human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nID].nFinish = human.db.absAct[BUSONETASKABSID].tTaskInfo.tChoseTask[nID].nFinish + nAddNum
end

-- 获取任务刷新时间
local function BusOneTask_GetTaskTime(human)
    return human.db.absAct[BUSONETASKABSID].tTaskInfo.nRefresh
end

-- 设置任务刷新时间
local function BusOneTask_SetTaskTime(human, nValue)
    human.db.absAct[BUSONETASKABSID].tTaskInfo.nRefresh = nValue
end

-- 检测和重置任务数据
local function BusOneTask_CheckAndResetTask(human)
    local nLastTime = BusOneTask_GetTaskTime(human)
    if nil == Util.isSameDay(nLastTime) then
        BusOneTask_SetTaskTime(human, os.time())
        BusOneTask_ChoseTask(human)
        BusOneTask_BeginSubEvent(human)
    end
end

-- 获得英雄
local function BusOneTask_GetHero(nEventType, uuid, nValue1, nValue2)
    local human = ObjHuman.onlineUuid[uuid]
    if not human then
        print("[BusOneTask_GetHero] 玩家不在线了？ nEventType = "..nEventType)
        return
    end

    local nNum = nValue1
    local nStar = nValue2
    print("[BusOneTask_GetHero] 获取了英雄 nEventType = "..nEventType.." uuid = "..uuid.." nNum = "..nNum.." nStar = "..nStar)
    
    local tAllDBData = BusOneTask_GetAllTask(human)
    local bSend = false
    for nID, v in pairs(tAllDBData) do
        local tConfig = tTaskConf[nID]
        if tConfig and tConfig.nType == nEventType and tConfig.ExtraParameter then
            if v.nStatus == CommonDefine.COMMON_PRIZE_STATE_NOGET then
                local tTaskArgument = Util.split(tConfig.ExtraParameter , "|")
                if nNum >= tonumber(tTaskArgument[1]) and nStar == tonumber(tTaskArgument[2]) then
                    v.nFinish = v.nFinish + 1
                    if v.nFinish >= tConfig.nNeedFinish then
                        v.nStatus = CommonDefine.COMMON_PRIZE_STATE_CANGET
                        bSend = true
                    end
                end
            end
        end
    end

    if true == bSend then
        YunYingLogic.sendBanner(human)
        BusOneTask_SendRed(human)
    end
end

local function BusOneTask_Common(nEventType, uuid, nValue, nArgumentType)
    local human = ObjHuman.onlineUuid[uuid]
    if not human then
        print("[BusOneTask_Common] 玩家不在线了？ nEventType = "..nEventType)
        return
    end

    print("[BusOneTask_Common] 通用回调开始 nEventType = "..nEventType.." uuid = "..uuid)

    local tAllDBData = BusOneTask_GetAllTask(human)
    local bSend = false
    for nID, v in pairs(tAllDBData) do
        local tConfig = tTaskConf[nID]
        if tConfig and tConfig.nType == nEventType then
            if v.nStatus == CommonDefine.COMMON_PRIZE_STATE_NOGET then
                v.nFinish = v.nFinish + nValue
                if v.nFinish >= tConfig.nNeedFinish then
                    v.nStatus = CommonDefine.COMMON_PRIZE_STATE_CANGET
                    bSend = true
                end
                break
            end
        end
    end

    if true == bSend then
        YunYingLogic.sendBanner(human)
        BusOneTask_SendRed(human)
    end
end

-----------------------------------客户端请求-----------------------------
function BusOneTask_Query(human)
    BusOneTask_CheckDB(human)

    local tMsgData = Msg.gc.GC_NEW_BUSONEACT_TASK_QUERY
    tMsgData.tTaskList[0] = 0
    local tTaskDB = BusOneTask_GetAllTask(human)
    print("[BusOneTask_Query] 开始打印任务数据")
    table.print_lua_table(tTaskDB)
    print("[BusOneTask_Query] 结束打印任务数据")

    for nID, v in pairs(tTaskDB) do
        local tConfig = tTaskConf[nID]
        if tConfig  then
            tMsgData.tTaskList[0] = tMsgData.tTaskList[0] + 1
            local tData = tMsgData.tTaskList[tMsgData.tTaskList[0]]
            tData.nID = nID
            tData.szDes = tConfig.szDes
            tData.nStatus = v.nStatus
            tData.nNowFinishNum = v.nFinish
            tData.nNeedFinishNum = tConfig.nNeedFinish

            tData.tPrize[0] = #tConfig.tPrize
            for i, tItem in ipairs(tConfig.tPrize) do
                local nGoodsID = tItem[1]
                local nGoodsNum = tItem[2]

                Grid.makeItem(tData.tPrize[i], nGoodsID, nGoodsNum)
            end
        else
            print("[BusOneTask_Query] 不存在对应的任务ID配置 nID = "..nID)
        end
    end

    Msg.send(tMsgData, human.fd)
end

function BusOneTask_Get(human)
    local tTaskDB = BusOneTask_GetAllTask(human)
    local tItem = {}
    for nID, v in pairs(tTaskDB) do
        local tConfig = tTaskConf[nID]
        if tConfig and v.nStatus == CommonDefine.COMMON_PRIZE_STATE_CANGET then
            v.nStatus = CommonDefine.COMMON_PRIZE_STATE_GET
            for _, tGoods in ipairs(tConfig.tPrize) do
                local nGoodsID = tGoods[1]
                local nGoodsNum = tGoods[2]
                if not tItem[nGoodsID] then
                    tItem[nGoodsID] = 0
                end

                tItem[nGoodsID] = tItem[nGoodsID] + nGoodsNum
            end
        end
    end

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

        BagLogic.addItemList(human, tGoods, "BusOneTask")
        BusOneTask_Query(human)

        YunYingLogic.sendBanner(human)
        BusOneTask_SendRed(human)
    end
end

-----------------------------------外部调用-----------------------------
function isOpen(human, YYInfo, funcConfig)
    print("[BusOneActivityTask_isOpen] 进入判断")
    local state, endTime, startTime = AbsActLogic.isStarted(human, funcConfig and funcConfig.funcID or BUSONETASKABSID)
    if not state then
        print("[BusOneActivityTask_isOpen] 当前活动未开启")
        return
    end

    print("[BusOneActivityTask_isOpen] 进入判断 endTime = "..endTime.." startTime = "..startTime)

    return true, endTime, startTime
end

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

function isRed(human, YYInfo, absActConfig)
    BusOneTask_CheckDB(human)
    local tDBData = BusOneTask_GetAllTask(human)
    for nID, v in pairs(tDBData) do
        if CommonDefine.COMMON_PRIZE_STATE_CANGET ==  v.nStatus then
            return true
        end
    end

    return false
end

function onLogin(human)
    if false == isOpen(human) then
        return
    end

    print("[BusOneTask_onLogin] 玩家登录进行处理")
    BusOneTask_CheckDB(human)
    BusOneTask_CheckAndResetTask(human)
    BusOneTask_BeginSubEvent(human)
end

function onZeroAll()
    -- 遍历在线玩家
    for uuid, human in pairs(ObjHuman.onlineUuid) do
        onLogin(human)
    end
end

local function BusOneTask_Init()
    print("[BusOneTask_Init] 初始化回调函数开始")

    tEventHandler = {
        [TriggerDefine.EVENT_TYPE_GETHERO] = BusOneTask_GetHero,  -- 获得英雄
        [TriggerDefine.EVENT_TYPE_FATESUMMON] = BusOneTask_Common,   -- 天命召唤
        [TriggerDefine.EVENT_TYPE_FINDSTAR] = BusOneTask_Common,     -- 寻星
        [TriggerDefine.DRAWCALL_SERNIOR_CNT] = BusOneTask_Common,    -- 高抽
        [TriggerDefine.EQUIP_REFINEMENT] = BusOneTask_Common,        -- 装备洗练
        [TriggerDefine.JINBI_DEL] = BusOneTask_Common,               -- 消耗金币
        [TriggerDefine.GUYU_DEL] = BusOneTask_Common,                -- 消耗古玉
        [TriggerDefine.JINGYAN_DEL] = BusOneTask_Common,             -- 消耗经验
    }

    print("[BusOneTask_Init] 初始化回调函数完成")
end

function BusOneTask_EventCallBack(nEventType, uuid, nValue1, nValue2)
    print("[BusOneTask_EventCallBack] 进入回调函数 11111 nEventType = "..nEventType)
    if not tEventHandler then
        print("[BusOneTask_EventCallBack] 进入初始化 回调数据 ")
        BusOneTask_Init()
    end

    print("[BusOneTask_EventCallBack] 进入回调函数 22222 nEventType = "..nEventType)
    if not tEventHandler or not tEventHandler[nEventType] then
        print("[BusOneTask_EventCallBack] 不存在对应的处理函数 当前已经返回",nEventType)
        return
    end

    print("[BusOneTask_EventCallBack] 商业活动回调开始 nEventType = "..nEventType.." uuid = "..uuid)
    pcall(tEventHandler[nEventType], nEventType, uuid, nValue1, nValue2)
end

function BusOneTask_SendRed(human)
    local tMsgData = Msg.gc.GC_NEW_BUSONEACT_SEND_RED
    tMsgData.tListRed[0] = 4
    tMsgData.tListRed[1] = isRed(human) == true and 1 or 0
    tMsgData.tListRed[2] = BusOneActivityBuy.isRed(human) == true and 1 or 0
    tMsgData.tListRed[3] = BusOneActivityYuanZheng.isRed(human) == true and 1 or 0
    tMsgData.tListRed[4] = BusOneActivityHero.isRed(human) == true and 1 or 0

    Msg.send(tMsgData, human.fd)
end