--------------------------------
-- 文件名       :   ServerCommerceActShop.lua
-- 文件说明     :   跨服商业-任务
-- 创建时间     :   2025/04/08
-- 创建人       :   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 ServerCommerceConf = require("excel.ServerCommerce")
local ObjHuman = require("core.ObjHuman")
local TriggerDefine = require("trigger.TriggerDefine")
local TriggerLogic = require("trigger.TriggerLogic")
local ServerCommerceManager = require("serverCommerce.ServerCommerceManager")

----------------------------------------- 内部处理开始 -------------------------------------
-- 配置
local function CommerceActTask_GetTaskCof()
    return ServerCommerceConf.CommerceTask
end

local function CommerceActTask_GetTaskPointCof()
    return ServerCommerceConf.CommerceTaskPoint
end

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

-- 创建DB数据
function CreatDB(human)
    if not human.db.ServerCommerce or not human.db.ServerCommerce.Task then
        print("[CommerceActTask_CreatDB] 初始化数据失败 name = "..human.db.name)
        return false
    end

    human.db.ServerCommerce.Task = {
        nTaskPoint = 0,             -- 任务积分
        TaskPrize = {},             -- 任务数据
        TaskPointPrize = {},        -- 任务积分奖励
    }

    local tConf = CommerceActTask_GetTaskCof()
    local tEvnetType = {}
    local tDBTask = human.db.ServerCommerce.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
            CommerceActTask_SubEvent(human.db._id, v.nTaskType)
            tEvnetType[v.nTaskType] = 1
        end
    end

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

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

-- 获取任务奖励DB数据
local function CommerceActTask_GetTaskDB(human)
    if not human.db.ServerCommerce.Task then
        human.db.ServerCommerce.Task = {}
        CreatDB(human)
    end

    return human.db.ServerCommerce.Task
end

local function CommerceActTask_GetOpenTime(human)
    local nSatrtTime, nEndTime = ServerCommerceManager.CommerceAct_GetOpenAndEndTime()
    if 0 >= nSatrtTime or 0 >= nEndTime then
        print("[CommerceActTask_GetOpenTime] 获取的活动开始数据不正确 ")
        return 0
    end

    return nSatrtTime, nEndTime
end

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

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

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

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

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

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

    return tDBData.TaskPrize[nTaskType].nFinishNum
end

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

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

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

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

-- 获取任务积分奖励状态
local function CommerceActTask_GetTaskPointPrizeStatus(human, nID)
    local tDBData = CommerceActTask_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 CommerceActTask_SetTaskPointPrizeStatus(human, nID, nValue)
    local tDBData = CommerceActTask_GetTaskDB(human)
    tDBData.TaskPointPrize[nID] = nValue
end

-- 检查任务是否完成
local function CommerceActTask_CheckTaskStatus(human, nTaskType)
    local tConf = CommerceActTask_GetTaskCof()
    local nNowFinishNum = CommerceActTask_GetTaskFinishNum(human, nTaskType)
    print("[CommerceActTask_CheckTaskStatus] nNowFinishNum = "..nNowFinishNum)
    local nDay
    for nID, v in ipairs(tConf) do
        if v.nTaskType == nTaskType then
            if nNowFinishNum >= v.nValue then
                local nState = CommerceActTask_GetTaskStatus(human, nID, nTaskType)
                if CommonDefine.COMMON_PRIZE_STATE_NOGET == nState then
                    CommerceActTask_SetTaskStatus(human, nID, v.nTaskType, CommonDefine.COMMON_PRIZE_STATE_CANGET)
                    if not nDay then
                        nDay = v.nDay
                    end
                end
            else
                break
            end
        end
    end

--    if nil ~= nDay then
--         local nOpenTime = CommerceActTask_GetOpenTime(human)
--         local nDiffDay = Util.diffDay(nOpenTime)
--         if nDiffDay == nDay then
--             CommerceActTask_QueryTask(human, nDay)
--         end
--    end
end

-- 检查任务点数奖励状态
local function CommerceActTask_CheckTaskPointStatus(human)
    local nNowPoint = CommerceActTask_GetTaskPoint(human)
    local tConf = CommerceActTask_GetTaskPointCof()

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

    if true == bSendClient then
        CommerceActTask_QueryTaskPoint(human)
        ServerCommerceManager.CommerceAct_SendActInfo(human)
    end
end

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

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

    local nOldNum = CommerceActTask_GetTaskFinishNum(human, nEventType)

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

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

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

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

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

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

    CommerceActTask_CheckTaskStatus(human, nEventType)
end

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

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

----------------------------------------- 外部调用开始 -------------------------------------
function CommerceActTask_EventCallBack(nEventType, uuid, nValue1, nValue2)
    if not tEventHandler or not tEventHandler[nEventType] then
        ServerCommerceManager.CommerveManager_WriteLog("[CommerceActTask_EventCallBack] 不存在对应的回调处理函数 nEventType = "..nEventType)
        return
    end

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

function CommerceTask_AddPoint(human, nAddPoint)
    -- 增加积分
    CommerceActTask_AddTaskPoint(human, nAddPoint)

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

    -- 增加全服积分
    ServerCommerceManager.CommerveManager_AddServerPoint(nAddPoint)

    -- 增加个人积分
    ServerCommerceManager.CommerveManager_AddHumanPint(human, nAddPoint)
end

----------------------------------------- 客户端请求 -------------------------------------
-- 请求战区集结任务信息
function CommerceActTask_QueryTask(human, nDay)
    local tConf = CommerceActTask_GetTaskCof()
    local nOpenTime, nEndTime = CommerceActTask_GetOpenTime(human)
    if 0 >= nOpenTime or 0 >= nEndTime then
        print("[CommerceActTask_QueryTask] 获取的开服时间不正确")    
        return
    end

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

    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 = CommerceActTask_GetTaskStatus(human, nID, v.nTaskType)
            tNode.nDay = v.nDay
            tNode.nValue = v.nValue
            tNode.nPoint = v.nPoint
            tNode.Desc = v.szDes
            tNode.nFinish = CommerceActTask_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 = CommerceActTask_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)
end

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

    for nID, v in ipairs(tConf) do
        if v.nDay == nDay then
            local nState = CommerceActTask_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

                CommerceActTask_SetTaskStatus(human, nID, v.nTaskType, CommonDefine.COMMON_PRIZE_STATE_GET)
            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, "servercommerce")

        CommerceActTask_QueryTask(human, nDay)
        ServerCommerceManager.CommerceAct_SendActInfo(human)
        CommerceActTask_QueryTaskPoint(human)
    end
end

-- 请求任务积分信息
function CommerceActTask_QueryTaskPoint(human)
    local tConf = CommerceActTask_GetTaskPointCof()

    local tMsgData = Msg.gc.GC_SERVEERCOMMERCE_ACT_TASKPOINTQUERY
    tMsgData.nNowPoint = CommerceActTask_GetTaskPoint(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 = CommerceActTask_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 CommerceActTask_GetTaskPointPrize(human)
    local tConf = CommerceActTask_GetTaskPointCof()

    local tGoods = {}
    for nID, v in ipairs(tConf) do
        local nState = CommerceActTask_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

            CommerceActTask_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, "servercommerce")
        CommerceActTask_QueryTaskPoint(human)
        ServerCommerceManager.CommerceAct_SendActInfo(human)
    end
end

function isRed(human)
    local tConf = CommerceActTask_GetTaskCof()

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

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

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

    return false
end

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

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

    -- table.print_lua_table(tTaskType)

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

function onLogin(human)
    CommerceActTask_HumanSubEvent(human)
end