local _, ns = ...
local B, C, L, DB = unpack(ns)
local M = B:GetModule("Misc")

-- 模块变量
local dungeonData = {}
local isInDungeon = false
local dungeonStartTime = 0
local dungeonEndTime = 0
local summaryFrame = nil
local combatStats = {} -- 存储战斗统计数据

-- 全局表头定义
local headers = {"排名", "职业", "姓名", "装等", "DPS", "承受伤害", "治疗量", "死亡", "打断", "驱散"}

-- 职业颜色映射
local classColors = {
    ["WARRIOR"] = "|cFFC79C6E",
    ["PALADIN"] = "|cFFF58CBA",
    ["HUNTER"] = "|cFFABD473",
    ["ROGUE"] = "|cFFFFF569",
    ["PRIEST"] = "|cFFFFFFFF",
    ["DEATHKNIGHT"] = "|cFFC41F3B",
    ["SHAMAN"] = "|cFF0070DE",
    ["MAGE"] = "|cFF69CCF0",
    ["WARLOCK"] = "|cFF9482C9",
    ["MONK"] = "|cFF00FF96",
    ["DRUID"] = "|cFFFF7D0A",
    ["DEMONHUNTER"] = "|cFFA330C9",
    ["EVOKER"] = "|cFF33937F"
}

-- 职业图标坐标
local class_icon_tcoords = {
    ["WARRIOR"] = {0, 0.25, 0, 0.25},
    ["MAGE"] = {0.25, 0.49609375, 0, 0.25},
    ["ROGUE"] = {0.49609375, 0.7421875, 0, 0.25},
    ["DRUID"] = {0.7421875, 0.98828125, 0, 0.25},
    ["HUNTER"] = {0, 0.25, 0.25, 0.5},
    ["SHAMAN"] = {0.25, 0.49609375, 0.25, 0.5},
    ["PRIEST"] = {0.49609375, 0.7421875, 0.25, 0.5},
    ["WARLOCK"] = {0.7421875, 0.98828125, 0.25, 0.5},
    ["PALADIN"] = {0, 0.25, 0.5, 0.75},
    ["DEATHKNIGHT"] = {0.25, 0.49609375, 0.5, 0.75},
    ["MONK"] = {0.49609375, 0.7421875, 0.5, 0.75},
    ["DEMONHUNTER"] = {0.7421875, 0.98828125, 0.5, 0.75},
    ["EVOKER"] = {0, 0.25, 0.75, 1.0}
}

-- 职责图标坐标
local role_icon_tcoords = {
    ["DAMAGER"] = {0.3125, 0.625, 0.3125, 0.625},
    ["HEALER"] = {0.3125, 0.625, 0.015625, 0.3125},
    ["TANK"] = {0, 0.296875, 0.3125, 0.625}
}

-- 创建职业图标
local function CreateClassIcon(parent, class, size)
    local icon = parent:CreateTexture(nil, "OVERLAY")
    icon:SetSize(size or 16, size or 16)
    icon:SetTexture("Interface\\Glues\\CharacterCreate\\UI-CharacterCreate-Classes")
    
    if class_icon_tcoords[class] then
        local coords = class_icon_tcoords[class]
        icon:SetTexCoord(coords[1], coords[2], coords[3], coords[4])
    end
    
    return icon
end

-- 创建职责图标
local function CreateRoleIcon(parent, role, size)
    local icon = parent:CreateTexture(nil, "HIGHLIGHT")
    icon:SetSize(size or 16, size or 16)
    icon:SetTexture("Interface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES")
    
    if role_icon_tcoords[role] then
        local coords = role_icon_tcoords[role]
        icon:SetTexCoord(coords[1], coords[2], coords[3], coords[4])
    end
    
    return icon
end

-- 缓存装等数据
local itemLevelCache = {}

-- 获取玩家装备等级
local function GetPlayerItemLevel(playerName, unit)
    if playerName == DB.MyName then
        local avgItemLevel = GetAverageItemLevel()
        itemLevelCache[playerName] = math.floor(avgItemLevel or 0)
        return itemLevelCache[playerName]
    else
        if itemLevelCache[playerName] then
            return itemLevelCache[playerName]
        end
        
        if unit and UnitExists(unit) then
            local avgItemLevel = GetAverageItemLevel()
            itemLevelCache[playerName] = math.floor(avgItemLevel or 0)
            return itemLevelCache[playerName]
        end
        
        return 0
    end
end

-- 格式化数字（缩写）
local function FormatNumber(num)
    if not num or num == 0 then return "0" end
    if num >= 1000000 then
        return format("%.1fM", num / 1000000)
    elseif num >= 1000 then
        return format("%.1fK", num / 1000)
    else
        return tostring(num)
    end
end

-- 收集队伍成员数据（使用官方 API）
local function CollectGroupData()
    local groupData = {}
    local groupSize = GetNumGroupMembers()
    
    if groupSize == 0 then
        groupSize = 1
    end
    
    local isRaid = IsInRaid()
    
    for i = 1, groupSize do
        local unit
        if groupSize == 1 then
            unit = "player"
        elseif isRaid then
            unit = "raid" .. i
        else
            unit = (i == 1) and "player" or ("party" .. (i - 1))
        end
        
        if UnitExists(unit) then
            local name = UnitName(unit)
            local _, class = UnitClass(unit)
            local itemLevel = GetPlayerItemLevel(name, unit)
            local role = UnitGroupRolesAssigned(unit) or "DAMAGER"
            local guid = UnitGUID(unit)
            
            -- 从收集的战斗统计数据中获取
            local stats = combatStats[guid] or {}
            
            local playerData = {
                name = name,
                class = class,
                role = role,
                itemLevel = itemLevel,
                damage = stats.damage or 0,
                dps = stats.dps or 0,
                damageTaken = stats.damageTaken or 0,
                healing = stats.healing or 0,
                deaths = stats.deaths or 0,
                interrupts = stats.interrupts or 0,
                dispels = stats.dispels or 0
            }
            
            table.insert(groupData, playerData)
        end
    end
    
    -- 按伤害降序排序
    table.sort(groupData, function(a, b)
        return a.damage > b.damage
    end)
    
    return groupData
end

-- 创建统计界面
local function CreateSummaryFrame()
    if summaryFrame then
        summaryFrame:Hide()
        summaryFrame = nil
    end
    
    -- 创建主框架
    summaryFrame = CreateFrame("Frame", "OrzUIDungeonSummary", UIParent)
    summaryFrame:SetSize(900, 400)
    summaryFrame:SetPoint("CENTER")
    summaryFrame:SetMovable(true)
    summaryFrame:EnableMouse(true)
    summaryFrame:RegisterForDrag("LeftButton")
    summaryFrame:SetScript("OnDragStart", summaryFrame.StartMoving)
    summaryFrame:SetScript("OnDragStop", summaryFrame.StopMovingOrSizing)
    summaryFrame:SetFrameStrata("HIGH")
    B.CreateMF(summaryFrame)
    
    -- 主背景
    summaryFrame.bg = B.SetBD(summaryFrame)
    
    -- 标题区域
    local titleBg = summaryFrame:CreateTexture(nil, "ARTWORK")
    titleBg:SetPoint("TOPLEFT", summaryFrame, "TOPLEFT", 15, -15)
    titleBg:SetPoint("TOPRIGHT", summaryFrame, "TOPRIGHT", -15, -15)
    titleBg:SetHeight(50)
    titleBg:SetColorTexture(0, 0, 0, 0.3)
    
    -- 标题文字
    summaryFrame.title = summaryFrame:CreateFontString(nil, "OVERLAY")
    summaryFrame.title:SetFontObject("GameFontNormalHuge")
    summaryFrame.title:SetPoint("CENTER", titleBg, "CENTER", 0, 0)
    
    -- 获取当前地下城名称和层数
    local instanceName = GetInstanceInfo()
    local keystoneLevel = C_ChallengeMode and C_ChallengeMode.GetActiveKeystoneInfo and C_ChallengeMode.GetActiveKeystoneInfo() or nil
    
    if instanceName and instanceName ~= "" then
        if keystoneLevel and keystoneLevel > 0 then
            summaryFrame.title:SetText("|cFFFFD700" .. instanceName .. " +" .. keystoneLevel .. "|r")
        else
            summaryFrame.title:SetText("|cFFFFD700" .. instanceName .. "|r")
        end
    else
        summaryFrame.title:SetText("|cFFFFD700地下城统计报告|r")
    end
    
    -- 关闭按钮
    local closeBtn = CreateFrame("Button", nil, summaryFrame)
    closeBtn:SetSize(28, 28)
    closeBtn:SetPoint("TOPRIGHT", summaryFrame, "TOPRIGHT", -20, -20)
    B.ReskinClose(closeBtn)
    closeBtn:SetScript("OnClick", function()
        summaryFrame:Hide()
    end)
    
    summaryFrame.closeBtn = closeBtn
    
    return summaryFrame
end

-- 显示统计数据
local function ShowDungeonSummary()
    local groupData = CollectGroupData()
    
    if #groupData == 0 then
        return
    end
    
    local frame = CreateSummaryFrame()
    
    -- 数据区域背景
    local dataBg = frame:CreateTexture(nil, "ARTWORK")
    dataBg:SetPoint("TOPLEFT", frame, "TOPLEFT", 20, -80)
    dataBg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -20, 20)
    dataBg:SetColorTexture(0, 0, 0, 0.2)
    
    -- 表头设置
    local headerHeight = 35
    local rowHeight = 40
    local startY = -90
    local yOffset = startY
    
    -- 表头背景
    local headerBg = frame:CreateTexture(nil, "OVERLAY")
    headerBg:SetPoint("TOPLEFT", frame, "TOPLEFT", 25, yOffset)
    headerBg:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -25, yOffset)
    headerBg:SetHeight(headerHeight)
    headerBg:SetColorTexture(0, 0, 0, 0.4)
    
    -- 表头文字
    local headerWidths = {50, 80, 100, 60, 100, 100, 100, 50, 60, 60}
    local xPos = 35
    
    for i, header in ipairs(headers) do
        local headerText = frame:CreateFontString(nil, "OVERLAY")
        headerText:SetFontObject("GameFontNormal")
        headerText:SetPoint("CENTER", frame, "TOPLEFT", xPos + (headerWidths[i] / 2), yOffset - 17)
        headerText:SetText("|cFFFFD700" .. header .. "|r")
        xPos = xPos + headerWidths[i]
    end
    
    yOffset = yOffset - headerHeight
    
    -- 计算各类数据的最高值
    local maxValues = {
        dps = 0,
        damageTaken = 0,
        healing = 0,
        interrupts = 0,
        dispels = 0
    }
    
    for _, playerData in ipairs(groupData) do
        if playerData.dps and playerData.dps > maxValues.dps then
            maxValues.dps = playerData.dps
        end
        if playerData.damageTaken and playerData.damageTaken > maxValues.damageTaken then
            maxValues.damageTaken = playerData.damageTaken
        end
        if playerData.healing and playerData.healing > maxValues.healing then
            maxValues.healing = playerData.healing
        end
        if playerData.interrupts and playerData.interrupts > maxValues.interrupts then
            maxValues.interrupts = playerData.interrupts
        end
        if playerData.dispels and playerData.dispels > maxValues.dispels then
            maxValues.dispels = playerData.dispels
        end
    end
    
    -- 显示玩家数据
    for rank, playerData in ipairs(groupData) do
        -- 行背景（交替颜色）
        if rank % 2 == 0 then
            local rowBg = frame:CreateTexture(nil, "ARTWORK")
            rowBg:SetPoint("TOPLEFT", frame, "TOPLEFT", 25, yOffset)
            rowBg:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -25, yOffset)
            rowBg:SetHeight(rowHeight)
            rowBg:SetColorTexture(1, 1, 1, 0.05)
        end
        
        xPos = 35
        
        -- 排名
        local rankText = frame:CreateFontString(nil, "OVERLAY")
        rankText:SetFontObject("GameFontNormal")
        rankText:SetPoint("CENTER", frame, "TOPLEFT", xPos + 25, yOffset - 20)
        if rank == 1 then
            rankText:SetText("|cFFFFD7001|r")
        elseif rank == 2 then
            rankText:SetText("|cFFC0C0C02|r")
        elseif rank == 3 then
            rankText:SetText("|cFFCD7F323|r")
        else
            rankText:SetText("|cFFCCCCCC" .. rank .. "|r")
        end
        xPos = xPos + headerWidths[1]
        
        -- 职业图标
        local classIcon = CreateClassIcon(frame, playerData.class, 20)
        classIcon:SetPoint("CENTER", frame, "TOPLEFT", xPos + 40, yOffset - 20)
        
        -- 职责图标
        local roleIcon = CreateRoleIcon(frame, playerData.role, 12)
        roleIcon:SetPoint("CENTER", frame, "TOPLEFT", xPos + 40 + 12, yOffset - 20 + 6)
        xPos = xPos + headerWidths[2]
        
        -- 姓名
        local nameText = frame:CreateFontString(nil, "OVERLAY")
        nameText:SetFontObject("GameFontNormal")
        nameText:SetPoint("LEFT", frame, "TOPLEFT", xPos + 5, yOffset - 20)
        local color = classColors[playerData.class] or "|cFFFFFFFF"
        nameText:SetText(color .. playerData.name .. "|r")
        xPos = xPos + headerWidths[3]
        
        -- 数据列 (对应 headerWidths[4] 到 headerWidths[10])
        local dataColumns = {
            {value = playerData.itemLevel > 0 and tostring(playerData.itemLevel) or "-", maxValue = nil},
            {value = FormatNumber(playerData.dps), maxValue = maxValues.dps, key = "dps", color = "|cFFFF8800"},
            {value = FormatNumber(playerData.damageTaken), maxValue = maxValues.damageTaken, key = "damageTaken", color = "|cFFFF8800"},
            {value = FormatNumber(playerData.healing), maxValue = maxValues.healing, key = "healing", color = "|cFF00FF88"},
            {value = tostring(playerData.deaths), maxValue = nil, key = "deaths", warning = true},
            {value = tostring(playerData.interrupts), maxValue = maxValues.interrupts, key = "interrupts", color = "|cFF00FF00"},
            {value = tostring(playerData.dispels), maxValue = maxValues.dispels, key = "dispels", color = "|cFF4488FF"}
        }
        
        for i, colData in ipairs(dataColumns) do
            local dataText = frame:CreateFontString(nil, "OVERLAY")
            dataText:SetFontObject("GameFontNormal")
            local headerIndex = i + 3 -- headerWidths[4] 对应 dataColumns[1]
            dataText:SetPoint("CENTER", frame, "TOPLEFT", xPos + (headerWidths[headerIndex] / 2), yOffset - 20)
            
            local data = colData.value
            local key = colData.key
            
            if key and playerData[key] == colData.maxValue and colData.maxValue > 0 then
                -- 最高值用金色
                dataText:SetText("|cFFFFD700" .. data .. "|r")
            elseif colData.warning and tonumber(playerData[key]) > 0 then
                -- 死亡警告用红色
                dataText:SetText("|cFFFF0000" .. data .. "|r")
            elseif colData.color then
                -- 使用指定颜色
                dataText:SetText(colData.color .. data .. "|r")
            else
                dataText:SetText("|cFFCCCCCC" .. data .. "|r")
            end
            
            xPos = xPos + headerWidths[headerIndex]
        end
        
        yOffset = yOffset - rowHeight
    end
    
    frame:Show()
end

-- 战斗日志事件处理
local function OnCombatLogEvent(_, ...)
    local timestamp, subevent, _, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, 
          destGUID, destName, destFlags, destRaidFlags = ...
    
    -- 只处理队伍/团队成员的事件
    local isSourcePlayer = bit.band(sourceFlags, COMBATLOG_OBJECT_AFFILIATION_MASK) <= COMBATLOG_OBJECT_AFFILIATION_RAID
    local isDestPlayer = bit.band(destFlags, COMBATLOG_OBJECT_AFFILIATION_MASK) <= COMBATLOG_OBJECT_AFFILIATION_RAID
    
    if not isSourcePlayer and not isDestPlayer then return end
    
    -- 初始化玩家数据
    if not combatStats[sourceGUID] then
        combatStats[sourceGUID] = {
            name = sourceName,
            damage = 0,
            dps = 0,
            damageTaken = 0,
            healing = 0,
            deaths = 0,
            interrupts = 0,
            dispels = 0
        }
    end
    
    if not combatStats[destGUID] then
        combatStats[destGUID] = {
            name = destName,
            damage = 0,
            dps = 0,
            damageTaken = 0,
            healing = 0,
            deaths = 0,
            interrupts = 0,
            dispels = 0
        }
    end
    
    -- 伤害事件
    if subevent == "SWING_DAMAGE" then
        local amount = select(12, ...)
        if isSourcePlayer and amount then
            combatStats[sourceGUID].damage = combatStats[sourceGUID].damage + amount
        end
        if isDestPlayer and amount then
            combatStats[destGUID].damageTaken = combatStats[destGUID].damageTaken + amount
        end
    elseif subevent == "SPELL_DAMAGE" or subevent == "SPELL_PERIODIC_DAMAGE" or 
           subevent == "RANGE_DAMAGE" or subevent == "SPELL_BUILDING_DAMAGE" then
        local amount = select(15, ...)
        if isSourcePlayer and amount then
            combatStats[sourceGUID].damage = combatStats[sourceGUID].damage + amount
        end
        if isDestPlayer and amount then
            combatStats[destGUID].damageTaken = combatStats[destGUID].damageTaken + amount
        end
    end
    
    -- 治疗事件
    if subevent == "SPELL_HEAL" or subevent == "SPELL_PERIODIC_HEAL" then
        local amount = select(15, ...)
        if isSourcePlayer and amount then
            combatStats[sourceGUID].healing = combatStats[sourceGUID].healing + amount
        end
    end
    
    -- 死亡事件
    if subevent == "UNIT_DIED" or subevent == "UNIT_DESTROYED" then
        if isDestPlayer then
            combatStats[destGUID].deaths = combatStats[destGUID].deaths + 1
        end
    end
    
    -- 打断事件
    if subevent == "SPELL_INTERRUPT" then
        if isSourcePlayer then
            combatStats[sourceGUID].interrupts = combatStats[sourceGUID].interrupts + 1
        end
    end
    
    -- 驱散事件
    if subevent == "SPELL_DISPEL" or subevent == "SPELL_STOLEN" then
        if isSourcePlayer then
            combatStats[sourceGUID].dispels = combatStats[sourceGUID].dispels + 1
        end
    end
end

-- 计算 DPS
local function CalculateDPS()
    local duration = dungeonEndTime - dungeonStartTime
    if duration <= 0 then duration = 1 end
    
    for guid, stats in pairs(combatStats) do
        stats.dps = stats.damage / duration
    end
end

-- 重置统计数据
local function ResetCombatStats()
    combatStats = {}
end

-- 大秘境开始
local function OnChallengeModeStart()
    isInDungeon = true
    dungeonStartTime = GetTime()
    dungeonData = {}
    ResetCombatStats()
end

-- 大秘境完成
local function OnChallengeModeCompleted()
    if isInDungeon then
        dungeonEndTime = GetTime()
        CalculateDPS()
        -- 延迟1秒显示统计，确保数据收集完整
        C_Timer.After(1, function()
            ShowDungeonSummary()
        end)
        isInDungeon = false
    end
end

-- 区域改变
local function OnZoneChanged()
    local inInstance, instanceType = IsInInstance()
    if inInstance and instanceType == "party" then
        if not isInDungeon then
            isInDungeon = true
            dungeonStartTime = GetTime()
            dungeonData = {}
            ResetCombatStats()
        end
    else
        if isInDungeon then
            dungeonEndTime = GetTime()
            CalculateDPS()
            -- 普通地下城完成，延迟显示统计
            C_Timer.After(1, function()
                ShowDungeonSummary()
            end)
            isInDungeon = false
        end
    end
end

-- 玩家进入世界
local function OnPlayerEnteringWorld()
    local inInstance, instanceType = IsInInstance()
    if inInstance and instanceType == "party" then
        isInDungeon = true
        dungeonStartTime = GetTime()
        dungeonData = {}
        ResetCombatStats()
    else
        isInDungeon = false
    end
end

-- 初始化模块
function M:DungeonSummary()
    if not C.db["Misc"]["DungeonSummary"] then return end
    -- 注册事件
    B:RegisterEvent("CHALLENGE_MODE_START", OnChallengeModeStart)
    B:RegisterEvent("CHALLENGE_MODE_COMPLETED", OnChallengeModeCompleted)
    B:RegisterEvent("ZONE_CHANGED_NEW_AREA", OnZoneChanged)
    B:RegisterEvent("PLAYER_ENTERING_WORLD", OnPlayerEnteringWorld)
    --B:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED", OnCombatLogEvent)
end

-- 测试命令
SLASH_ORZUIDUNGEONSUMMARY1 = "/dgs"
SlashCmdList["ORZUIDUNGEONSUMMARY"] = function()
    -- 创建测试数据
    combatStats = {
        [UnitGUID("player")] = {
            name = DB.MyName,
            damage = 12500000,
            dps = 45000,
            damageTaken = 3200000,
            healing = 850000,
            deaths = 1,
            interrupts = 8,
            dispels = 3
        }
    }
    
    -- 添加模拟队友数据
    for i = 1, 4 do
        local guid = "TestGUID-" .. i
        combatStats[guid] = {
            name = "老胡" .. i,
            damage = 10000000 + math.random(5000000),
            dps = 35000 + math.random(15000),
            damageTaken = 2500000 + math.random(2000000),
            healing = 500000 + math.random(1000000),
            deaths = math.random(3),
            interrupts = math.random(10),
            dispels = math.random(5)
        }
    end
    
    dungeonStartTime = GetTime() - 600
    dungeonEndTime = GetTime()
    CalculateDPS()
    ShowDungeonSummary()
end
