local addonName, ZLAUTO = ...

local ZL = ZLAUTO.mainFrame
local ZLCreateFrame = ZL.ZLCreateFrame
local CreateButton = ZL.CreateButton
local CreateDynamicTable = ZL.CreateDynamicTable
local ScrollFrame_OnMouseWheel = ZL.ScrollFrame_OnMouseWheel
local MyAddon = ZL.MyAddon
local GameTooltipShow = ZL.GameTooltipShow

function ZL.CreateInstancesInfoFrame()
    local function selectInstanceDropdownMenu()
        local menuList = {}
        for _, projectName in ipairs(ZL.WOW_PROJECT) do
            local projectData = ZL.INSTANCEINFO[projectName]
            if projectData then
                tinsert(menuList, {
                    text = projectName,
                    hasArrow = 1,
                    notClickable = 1,
                    menuTable = function ()
                        local tempList1 = {}
                        for _, v1 in ipairs(projectData) do
                            local journalInstanceID = v1.journalInstanceID
                            local success = pcall(EJ_SelectInstance, journalInstanceID)
                            if success then
                                local instanceName, _, _, _, _, _, _, _, _, instanceID = EJ_GetInstanceInfo(journalInstanceID)
                                tinsert(tempList1, {
                                    text = instanceName,
                                    hasArrow = 1,
                                    notClickable = 1,
                                    menuTable = function ()
                                        local tempList2 = {}
                                        for _, difficultyId in ipairs(v1.difficultyId) do
                                            local difficultyName = GetDifficultyInfo(difficultyId)
                                            tinsert(tempList2, {
                                                text = difficultyName,
                                                func = function ()
                                                    ZL.opt.InstanceSelectJournalInstanceID = journalInstanceID
                                                    ZL.opt.InstanceSelectInstanceID = instanceID
                                                    ZL.opt.InstanceSelectInstanceName = format("%s[%s]", instanceName, difficultyName)
                                                    ZL.opt.InstanceSelectDifficultyId = difficultyId
                                                    ZL.InstancesInfoFrame.selectInstanceDropdown.fontString:SetText(format("%s[%s]", instanceName, difficultyName))
                                                    -- print(instanceName, journalInstanceID, instanceID, difficultyId)
                                                    ZL.InstancesInfoFrame:Update()
                                                end
                                            })
                                        end
                                        return tempList2
                                    end
                                })
                            end
                        end
                        return tempList1
                    end
                })
            end
        end
        return menuList
    end
    local function getInstanceBossInfo()
        local bossNameList = {}
        local journalInstanceID = ZL.opt.InstanceSelectJournalInstanceID
        EJ_SelectInstance(journalInstanceID)
        local bossName = EJ_GetEncounterInfoByIndex(1, journalInstanceID)
        local i = 1
        while bossName do
            bossName = EJ_GetEncounterInfoByIndex(i, journalInstanceID)
            if bossName then
                tinsert(bossNameList, bossName)
            end
            i = i + 1
        end
        return bossNameList
    end
    local lineHeight = 20
    local groupWidth, playerNameWidth, bossNameWidth, updateTimeWidth = 40, 150, 60, 120
    local minWidth, minHeight = 600, 400
    local btnTexture = [[Interface\ACHIEVEMENTFRAME\UI-Achievement-Parchment-Horizontal]]
    ZL.InstancesInfoFrame = ZLCreateFrame(nil, ZL, minWidth, minHeight, nil, true, true, "团队成员副本击杀信息")
    local InstancesInfoFrame = ZL.InstancesInfoFrame
    InstancesInfoFrame:Hide()
    InstancesInfoFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
        if not ZL.glb.ZLInstancesInfoFrame then ZL.glb.ZLInstancesInfoFrame = {} end
        ZL.glb.ZLInstancesInfoFrame.point, _, ZL.glb.ZLInstancesInfoFrame.relative, ZL.glb.ZLInstancesInfoFrame.x, ZL.glb.ZLInstancesInfoFrame.y = self:GetPoint()
    end)
    InstancesInfoFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    InstancesInfoFrame:SetScript("OnShow", function (self)
        InstancesInfoFrame:Update()
    end)
    local resizeButton = InstancesInfoFrame.resizeButton
    -- 设置鼠标按下时开始调整大小
    resizeButton:SetScript("OnMouseDown", function(self, button)
        if button == "LeftButton" then
            InstancesInfoFrame:StartSizing("BOTTOMRIGHT")
        end
    end)
    -- 鼠标松开时停止调整大小
    resizeButton:SetScript("OnMouseUp", function(self, button)
        InstancesInfoFrame:StopMovingOrSizing()
        ZL.glb.ZLInstancesInfoFrame = ZL.glb.ZLInstancesInfoFrame or {}
        ZL.glb.ZLInstancesInfoFrame.Width, ZL.glb.ZLInstancesInfoFrame.Height = InstancesInfoFrame:GetSize()
    end)
    InstancesInfoFrame:ClearAllPoints()
    if ZL.glb.ZLInstancesInfoFrame and ZL.glb.ZLInstancesInfoFrame.point then
        InstancesInfoFrame:SetPoint(ZL.glb.ZLInstancesInfoFrame.point, UIParent, ZL.glb.ZLInstancesInfoFrame.relative, ZL.glb.ZLInstancesInfoFrame.x, ZL.glb.ZLInstancesInfoFrame.y)
    else
        InstancesInfoFrame:SetPoint("CENTER")
    end

    local selectInstanceFontString = InstancesInfoFrame:CreateFontString(nil, "OVERLAY")
    selectInstanceFontString:SetPoint("TOPLEFT", InstancesInfoFrame.TitleBottom, "BOTTOMLEFT", 5, -8)
    selectInstanceFontString:SetHeight(24)
    selectInstanceFontString:SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    selectInstanceFontString:SetWordWrap(false)
    selectInstanceFontString:SetJustifyH("LEFT")
    selectInstanceFontString:SetTextColor(1, 0.82, 0, 1)
    selectInstanceFontString:SetText("副本：")
    local selectInstanceDropdown = CreateFrame("Button", nil, InstancesInfoFrame)
    InstancesInfoFrame.selectInstanceDropdown = selectInstanceDropdown
    selectInstanceDropdown:SetPoint("LEFT", selectInstanceFontString, "RIGHT", 5, 0)
    selectInstanceDropdown:SetSize(250, 24)
    ZL.GUI:GetClass('Dropdown'):Bind(selectInstanceDropdown)
    do
        local fontString = selectInstanceDropdown:GetFontString()
        if fontString then
            fontString:Hide()
        end
    end
    selectInstanceDropdown.fontString = selectInstanceDropdown:CreateFontString(nil, "OVERLAY")
    selectInstanceDropdown.fontString:SetPoint("LEFT", 8, 0)
    selectInstanceDropdown.fontString:SetWidth(selectInstanceDropdown:GetWidth()-selectInstanceDropdown.MenuButton:GetWidth()-7)
    selectInstanceDropdown.fontString:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    selectInstanceDropdown.fontString:SetWordWrap(false)
    selectInstanceDropdown.fontString:SetJustifyH("LEFT")
    selectInstanceDropdown.fontString:SetTextColor(1, 1, 1, 1)
    selectInstanceDropdown.fontString:SetText(ZL.opt.InstanceSelectInstanceName)
    selectInstanceDropdown:SetMenuTable(selectInstanceDropdownMenu())

    local refreshFrameBtn = CreateButton(nil, InstancesInfoFrame, "刷新界面", "LEFT", selectInstanceDropdown, "RIGHT", 10, 0, 110, 20, 14, true, 0)
    refreshFrameBtn:SetScript("OnClick", function ()
        InstancesInfoFrame:Update()
    end)
    InstancesInfoFrame.SpellHighlightTexture = refreshFrameBtn:CreateTexture("SpellHighlightTexture1", "OVERLAY", nil, 1)
    local SpellHighlightTexture = InstancesInfoFrame.SpellHighlightTexture
    SpellHighlightTexture:SetAtlas("bags-newitem")
    SpellHighlightTexture:SetSize(130, 30)
    SpellHighlightTexture:SetPoint("CENTER")
    SpellHighlightTexture:SetBlendMode("ADD")  -- 通常 ADD 模式需要设置 BlendMode
    SpellHighlightTexture:Hide()

    -- 创建 SpellHighlightAnim 动画组（循环播放）
    InstancesInfoFrame.SpellHighlightAnim = SpellHighlightTexture:CreateAnimationGroup()
    local SpellHighlightAnim = InstancesInfoFrame.SpellHighlightAnim
    SpellHighlightAnim:SetLooping("REPEAT")

    -- 第一个 Alpha 动画（淡入）
    local alpha1 = SpellHighlightAnim:CreateAnimation("Alpha")
    alpha1:SetChildKey("SpellHighlightTexture")
    alpha1:SetSmoothing("OUT")
    alpha1:SetDuration(0.75)
    alpha1:SetOrder(1)
    alpha1:SetFromAlpha(0)
    alpha1:SetToAlpha(1)

    -- 第二个 Alpha 动画（淡出）
    local alpha2 = SpellHighlightAnim:CreateAnimation("Alpha")
    alpha2:SetChildKey("SpellHighlightTexture")
    alpha2:SetSmoothing("IN")
    alpha2:SetDuration(0.75)
    alpha2:SetOrder(2)
    alpha2:SetFromAlpha(1)
    alpha2:SetToAlpha(0)
    function InstancesInfoFrame.UpdateSpellHighlightAnim()
        if InstancesInfoFrame:IsShown() then
            if InstancesInfoFrame.hasNewInfo then
                if not SpellHighlightTexture:IsShown() then
                    SpellHighlightTexture:Show()
                    SpellHighlightAnim:Play()
                end
            else
                SpellHighlightTexture:Hide()
                SpellHighlightAnim:Stop()
            end
        end
    end
    local refreshInstancesInfoBtn = CreateButton(nil, InstancesInfoFrame, "获取副本CD信息", "LEFT", refreshFrameBtn, "RIGHT", 5, 0, 160, 20, 14, true, 0)
    refreshInstancesInfoBtn:SetScript("OnClick", function ()
        local chatType
        if IsInRaid(1) then
            chatType = "RAID"
        elseif IsInGroup(1) then
            chatType = "PARTY"
        end
        if chatType then
            if not (UnitIsGroupLeader("player", 1) or UnitName("player") == "潇湘笛韵") then
                ZL.Print("团长权限，团长查询后全团共享。", true)
                return
            end
            ZL_PLAYERLIST.instancesInfo = {}
            local data = {type="request"}
            MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, chatType, nil, "BULK")
            refreshInstancesInfoBtn:Disable()
            local remainCount = 10
            refreshInstancesInfoBtn:SetText(remainCount .. "秒后可用...")
            C_Timer.NewTicker(1, function (self)
                remainCount = remainCount - 1
                refreshInstancesInfoBtn:SetText(remainCount .. "秒后可用...")
                if remainCount == 0 then
                    refreshInstancesInfoBtn:SetText("获取团队副本信息")
                    refreshInstancesInfoBtn:Enable()
                elseif remainCount == 7 then
                    InstancesInfoFrame:Update()
                    ZL.Print("已刷新界面，获取数据有延迟，如还未更新，请手动刷新界面", true)
                end
            end, 10)
        else
            ZL_PLAYERLIST.instancesInfo = {}
            local fullName = ZL.GetFullName(UnitName("player"))
            local fullColorName = ZL.GetClassColorName(fullName)
            ZL_PLAYERLIST.instancesInfo[fullColorName] = ZL.GetPlayerSavedInstanceInfo()
            InstancesInfoFrame:Update()
        end
    end)
    --创建滚动条
    InstancesInfoFrame.ScrollFrame = CreateFrame("ScrollFrame", nil, InstancesInfoFrame, "UIPanelScrollFrameTemplate")
    local InstancesInfoFrame_ScrollFrame = InstancesInfoFrame.ScrollFrame
    InstancesInfoFrame_ScrollFrame:SetFrameLevel(InstancesInfoFrame:GetFrameLevel() + 1)
    InstancesInfoFrame_ScrollFrame:SetPoint("TOPLEFT", selectInstanceFontString, "BOTTOMLEFT", 0, -10-lineHeight)
    InstancesInfoFrame_ScrollFrame:SetPoint("BOTTOMRIGHT", InstancesInfoFrame, "BOTTOMRIGHT", -2, 3)
    InstancesInfoFrame_ScrollFrame:SetClipsChildren(true)
    InstancesInfoFrame_ScrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel)
    InstancesInfoFrame_ScrollFrame.ScrollBar:ClearAllPoints()
    InstancesInfoFrame_ScrollFrame.ScrollBar:SetPoint("TOPLEFT", InstancesInfoFrame_ScrollFrame, "TOPRIGHT", -20, -16)
    InstancesInfoFrame_ScrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", InstancesInfoFrame_ScrollFrame, "BOTTOMRIGHT", 0, 16)
    InstancesInfoFrame_ScrollFrame.content = CreateFrame("Frame", nil, InstancesInfoFrame_ScrollFrame)
    local instanceInfoContent = InstancesInfoFrame_ScrollFrame.content
    instanceInfoContent:SetPoint("TOPLEFT", InstancesInfoFrame_ScrollFrame, "TOPLEFT", 0, 0)
    instanceInfoContent:SetSize(180, 100)
    InstancesInfoFrame_ScrollFrame:SetScrollChild(instanceInfoContent)

    InstancesInfoFrame.entries = CreateDynamicTable()
    function InstancesInfoFrame:Update()
        InstancesInfoFrame.hasNewInfo = nil
        InstancesInfoFrame.UpdateSpellHighlightAnim()
        for i in ipairs(InstancesInfoFrame.entries) do
            for j in ipairs(InstancesInfoFrame.entries[i]) do
                InstancesInfoFrame.entries[i][j]:Hide()
            end
        end
        local totalWidth = 0
        if ZL_PLAYERLIST.instancesInfo then
            local bossNameList = getInstanceBossInfo()
            local bossCount = #bossNameList
            if bossCount > 0 then
                local instanceInfoData = {}
                local tempList = {"队", "玩家名字"}
                for i in ipairs(bossNameList) do
                    tinsert(tempList, "|cffffffff" .. i .. "号|r")
                end
                tinsert(tempList, "更新时间")
                tinsert(instanceInfoData, tempList)

                local instanceID = ZL.opt.InstanceSelectInstanceID
                local difficultyId = ZL.opt.InstanceSelectDifficultyId
                if (IsInRaid(1) or IsInGroup(1)) then
                    for i = 1, MAX_RAID_MEMBERS do
                        local pruneName, _, subgroup, _, _, classFilename = GetRaidRosterInfo(i)
                        if pruneName then
                            local playerData = {}
                            local fullName = ZL.GetFullName(pruneName)
                            local fullColorName = fullName
                            if classFilename then
                                local color = select(4, GetClassColor(classFilename))
                                fullColorName = "|c" .. color .. fullColorName .. "|r"
                            end
                            playerData = {"|cffffffff" .. subgroup .. "|r", fullColorName}
                            local bossKill
                            --0：有拾取, 1:没有拾取打X, 2:版本过低 3：未安装插件 4：获取中...
                            if not ZL_PLAYERLIST.GroupMembersVersion[fullName] then
                                bossKill = 3
                            else
                                local ver = ZL_PLAYERLIST.GroupMembersVersion[fullName]
                                local senderVerA, senderVerB, senderVerC = ver:match("^V(%d+)%.(%d+)%.(%d+)")
                                senderVerA = tonumber(senderVerA) or 0
                                senderVerB = tonumber(senderVerB) or 0
                                senderVerC = tonumber(senderVerC) or 0
                                local verA, verB, verC = 2, 4, 9
                                local lowVer = true
                                if senderVerA > verA then
                                    lowVer = false
                                elseif senderVerA == verA then
                                    if senderVerB > verB then
                                        lowVer = false
                                    elseif senderVerB == verB then
                                        if senderVerC > verC then
                                            lowVer = false
                                        end
                                    end
                                end
                                if lowVer then
                                    bossKill = 2
                                else
                                    if not ZL_PLAYERLIST.instancesInfo[fullColorName] then
                                        bossKill = 4
                                    else
                                        if not (ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID] and
                                        ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID][difficultyId]) then
                                            bossKill = 0
                                        end
                                    end
                                end
                            end
                            for j = 1, bossCount do
                                local bossKill2 = bossKill
                                if not bossKill then
                                    bossKill2 = ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID][difficultyId][j]
                                end
                                local txt = ""
                                if bossKill2 == 1 then
                                    txt = "|T136813:18:18|t"
                                end
                                tinsert(playerData, txt)
                            end
                            local updateTime
                            if ZL_PLAYERLIST.instancesInfo[fullColorName] then
                                updateTime = ZL_PLAYERLIST.instancesInfo[fullColorName].updateTime
                                updateTime = "|cffffffff" .. ZL.ConvertSecondsToUpdateUnits(updateTime) .. "|r"
                            else
                                if bossKill == 2 then
                                    updateTime = "|T131070:20:20|t 更新插件"
                                elseif bossKill == 3 then
                                    updateTime = "|T131070:20:20|t |cffff0000未安装|r"
                                elseif bossKill == 4 then
                                    updateTime = "|cffffde00获取中|r"
                                end
                            end
                            tinsert(playerData, updateTime)
                            tinsert(instanceInfoData, playerData)
                        end
                    end
                else
                    local playerData = {}
                    local fullName = ZL.GetFullName(UnitName("player"))
                    local fullColorName = ZL.GetClassColorName(fullName)
                    playerData = {"|cffffffff1|r", fullColorName}
                    for j = 1, bossCount do
                        local bossKill2
                        if (ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID] and ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID][difficultyId])
                        and ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID][difficultyId][j] then
                            bossKill2 = ZL_PLAYERLIST.instancesInfo[fullColorName][instanceID][difficultyId][j]
                        else
                            bossKill2 = 0
                        end
                        local txt = ""
                        if bossKill2 == 1 then
                            txt = "|T136813:18:18|t"
                        end
                        tinsert(playerData, txt)
                    end
                    local updateTime
                    if ZL_PLAYERLIST.instancesInfo[fullColorName] then
                        updateTime = ZL_PLAYERLIST.instancesInfo[fullColorName].updateTime
                        updateTime = "|cffffffff" .. ZL.ConvertSecondsToUpdateUnits(updateTime) .. "|r"
                    else
                        updateTime = "|cffffde00获取中|r"
                    end
                    tinsert(playerData, updateTime)
                    tinsert(instanceInfoData, playerData)
                end
                for i, data in ipairs(instanceInfoData) do
                    local childTotalWidth = 0
                    for j, value in ipairs(data) do
                        local w = bossNameWidth
                        if j == 1 then
                            w = groupWidth
                        elseif j == 2 then
                            w = playerNameWidth
                        elseif j == #data then
                            w = updateTimeWidth
                        end
                        if not InstancesInfoFrame.entries[i][j] then
                            local f
                            if i == 1 then
                                f = CreateButton(nil, InstancesInfoFrame, " ", "TOPLEFT", selectInstanceFontString, "BOTTOMLEFT", childTotalWidth, -5, w, lineHeight+5)
                                f:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
                                f:SetNormalTexture(btnTexture)
                                f:ClearHighlightTexture()
                                f:SetScript("OnLeave", function ()
                                    GameTooltip:Hide()
                                end)
                            else
                                f = CreateButton(nil, instanceInfoContent, "", "TOPLEFT", instanceInfoContent, "TOPLEFT", childTotalWidth, -(i-2)*lineHeight, w, lineHeight, 13)
                                f:RegisterForClicks("LeftButtonUp", "RightButtonUp")
                            end
                            f:Hide()
                            InstancesInfoFrame.entries[i][j] = f
                        end
                        local f = InstancesInfoFrame.entries[i][j]
                        f:SetWidth(w)
                        childTotalWidth = childTotalWidth + f:GetWidth()
                        if i > 1 and j == 2 then
                            -- f.pruneName = ZL.pruneCrossRealm(value)
                            value = ZL.GetNoRealmName(value, true)
                        end
                        f:SetText(value)
                        if i == 1 and j >2 and j<#data then
                            f:SetScript("OnEnter", function (self)
                                GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
                                GameTooltip:AddLine(bossNameList[j-2])
                                GameTooltip:Show()
                            end)
                        end
                        if i > 1 then
                            f:SetScript("OnClick", function (self)
                                local pruneName = ZL.pruneCrossRealm(data[2])
                                local menuList = {
                                    {text=ZL.GetNoRealmName(data[2], true), isTitle=1},
                                    {
                                        text = "移除",
                                        disabled = pruneName == GetUnitName("player", true) or (not UnitIsGroupLeader("player") and not UnitIsGroupAssistant("player")),
                                        func = function()
                                            UninviteUnit(ZL.pruneCrossRealm(data[2]))
                                            C_Timer.After(0.5, function ()
                                                InstancesInfoFrame:Update()
                                            end)
                                        end,
                                    }
                                }
                                ZL.GUI:ToggleMenu(self, menuList, "cursor")
                            end)
                        end
                        f:Show()
                    end
                    totalWidth = childTotalWidth + 30
                end
             end
        end
        totalWidth = max(totalWidth, minWidth)
        local totalHeight = minHeight
        if ZL.glb.ZLInstancesInfoFrame and ZL.glb.ZLInstancesInfoFrame.Height then
            totalHeight = min(ZL.db.global.ZLInstancesInfoFrame.Height, GetScreenHeight()-110)
        end
        InstancesInfoFrame:SetResizeBounds(totalWidth, minHeight, totalWidth, GetScreenHeight()-110)
        InstancesInfoFrame:SetSize(totalWidth, totalHeight)
    end
end