-- ## Version: 1.1.0 ## Author: YourName ## SavedVariables: MonsterKillCounterDB 命令/mkc
-- 插件名称
--local addonName = "MonsterKillCounter"

-- 确保数据库结构存在
if not MonsterKillCounterDB then
    MonsterKillCounterDB = {}
end

-- 初始化数据库结构
if not MonsterKillCounterDB.accountData then
    MonsterKillCounterDB.accountData = {
        totalKills = 0,
        characters = {}
    }
end

if not MonsterKillCounterDB.settings then
    MonsterKillCounterDB.settings = {
        targetStatisticID = 19386,
        autoAnnounce = true,
        debug = false  -- 添加调试开关，默认关闭
    }
end

-- 本地函数
local function GetCharacterKey()
    -- 创建角色唯一标识：服务器-角色名
    local realmName = GetRealmName()
    local characterName = UnitName("player")
    return realmName .. "-" .. characterName
end

local function GetCurrentKillCount()
    local statisticID = MonsterKillCounterDB.settings.targetStatisticID
    local value = GetStatistic(statisticID)
    
    if value and value ~= "--" and value ~= "" then
        return tonumber(value) or 0
    end
    return 0
end

local function PrintMessage(message)
    print("|cFF00FF00[猫头鹰]|r " .. message)  --击杀统计
end

local function AnnounceKills(channel)
    local characterKey = GetCharacterKey()
    local currentKills = GetCurrentKillCount()
    
    -- 确保 characters 表存在
    if not MonsterKillCounterDB.accountData.characters then
        MonsterKillCounterDB.accountData.characters = {}
    end
    
    -- 更新当前角色数据
    MonsterKillCounterDB.accountData.characters[characterKey] = {
        kills = currentKills,
        lastUpdated = time(),
        class = UnitClass("player"),
        level = UnitLevel("player")
    }
    
    -- 重新计算账号总击杀数
    local totalKills = 0
    for _, charData in pairs(MonsterKillCounterDB.accountData.characters) do
        totalKills = totalKills + (charData.kills or 0)
    end
    MonsterKillCounterDB.accountData.totalKills = totalKills
    
    -- 获取当前角色信息
    local className, classFileName = UnitClass("player")
    local classColor = RAID_CLASS_COLORS[classFileName] or {r=1, g=1, b=1}
    local classColorStr = string.format("|cFF%02x%02x%02x", 
        classColor.r*255, classColor.g*255, classColor.b*255)
    
    -- 格式化消息
    local message = string.format("%s%s|r 已击杀 |cFFFFFF00%d|r 只怪物，账号总计 |cFFFFFF00%d|r 只怪物",
        classColorStr, UnitName("player"), currentKills, totalKills)
    
    -- 输出到指定频道或默认说
    if channel and (channel == "say" or channel == "SAY") then
        SendChatMessage(message, "SAY")
    elseif channel and (channel == "yell" or channel == "YELL") then
        SendChatMessage(message, "YELL")
    elseif channel and (channel == "guild" or channel == "GUILD" or channel == "g") then
        if IsInGuild() then
            SendChatMessage(message, "GUILD")
        else
            PrintMessage("你不在公会中，无法发送公会消息")
        end
    else
    -- 默认在说频道显示
        SendChatMessage(message, "SAY")
    end
    
    -- 同时在聊天框显示
    PrintMessage(string.format("当前角色猫头鹰击杀数: |cFFFFFF00%d|r, 账号总击杀数: |cFFFFFF00%d|r", 
        currentKills, totalKills))
end

local function ShowCharacterList()
    PrintMessage("账号下角色击杀统计:")
    
    -- 确保 characters 表存在
    if not MonsterKillCounterDB.accountData.characters then
        PrintMessage("暂无角色数据")
        return
    end
    
    local characters = MonsterKillCounterDB.accountData.characters
    if not next(characters) then
        PrintMessage("暂无角色数据")
        return
    end
    
    local total = 0
    local count = 0
    
    for charKey, charData in pairs(characters) do
        local kills = charData.kills or 0
        local class = charData.class or "未知"
        local level = charData.level or 0
        local lastUpdated = charData.lastUpdated or 0
        
        -- 解析服务器和角色名
        local realm, name = charKey:match("^(.*)-(.*)$")
        if not realm then
            realm = "未知服务器"
            name = charKey
        end
        
        -- 计算时间间隔
        local timeAgo = ""
        if lastUpdated > 0 then
            local diff = time() - lastUpdated
            if diff < 3600 then -- 1小时内
                timeAgo = string.format("|cFF808080(%.0f分钟前)|r", diff/60)
            elseif diff < 86400 then -- 24小时内
                timeAgo = string.format("|cFF808080(%.1f小时前)|r", diff/3600)
            else
                timeAgo = string.format("|cFF808080(%.0f天前)|r", diff/86400)
            end
        end
        
        print(string.format("  %s |cFFFFFF00Lv.%d|r %s: |cFFFFFF00%d|r 次 %s", 
            class, level, name, kills, timeAgo))
        
        total = total + kills
        count = count + 1
    end
    
    PrintMessage(string.format("总计 |cFFFFFF00%d|r 个角色，总击杀数: |cFFFFFF00%d|r", count, total))
end

-- 更新角色数据，新增可选参数 silent：为 true 时不打印“新增击杀”提示
local function UpdateCharacterData(silent)
    local characterKey = GetCharacterKey()
    local currentKills = GetCurrentKillCount()
    local lastKills = 0
    
    -- 确保 characters 表存在
    if not MonsterKillCounterDB.accountData.characters then
        MonsterKillCounterDB.accountData.characters = {}
    end
    
    if MonsterKillCounterDB.accountData.characters[characterKey] then
        lastKills = MonsterKillCounterDB.accountData.characters[characterKey].kills or 0
    end
    
    -- 更新角色数据
    MonsterKillCounterDB.accountData.characters[characterKey] = {
        kills = currentKills,
        lastUpdated = time(),
        class = UnitClass("player"),
        level = UnitLevel("player"),
        realm = GetRealmName(),
        name = UnitName("player")
    }
    
    -- 如果有新增击杀且不是静默模式，显示“新增击杀”提示
    if currentKills > lastKills and lastKills > 0 and not silent then
        local newKills = currentKills - lastKills
        PrintMessage(string.format("新增 |cFFFFFF00%d|r 次击杀，当前总计: |cFFFFFF00%d|r", 
            newKills, currentKills))
    end
    
    -- 重新计算总击杀数
    local totalKills = 0
    for _, charData in pairs(MonsterKillCounterDB.accountData.characters) do
        totalKills = totalKills + (charData.kills or 0)
    end
    MonsterKillCounterDB.accountData.totalKills = totalKills
    
    return currentKills
end

-- 事件处理
local frame = CreateFrame("Frame")
frame:RegisterEvent("PLAYER_LOGIN")
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("ENCOUNTER_END")  -- 监听副本战斗结束
frame:RegisterEvent("ZONE_CHANGED_NEW_AREA") -- 监听区域变化（用于进入副本检测）
frame:RegisterEvent("PLAYER_LOGOUT") -- 退出时保存数据

local function OnAddonLoaded()
    --PrintMessage("插件已加载")
    
    -- 确保数据库结构正确
    if not MonsterKillCounterDB.accountData then
        MonsterKillCounterDB.accountData = {
            totalKills = 0,
            characters = {}
        }
    end
    
    if not MonsterKillCounterDB.settings then
        MonsterKillCounterDB.settings = {
            targetStatisticID = 19386,
            autoAnnounce = true,
            debug = false
        }
    end
    
    -- 显示当前状态
    local charCount = 0
    local characters = MonsterKillCounterDB.accountData.characters or {}
    for _ in pairs(characters) do
        charCount = charCount + 1
    end
    
    --PrintMessage(string.format("已记录 |cFFFFFF00%d|r 个角色，账号总击杀数: |cFFFFFF00%d|r", charCount, MonsterKillCounterDB.accountData.totalKills or 0))
    --PrintMessage("输入 |cFFFFFF00/mkc help|r 查看命令帮助。")
end

-- 定义发送团队消息的函数（带重试机制）
local function SendRaidMessageWithRetry(message, retryCount, maxRetries)
    retryCount = retryCount or 1
    maxRetries = maxRetries or 3
    
    if IsInRaid() then
        SendChatMessage(message, "RAID")
        if MonsterKillCounterDB.settings.debug then
            PrintMessage(string.format("团队消息已发送（重试次数：%d）", retryCount - 1))
        end
    else
        if retryCount <= maxRetries then
            C_Timer.After(1, function()
                SendRaidMessageWithRetry(message, retryCount + 1, maxRetries)
            end)
        else
            if MonsterKillCounterDB.settings.debug then
                PrintMessage("无法发送团队消息：不在团队中（已重试3次）")
            end
            -- 可选：降级到说频道
            -- SendChatMessage(message, "SAY")
        end
    end
end

frame:SetScript("OnEvent", function(self, event, ...)
    -- 初始化状态变量（仅首次）
    if self.wasInTargetInstance == nil then
        self.wasInTargetInstance = false
    end

    if event == "ADDON_LOADED" then
        local loadedAddon = ...
        if loadedAddon == "OrzUI" then
            OnAddonLoaded()
        end
    elseif event == "PLAYER_LOGIN" then
        -- 玩家登录时更新数据（显示“新增击杀”提示）
        C_Timer.After(3, function()
            local currentKills = UpdateCharacterData()  -- silent 默认 false，显示提示
            if MonsterKillCounterDB.settings.autoAnnounce then
                PrintMessage(string.format("当前角色击杀数: |cFFFFFF00%d|r, 账号总击杀数: |cFFFFFF00%d|r",
                    currentKills, MonsterKillCounterDB.accountData.totalKills or 0))
            end
        end)
    elseif event == "PLAYER_ENTERING_WORLD" then
        local isLogin, isReload = ...
        if isLogin or isReload then
            -- 登录或重载时更新数据（显示“新增击杀”提示）
            C_Timer.After(2, function() UpdateCharacterData() end)
        end
    elseif event == "ENCOUNTER_END" then
        -- 参数：encounterID, encounterName, difficultyID, raidSize, endStatus
        local encounterID, encounterName, difficultyID, raidSize, endStatus = ...
        -- 仅当击杀成功（endStatus == 1）、史诗难度（difficultyID == 16）、目标为火光之龙菲莱克（encounterID == 2677）
        if endStatus == 1 and difficultyID == 16 and (encounterName == "火光之龙菲莱克" or encounterName == "Fyrakk the Blazing") then
            if MonsterKillCounterDB.settings.debug then  --开启调试开关的时候会打印击杀尾王信息
                PrintMessage(string.format("检测到击杀尾王：%s (ID:%d)", encounterName, encounterID))
            end
            -- 延迟一小段时间确保统计信息已更新
            C_Timer.After(0.5, function()
                UpdateCharacterData(true)  -- 静默更新，不显示“新增击杀”
                local current = GetCurrentKillCount()
                local total = MonsterKillCounterDB.accountData.totalKills or 0
                PrintMessage(string.format("当前角色击杀数: |cFFFFFF00%d|r, 账号总击杀数: |cFFFFFF00%d|r", current, total))

                -- 发送团队消息（带重试机制，最多尝试3次）
                local plainMsg = string.format("当前角色击杀数:%d, 账号总击杀数:%d", current, total)
                SendRaidMessageWithRetry(plainMsg, 1, 3)
            end)
        end
    elseif event == "ZONE_CHANGED_NEW_AREA" then
        -- 检测是否进入史诗难度阿梅达希尔副本
        local inInstance = IsInInstance()
        if inInstance then
            local name, instanceType, difficultyID, difficultyName = GetInstanceInfo()
            -- 目标副本名称和难度（史诗难度ID为16）
            local targetName = "阿梅达希尔，梦境之愿"
            if name == targetName and difficultyID == 16 then
                -- 现在在目标副本中
                if not self.wasInTargetInstance then
                    -- 刚进入目标副本，打印信息
                    UpdateCharacterData(true) -- 静默更新数据
                    local charCount = 0
                    if MonsterKillCounterDB.accountData.characters then
                        for _ in pairs(MonsterKillCounterDB.accountData.characters) do
                            charCount = charCount + 1
                        end
                    end
                    local totalKills = MonsterKillCounterDB.accountData.totalKills or 0
                    PrintMessage(string.format("已记录 |cFFFFFF00%d|r 个角色，账号总击杀数:|cFFFFFF00%d|r", charCount, totalKills))
                    --PrintMessage("输入 |cFFFFFF00/mkc|r 查看击杀次数")
                    
                    --[[ ===== 新增：进入副本时在团队频道发送固定消息 =====
                    if IsInRaid() then
                        SendChatMessage("GOGOGO", "RAID")
                    end
                    -- ==============================================]]
                end
                self.wasInTargetInstance = true
            else
                -- 不在目标副本中
                self.wasInTargetInstance = false
            end
        else
            -- 不在任何副本中
            self.wasInTargetInstance = false
        end
    elseif event == "PLAYER_LOGOUT" then
        -- 角色离开世界时保存数据（显示“新增击杀”提示）
        UpdateCharacterData()  -- silent 默认 false，但退出时 print 可能不可见，保留逻辑无影响
    end
end)

-- 创建斜杠命令
SLASH_MONSTERKILLCOUNTER1 = "/mkc"
SLASH_MONSTERKILLCOUNTER2 = "/mty"
SLASH_MONSTERKILLCOUNTER3 = "/monsterkill"
SlashCmdList["MONSTERKILLCOUNTER"] = function(msg)
    msg = msg:trim()
    
    if msg == "" then
        -- 静默更新数据，不显示“新增击杀”提示
        local currentKills = UpdateCharacterData(true)
        PrintMessage(string.format("当前角色击杀数: |cFFFFFF00%d|r, 账号总击杀数: |cFFFFFF00%d|r",
            currentKills, MonsterKillCounterDB.accountData.totalKills or 0))
    elseif msg:lower() == "announce" or msg:lower() == "say" then
        -- 在说频道宣布
        AnnounceKills("say")
    elseif msg:lower() == "yell" then
        -- 在喊话频道宣布
        AnnounceKills("yell")
    elseif msg:lower() == "guild" or msg:lower() == "g" then
        -- 在公会频道宣布
        AnnounceKills("guild")
    elseif msg:lower() == "list" or msg:lower() == "chars" then
        -- 静默更新数据，再显示所有角色列表
        UpdateCharacterData(true)
        ShowCharacterList()
    elseif msg:lower() == "update" then
        -- 手动更新数据
        local currentKills = UpdateCharacterData()
        PrintMessage(string.format("数据已更新！当前角色猫头鹰击杀数: |cFFFFFF00%d|r", currentKills))
    elseif msg:lower() == "auto" then
        -- 切换自动显示
        MonsterKillCounterDB.settings.autoAnnounce = not MonsterKillCounterDB.settings.autoAnnounce
        PrintMessage(string.format("登录时自动显示: |cFFFFFF00%s|r",
            MonsterKillCounterDB.settings.autoAnnounce and "开启" or "关闭"))
    elseif msg:lower() == "debug" then
        -- 切换调试模式（新增）
        MonsterKillCounterDB.settings.debug = not MonsterKillCounterDB.settings.debug
        PrintMessage(string.format("调试模式: |cFFFFFF00%s|r",
            MonsterKillCounterDB.settings.debug and "开启" or "关闭"))
    elseif msg:lower() == "reset" then
        -- 重置账号数据
        StaticPopup_Show("MKC_RESET_CONFIRM")
    elseif msg:lower() == "help" or msg:lower() == "?" then
        -- 显示帮助
        PrintMessage("使用说明:")
        print("|cFFFFFF00/mkc|r - 显示当前统计")
        print("|cFFFFFF00/mkc announce|r - 在说频道显示击杀统计")
        print("|cFFFFFF00/mkc yell|r - 在喊话频道显示")
        print("|cFFFFFF00/mkc guild|r - 在公会频道显示")
        print("|cFFFFFF00/mkc list|r - 显示所有角色列表")
        print("|cFFFFFF00/mkc update|r - 手动更新数据")
        print("|cFFFFFF00/mkc auto|r - 切换登录时自动显示")
        print("|cFFFFFF00/mkc debug|r - 切换调试模式")
        print("|cFFFFFF00/mkc reset|r - 重置账号数据")
        print("|cFFFFFF00/mkc help|r - 显示此帮助")
        print("")
        print("|cFFFFFF00当前统计ID:|r " .. MonsterKillCounterDB.settings.targetStatisticID)
        print("|cFFFFFF00账号总击杀:|r " .. (MonsterKillCounterDB.accountData.totalKills or 0))
    elseif tonumber(msg) then
        -- 设置新的统计ID
        local newID = tonumber(msg)
        MonsterKillCounterDB.settings.targetStatisticID = newID
        PrintMessage(string.format("已设置统计ID为 |cFFFFFF00%d|r", newID))
        UpdateCharacterData()  -- 更新时显示“新增击杀”提示（如有）
    else
        PrintMessage("未知命令。输入 |cFFFFFF00/mkc help|r 查看帮助。")
    end
end

-- 创建重置确认框
StaticPopupDialogs["MKC_RESET_CONFIRM"] = {
    text = "确定要重置所有账号数据吗？此操作不可撤销！",
    button1 = "确定",
    button2 = "取消",
    OnAccept = function()
        MonsterKillCounterDB.accountData = {
            totalKills = 0,
            characters = {}
        }
        PrintMessage("账号数据已重置")
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}