--跨服服务器, 合服后的处理逻辑

local Config = require("Config")
local MergeServerDefine = require("merge.MergeServerDefine")
local GodsAreaDB = require("godsArea.GodsAreaDB")


-- 服务器服号起始值
local SRV_BASE_NUM = 810537


local function getDBInfo()
    for _, chanelId in ipairs(Config.SVR_CHANEL) do
        if MergeServerDefine.MERGE_CHECK_TB[chanelId] then
            return MergeServerDefine.MERGE_CHECK_TB[chanelId]
        end
    end
end


local function generateArray()
    local dbBaseArray = getDBInfo()
    if not dbBaseArray then
        return
    end

    local updateTb, removeTb = {}, {}

    for _, v in ipairs(dbBaseArray) do
        -- local targetChannelId = v[1][1]
        local targetServerId = v[1][2]
        local newSrvId = targetServerId + SRV_BASE_NUM

        for i=2, #v do
            local dbInfo = v[i]
            local channelId = dbInfo[1]
            local serverId = dbInfo[2]
            local opType = dbInfo[3]
            local oldSrvId = serverId + SRV_BASE_NUM

            if table.find(Config.SVR_CHANEL, channelId) then
                -- 同个跨服内合并
                if opType == 1 then
                    updateTb[oldSrvId] = newSrvId
                end

                -- 合并到其他跨服
                if opType == 2 then
                    removeTb[oldSrvId] = true
                end
            end

        end
    end

    return updateTb, removeTb
end




function AfterStart()
    if _G.is_middle ~= true then return end

    if not next(MergeServerDefine.MERGE_CHECK_TB) then
        return
    end

    local updateTb, removeTb = generateArray()
    if (not updateTb and not removeTb) or (not next(updateTb) and not next(removeTb)) then
        return
    end

    GodsAreaDB.UpdateAfterMergeSrv(updateTb, removeTb)
end