local Config = require("Config")
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local Util = require("common.Util")
local CommonDB = require("common.CommonDB")
local CombatLogic = require("combat.CombatLogic")

local QueryByNodeID = {nodeID = nil, nBattleType = nil}
function queryBattleDbByNodeID(nodeID, nBattleType)
    QueryByNodeID.nodeID = nodeID
    QueryByNodeID.nBattleType = nBattleType
    LuaMongo.find(DB.db_battle_shark, QueryByNodeID)
    local videoDb = {}
    return LuaMongo.next(videoDb) and videoDb
end

function updateBattleDB(roleBase,nodeID,combatInfo,videoUuid, nBattleType)
    local videoTb = queryBattleDbByNodeID(nodeID, nBattleType)
    local now = os.time()
    -- 如果没有战斗记录，插入战斗记录
    local useTime = CombatLogic.getCombatUseTime(combatInfo)
    if videoTb == nil then        
        local video = {}
        video.nodeID = nodeID
        video.nBattleType = nBattleType
        video.shark = {{},{},{}}
        video.shark[1].param = roleBase.zhandouli
        video.shark[1].videoUuid = videoUuid
        video.shark[1].roleBase = roleBase
        video.shark[2].param = useTime 
        video.shark[2].videoUuid = videoUuid
        video.shark[2].roleBase = roleBase
        video.shark[3].param = now
        video.shark[3].videoUuid = videoUuid
        video.shark[3].roleBase = roleBase
        LuaMongo.insert(DB.db_battle_shark, video)
    else
        local tempShark = videoTb.shark
        local isChange = nil
        -- 如果战力小，更换Uuid
        if roleBase.zhandouli < (videoTb.shark[1].param or 0) then
            tempShark[1].param = roleBase.zhandouli
            tempShark[1].videoUuid = videoUuid
            tempShark[1].roleBase = roleBase
            isChange = true
        end
        -- 拿出通关时间最短Uuid
        if useTime < videoTb.shark[2].param then
            tempShark[2].param = useTime
            tempShark[2].videoUuid = videoUuid
            tempShark[2].roleBase = roleBase
            isChange = true
        end 
        -- 拿出通关时间最近Uuid
        if now > videoTb.shark[3].param then
            tempShark[3].param = now
            tempShark[3].videoUuid = videoUuid
            tempShark[3].roleBase = roleBase
            isChange = true
        end
        QueryByNodeID.nodeID = nodeID
        QueryByNodeID.nBattleType = nBattleType
        LuaMongo.update(DB.db_battle_shark,QueryByNodeID,videoTb)
    end
end

