local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local ZLCreateFrame = ZL.ZLCreateFrame
local CreateEditBox = ZL.CreateEditBox
local CreateButton = ZL.CreateButton
local ScrollFrame_OnMouseWheel = ZL.ScrollFrame_OnMouseWheel
local GameTooltipShow = ZL.GameTooltipShow
local GameTooltipShowAnchor = ZL.GameTooltipShowAnchor
local GetClassColorName = ZL.GetClassColorName
local ParseClassColorName = ZL.ParseClassColorName
local cGetItemInfo = C_Item and C_Item.GetItemInfo or GetItemInfo
local cGetItemIcon = C_Item and C_Item.GetItemIconByID or GetItemIcon
local cGetItemInfoInstant = C_Item and C_Item.GetItemInfoInstant or GetItemInfoInstant

--双休T：T和DPS
--双休：DPS和N
local subsidyTypeList = {
    "RL", "T", "主T", "副T", "双休T", "N", "NQ", "DPS", "DPS1", "DPS2", "DPS3",
    "DPS4", "DPS5", "DPS6", "DPS7", "DPS8", "DPS9", "DPS10", "鱼", "猪",
    "恶魔术", "战斗贼", "鸟德", "暗牧", "增强萨", "双休", "修星", "橙锤", "橙斧",
}

local function singleMoneyboxTextChanged(self)
    local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
    local subsidyName = self:GetParent().subsidyName
    local text = self:GetText()
    if text and #text > 0 then
        local subsidyMoney
        if subsidyName == "RL" then
            subsidyMoney = text:match("(团双)")
            if not subsidyMoney then
                subsidyMoney = text:match("(%d+%%)")
                if not subsidyMoney then
                    subsidyMoney = tonumber(text:match("^(%d+)$"))
                end
            end
            subsidyMoney = subsidyMoney or 0
        else
            subsidyMoney = self:GetNumber()
        end
        subsidyData[subsidyName] = subsidyMoney
    end
    self:ClearFocus()
    ZL.SubsidyFrame:Update()
end

local subsidyTypeFunc = {
    ["RL"] = {
        icon = "|T132062:13|t",
        OnLeftButtonMouseDown = function (self)
            local function tempfunc(self)
                local menuList = {}
                local tempList = {"固定", "团双", "提成"}
                if IsInRaid(1) then
                    for i = 1, MAX_RAID_MEMBERS do
                        local name, rank, _, _, _, fileName = GetRaidRosterInfo(i)
                        if name and rank == 2 then
                            tinsert(menuList, {
                                text = GetClassColorName(name, fileName),
                                checkable = 1,
                                checked = true,
                                func = function ()
                                    
                                end,
                            })
                            tinsert(menuList, {isSeparator = true})
                            break
                        end
                    end
                end
                for _, value in ipairs(tempList) do
                    tinsert(menuList, {
                        text = value,
                        func = function ()
                            if value == "团双" then
                                local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                                local subsidyName = self:GetParent().subsidyName
                                subsidyData[subsidyName] = value
                                -- self.fontstring:SetText(value)
                                ZL.SubsidyFrame:Update()
                            end
                        end,
                        hasArrow = value ~= "团双" and true or false,
                        menuTable = function ()
                            local _menuList = {}
                            local _tempList
                            if value == "固定" then
                                _tempList = {100, 200, 500, 1000, 2000, 5000, 10000}
                            else
                                _tempList = {"1%", "2%", "3%", "4%", "5%"}
                            end
                            for _, _value in ipairs(_tempList) do
                                tinsert(_menuList, {
                                    text = _value,
                                    func = function ()
                                        local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                                        local subsidyName = self:GetParent().subsidyName
                                        subsidyData[subsidyName] = _value
                                        -- self.fontstring:SetText(_value)
                                        ZL.SubsidyFrame:Update()
                                    end
                                })
                            end
                            return _menuList
                        end,
                    })
                end
                return menuList
            end
            ZL.GUI:ToggleMenu(self, tempfunc(self), 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
        end,
        toolTip = function (self)
            GameTooltipShow(self, "BOTTOMLEFT", "TOPRIGHT")
            GameTooltip:AddLine("团长补贴方式")
            GameTooltip:AddLine("固定：|cffffffff输入|r|cff4080FF不小于0的数|r")
            GameTooltip:AddLine("团双：|cffffffff输入|r|cff4080FF团双|r")
            GameTooltip:AddLine("提成：|cffffffff输入带%的数字，如|r|cff4080FF2%|r")
            GameTooltip:AddLine(" ")
            GameTooltip:AddLine("支持鼠标滚轮快速输入数字")
            GameTooltip:AddLine("手动输入需按|cff4080FFEnter|r或|cff4080FF右键|r保存！")
            GameTooltip:Show()
        end,
    },
    ["T"] = {
        icon = "|A:UI-LFG-RoleIcon-Tank:13:13|a",
    },
    ["主T"] = {
        icon = "|A:UI-LFG-RoleIcon-Tank:13:13|a",
    },
    ["副T"] = {
        icon = "|A:UI-LFG-RoleIcon-Tank:13:13|a",
    },
    ["双休T"] = {
        icon = "|A:UI-LFG-RoleIcon-Tank:13:13|a",
        OnLeftButtonMouseDown = function (self)
            local function tempfunc(self)
                local menuList = {}
                if IsInRaid(1) then
                    for i = 1, MAX_RAID_MEMBERS do
                        local name, _, _, _, _, fileName = GetRaidRosterInfo(i)
                        if name and ZL_PLAYERLIST.playerInfo and ZL_PLAYERLIST.playerInfo[name] and
                        ZL_PLAYERLIST.playerInfo[name]["T"] and ZL_PLAYERLIST.playerInfo[name]["DPS"] then
                            tinsert(menuList, {
                                text = GetClassColorName(name, fileName),
                                checkable = 1,
                                checked = true,
                                func = function ()
                                    
                                end,
                            })
                            tinsert(menuList, {isSeparator = true})
                            break
                        end
                    end
                end
                return menuList
            end
            local menuList = tempfunc(self)
            if #menuList > 0 then
                tinsert(menuList, 1, {
                    text = "A:UI-LFG-RoleIcon-Tank:13:13|a双休T：",
                    isTitle = true,
                })
            else
                tinsert(menuList, {
                    text = "没有数据",
                    isTitle = true,
                })
            end
            ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
        end,
    },
    ["N"] = {
        icon = "|A:UI-LFG-RoleIcon-Healer:13:13|a",
    },
    ["NQ"] = {
        icon = "|T135920:13|t",
    },
    ["DPS"] = {
        icon = "|A:UI-LFG-RoleIcon-DPS:13:13|a",

    },
    ["猪"] = {
        icon = "|T132184:13|t",
    },
    ["鱼"] = {
        icon = "|T237303:13|t",
        OnLeftButtonMouseDown = function (self)
            local function tempfunc(self)
                local menuList = {}
                if IsInRaid(1) then
                    for i = 1, MAX_RAID_MEMBERS do
                        local name, _, _, _, _, fileName = GetRaidRosterInfo(i)
                        if name and ZL_PLAYERLIST.playerInfo and ZL_PLAYERLIST.playerInfo[name]
                        and ZL_PLAYERLIST.playerInfo[name]["鱼"] then
                            tinsert(menuList, {
                                text = function ()
                                    local text = GetClassColorName(name, fileName) .. " - " .. ZL_PLAYERLIST.playerInfo[name].fishCount .. "次"
                                    if ZL_PLAYERLIST.subsidyFishFirst == name then
                                        text = text .. " - First"
                                    end
                                    return text
                                end,
                                checkable = 1,
                                isNotRadio = nil,
                                checked = ZL_PLAYERLIST.subsidyFishFirst == name,
                                func = function ()
                                    ZL_PLAYERLIST.subsidyFishFirst = name
                                    self:ClearFocus()
                                end,
                            })
                        end
                    end
                end
                return menuList
            end
            local menuList = tempfunc(self)
            if #menuList > 0 then
                tinsert(menuList, 1, {
                    text = "|T237303:13|t鱼：",
                    isTitle = true,
                })
            else
                tinsert(menuList, {
                    text = "没有数据",
                    isTitle = true,
                })
            end
            ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
        end,
    },
    ["恶魔术"] = {
        icon = "|T136172:13|t",
    },
    ["战斗贼"] = {
        icon = "|T132090:13|t",
    },
    ["鸟德"] = {
        icon = "|T136096:13|t",
    },
    ["暗牧"] = {
        icon = "|T136207:13|t",
    },
    ["增强萨"] = {
        icon = "|T136051:13|t",
    },
    ["双休"] = {
        icon = "|T:13|t",
        OnLeftButtonMouseDown = function (self)
            local function tempfunc(self)
                local menuList = {}
                if IsInRaid(1) then
                    for i = 1, MAX_RAID_MEMBERS do
                        local name, _, _, _, _, fileName = GetRaidRosterInfo(i)
                        if name and ZL_PLAYERLIST.playerInfo and ZL_PLAYERLIST.playerInfo[name] and
                        ZL_PLAYERLIST.playerInfo[name]["N"] and ZL_PLAYERLIST.playerInfo[name]["DPS"] then
                            tinsert(menuList, {
                                text = GetClassColorName(name, fileName),
                                checkable = 1,
                                checked = true,
                                func = function ()
                                    
                                end,
                            })
                            tinsert(menuList, {isSeparator = true})
                            break
                        end
                    end
                end
                return menuList
            end
            local menuList = tempfunc(self)
            if #menuList > 0 then
                tinsert(menuList, 1, {
                    text = "T:13|t双休：",
                    isTitle = true,
                })
            else
                tinsert(menuList, {
                    text = "没有数据",
                    isTitle = true,
                })
            end
            ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
        end,
    },
    ["修星"] = {
        icon = "|T135753:13|t",
    },
    ["橙锤"] = {
        icon = "|T253399:13|t",
    },
    ["橙斧"] = {
        icon = "|T313914:13|t",
    },
}

local talentInfo = {
    ["鲜血坦克"] = {"T"},
    ["冰霜"] = {"DPS"},
    ["邪恶"] = {"DPS"},
    ["野性坦克"] = {"T"},
    ["野性输出"] = {"DPS"},
    ["平衡"] = {"DPS", "鸟德"},
    ["恢复"] = {"N"},
    ["野兽控制"] = {"DPS"},
    ["射击"] = {"DPS"},
    ["生存"] = {"DPS"},
    ["奥术"] = {"DPS"},
    ["火焰"] = {"DPS"},
    ["神圣"] = {"N"},
    ["防护"] = {"T"},
    ["惩戒"] = {"DPS"},
    ["戒律"] = {"N"},
    ["暗影"] = {"DPS", "暗牧"},
    ["战斗"] = {"DPS", "战斗贼"},
    ["刺杀"] = {"DPS"},
    ["敏锐"] = {"DPS"},
    ["元素"] = {"DPS"},
    ["增强"] = {"DPS", "增强萨"},
    ["武器"] = {"DPS"},
    ["狂怒"] = {"DPS"},
    ["痛苦"] = {"DPS"},
    ["恶魔学识"] = {"DPS", "恶魔术"},
    ["毁灭"] = {"DPS"},
}

local function getSubsidyTypeFromTalentInfo(playerName, mainTalentName)
    if not mainTalentName then return end
    if talentInfo[mainTalentName] then
        for _, key in ipairs(talentInfo[mainTalentName]) do
            ZL_PLAYERLIST.playerInfo = ZL_PLAYERLIST.playerInfo or {}
            ZL_PLAYERLIST.playerInfo[playerName] = ZL_PLAYERLIST.playerInfo[playerName] or {}
            ZL_PLAYERLIST.playerInfo[playerName][key] = true
        end
    end
end

local function canInspect(unit)
    if not unit or UnitIsDeadOrGhost("player") or UnitIsDeadOrGhost(unit) or InCombatLockdown()
    or not CheckInteractDistance(unit, 1) or not CanInspect(unit) then
        return false
    end
    return true
end
function ZL:CreateSubsidyFrame()
    ZL.SubsidyFrame = ZLCreateFrame("ZLSubsidyFrame", ZL, nil, nil, nil, true, true, "补贴设置")
    local SubsidyFrame = ZL.SubsidyFrame
    SubsidyFrame:Hide()
    SubsidyFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
        if not ZL.glb.ZLSubsidyFrame then ZL.glb.ZLSubsidyFrame = {} end
        ZL.glb.ZLSubsidyFrame.point, _, ZL.glb.ZLSubsidyFrame.relative, ZL.glb.ZLSubsidyFrame.x, ZL.glb.ZLSubsidyFrame.y = self:GetPoint()
    end)
    SubsidyFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    SubsidyFrame:SetScript("OnShow", function (self)
        SubsidyFrame:Update()
    end)
    local resizeButton = SubsidyFrame.resizeButton
    -- 设置鼠标按下时开始调整大小
    resizeButton:SetScript("OnMouseDown", function(self, button)
        if button == "LeftButton" then
            SubsidyFrame:StartSizing("BOTTOMRIGHT")
        end
    end)
    -- 鼠标松开时停止调整大小
    resizeButton:SetScript("OnMouseUp", function(self, button)
        SubsidyFrame:StopMovingOrSizing()
        ZL.db.global.ZLAuctionFrame = ZL.db.global.ZLAuctionFrame or {}
        ZL.db.global.ZLAuctionFrame.Width,  ZL.db.global.ZLAuctionFrame.Height= SubsidyFrame:GetSize()
    end)
    SubsidyFrame:ClearAllPoints()
    if ZL.glb.ZLSubsidyFrame and ZL.glb.ZLSubsidyFrame.point then
        SubsidyFrame:SetPoint(ZL.glb.ZLSubsidyFrame.point, UIParent, ZL.glb.ZLSubsidyFrame.relative, ZL.glb.ZLSubsidyFrame.x, ZL.glb.ZLSubsidyFrame.y)
    else
        SubsidyFrame:SetPoint("CENTER")
    end

    local subsidyTypeWidth, singleMoneyWidth, meetMembersWidth, actualMembersWidth, totalMoneyWidth, delWidth = 120, 80, 80, 80, 100, 30
    local totalWidth = subsidyTypeWidth + singleMoneyWidth + meetMembersWidth + actualMembersWidth + totalMoneyWidth + delWidth + 26
    SubsidyFrame:SetResizeBounds(totalWidth, 350, totalWidth, GetScreenHeight()-110)
    SubsidyFrame:SetWidth(totalWidth)
    if ZL.db.global.ZLAuctionFrame and ZL.db.global.ZLAuctionFrame.Height then
        SubsidyFrame:SetHeight(ZL.db.global.ZLAuctionFrame.Height)
    end

    local lineHeight = 20

    SubsidyFrame.subsidyTypeAddBox = CreateEditBox(SubsidyFrame, subsidyTypeWidth, lineHeight, 12, nil, nil, nil, nil, nil, nil, nil, "SubsidyFrameSubsidyTypeAddBox")
    local subsidyTypeAddBox = SubsidyFrame.subsidyTypeAddBox
    subsidyTypeAddBox:SetPoint("TOPLEFT", SubsidyFrame.TitleBottom, "BOTTOMLEFT", 3, -5)
    subsidyTypeAddBox.Background:SetColorTexture(0,0,0,1)

    SubsidyFrame.singleMoneyAddBox = CreateEditBox(SubsidyFrame, singleMoneyWidth, lineHeight, 12, nil, nil, nil, nil, nil, nil, nil, "SubsidyFrameSingleMoneyAddBox")
    local singleMoneyAddBox = SubsidyFrame.singleMoneyAddBox
    singleMoneyAddBox:SetPoint("LEFT", subsidyTypeAddBox, "RIGHT")
    singleMoneyAddBox.Background:SetColorTexture(0,0,0,1)

    SubsidyFrame.totalMoneyAddBox = CreateEditBox(SubsidyFrame, totalMoneyWidth, lineHeight, 12, nil, nil, nil, nil, nil, nil, nil, "SubsidyFrameTotalMoneyAddBox")
    local totalMoneyAddBox = SubsidyFrame.totalMoneyAddBox
    totalMoneyAddBox:SetPoint("LEFT", singleMoneyAddBox, "RIGHT")
    totalMoneyAddBox.Background:SetColorTexture(0,0,0,1)

    --设置TAB事件
    do
        local editboxList = {"SubsidyFrameSubsidyTypeAddBox", "SubsidyFrameSingleMoneyAddBox", "SubsidyFrameTotalMoneyAddBox"}
        local function OnTabPressed(self)
            EditBox_HandleTabbing(self, editboxList)
        end
        subsidyTypeAddBox:SetScript("OnTabPressed", OnTabPressed)
        singleMoneyAddBox:SetScript("OnTabPressed", OnTabPressed)
        totalMoneyAddBox:SetScript("OnTabPressed", OnTabPressed)
    end
    SubsidyFrame.addBtn = CreateButton(nil, SubsidyFrame, "添加", "LEFT", totalMoneyAddBox, "RIGHT", 3, 0, 47)
    local addBtn = SubsidyFrame.addBtn
    addBtn:SetScript("OnClick", function (self)
        local function tempfunc()
            local menuList = {}
            local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
            for _, subsidyName in ipairs(subsidyTypeList) do
                local subsidyNameGsub = subsidyName:gsub("%d+", "")
                if subsidyName == "主T" or subsidyName == "副T" or subsidyName == "双休T" then
                    subsidyNameGsub = "T"
                end
                local icon = subsidyTypeFunc[subsidyNameGsub].icon or "|T:13|t"
                tinsert(menuList, {
                    text = icon .. subsidyName,
                    checkable = 1,
                    isNotRadio = 1,
                    checked = subsidyData[subsidyName],
                    keepShownOnClick = 1,
                    func = function ()
                        if subsidyData[subsidyName] then
                            subsidyData[subsidyName] = nil
                        else
                            subsidyData[subsidyName] = 0
                            if subsidyName == "鱼" then
                                subsidyData["猪"] = nil
                            elseif subsidyName == "猪" then
                                subsidyData["鱼"] = nil
                            elseif subsidyName == "DPS" then
                                for i = 1, 10 do
                                    subsidyData["DPS" .. i] = nil
                                end
                            elseif subsidyName:match("^DPS%d+$") then
                                subsidyData["DPS"] = nil
                            elseif subsidyName == "T" then
                                subsidyData["主T"] = nil
                                subsidyData["副T"] = nil
                                subsidyData["双休T"] = nil
                            elseif subsidyName == "主T" or subsidyName == "副T" or subsidyName == "双休T" then
                                subsidyData["T"] = nil
                            end
                        end
                        SubsidyFrame:Update()
                        ZL.GUI:OpenMenu(self, tempfunc(), "TOPLEFT", self, "TOPRIGHT", 0, 0)
                    end
                })
            end
            return menuList
        end
        ZL.GUI:ToggleMenu(self, tempfunc(), "TOPLEFT", self, "TOPRIGHT", 0, 0)
    end)

    local btnTexture = [[Interface\ACHIEVEMENTFRAME\UI-Achievement-Parchment-Horizontal]]
    SubsidyFrame.subsidyTypeBtn = CreateButton(nil, SubsidyFrame, "补贴类型", "TOPLEFT", subsidyTypeAddBox, "BOTTOMLEFT", 0, -5, subsidyTypeWidth)
    local subsidyTypeBtn = SubsidyFrame.subsidyTypeBtn
    subsidyTypeBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    subsidyTypeBtn:SetNormalTexture(btnTexture)
    subsidyTypeBtn:ClearHighlightTexture()

    SubsidyFrame.singleMoneyBtn = CreateButton(nil, SubsidyFrame, "单个补贴", "LEFT", subsidyTypeBtn, "RIGHT", 0, 0, singleMoneyWidth)
    local singleMoneyBtn = SubsidyFrame.singleMoneyBtn
    singleMoneyBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    singleMoneyBtn:SetNormalTexture(btnTexture)
    singleMoneyBtn:ClearHighlightTexture()

    SubsidyFrame.meetMembersBtn = CreateButton(nil, SubsidyFrame, "预估人数", "LEFT", singleMoneyBtn, "RIGHT", 0, 0, meetMembersWidth)
    local meetMembersBtn = SubsidyFrame.meetMembersBtn
    meetMembersBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    meetMembersBtn:SetNormalTexture(btnTexture)
    meetMembersBtn:ClearHighlightTexture()

    SubsidyFrame.actualMembersBtn = CreateButton(nil, SubsidyFrame, "实际人数", "LEFT", meetMembersBtn, "RIGHT", 0, 0, actualMembersWidth)
    local actualMembersBtn = SubsidyFrame.actualMembersBtn
    actualMembersBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    actualMembersBtn:SetNormalTexture(btnTexture)
    actualMembersBtn:ClearHighlightTexture()

    SubsidyFrame.totalMoneyBtn = CreateButton(nil, SubsidyFrame, "合计补贴", "LEFT", actualMembersBtn, "RIGHT", 0, 0, totalMoneyWidth)
    local totalMoneyBtn = SubsidyFrame.totalMoneyBtn
    totalMoneyBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    totalMoneyBtn:SetNormalTexture(btnTexture)
    totalMoneyBtn:ClearHighlightTexture()

    --创建滚动条
    SubsidyFrame.scrollFrame = CreateFrame("ScrollFrame", nil, SubsidyFrame, "UIPanelScrollFrameTemplate")
    SubsidyFrame.scrollFrame:SetFrameLevel(SubsidyFrame:GetFrameLevel() + 1) -- 设置为比父框架高1级
    SubsidyFrame.scrollFrame:SetPoint("TOPLEFT", subsidyTypeBtn, "BOTTOMLEFT", -3, 0)
    SubsidyFrame.scrollFrame:SetPoint("BOTTOMRIGHT", SubsidyFrame, "BOTTOMRIGHT", 0, 3)
    SubsidyFrame.scrollFrame:SetClipsChildren(true) --必须设置为true，scrollFrame所有的子元素才会被剪切
    SubsidyFrame.scrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel) --重设滑动条鼠标滚轮事件
    --重设ScrollBar位置，放置到scrollFrame内，防止被剪切掉
    SubsidyFrame.scrollFrame.ScrollBar:ClearAllPoints()
    SubsidyFrame.scrollFrame.ScrollBar:SetPoint("TOPLEFT", SubsidyFrame.scrollFrame, "TOPRIGHT", -20, -17)
    SubsidyFrame.scrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", SubsidyFrame.scrollFrame, "BOTTOMRIGHT", 0, 16)
    SubsidyFrame.scrollFrame.content = CreateFrame("Frame", nil, SubsidyFrame.scrollFrame)
    local content = SubsidyFrame.scrollFrame.content
    content:SetPoint("TOPLEFT", SubsidyFrame.scrollFrame, "TOPLEFT", 0, 0)
    content:SetSize(SubsidyFrame.scrollFrame:GetWidth()-20, 100)
    SubsidyFrame.scrollFrame:SetScrollChild(content)
    SubsidyFrame.scrollFrame.ScrollBar:SetFrameLevel(content:GetFrameLevel()+100)

    local function OnEnter(self)
        self:GetParent():SetNormalTexture("Interface\\FriendsFrame\\UI-FriendsFrame-HighlightBar")
    end
    local function OnLeave(self)
        self:GetParent():ClearNormalTexture()
    end
    local board_r, board_g, board_b, board_a = 0.24, 0.25, 0.3, 1
    SubsidyFrame.entries = setmetatable({}, {
        __index = function (t, v)
            local f = CreateFrame("Button", nil, content)
            f:Hide()
            f:SetSize(totalWidth-26, lineHeight)
            if v == 1 then
                f:SetPoint("TOPLEFT", content, "TOPLEFT", 3, -1)
            else
                f:SetPoint("TOPLEFT", t[v-1], "BOTTOMLEFT")
            end
            f.Background = f:CreateTexture(nil,"BACKGROUND")
            f.Background:SetPoint("TOPLEFT")
            f.Background:SetPoint("BOTTOMRIGHT")
            f.Background:SetColorTexture(0.15, 0.15, 0.15, 1)
            f:SetScript("OnEnter", function (self)
                self:SetNormalTexture("Interface\\FriendsFrame\\UI-FriendsFrame-HighlightBar")
            end)
            f:SetScript("OnLeave", function (self)
                self:ClearNormalTexture()
            end)
            f.subsidyTypebox = CreateEditBox(f, subsidyTypeWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a, "SubsidyFrameSubsidyTypeAddBoxChild" .. v)
            f.subsidyTypebox:SetPoint("LEFT", f, "LEFT", 0, 0)
            f.subsidyTypebox.Background:SetColorTexture(0,0,0,0)
            f.subsidyTypebox.fontstring = f.subsidyTypebox:CreateFontString(nil, "OVERLAY")
            f.subsidyTypebox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.subsidyTypebox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.subsidyTypebox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.subsidyTypebox.fontstring:SetWordWrap(false)
            f.subsidyTypebox.fontstring:SetJustifyH("LEFT")
            f.subsidyTypebox.fontstring:SetJustifyV("MIDDLE")
            f.subsidyTypebox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.subsidyTypebox:Disable()
            f.subsidyTypebox:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.subsidyTypebox:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)
            f.subsidyTypebox:SetScript("OnMouseDown", function (self, button)
                local function tempfunc()
                    local menuList = {}
                    local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                    local currentSubsidyName = self:GetParent().subsidyName
                    for _, subsidyName in ipairs(subsidyTypeList) do
                        if not subsidyData[subsidyName] then
                            local subsidyNameGsub = subsidyName:gsub("%d+", "")
                            if subsidyName == "主T" or subsidyName == "副T" or subsidyName == "双休T" then
                                subsidyNameGsub = "T"
                            end
                            local icon = subsidyTypeFunc[subsidyNameGsub].icon or "|T:13|t"
                            tinsert(menuList, {
                                text = icon .. subsidyName,
                                func = function ()
                                    subsidyData[subsidyName] = subsidyData[currentSubsidyName]
                                    subsidyData[currentSubsidyName] = nil
                                    if subsidyName == "鱼" then
                                        subsidyData["猪"] = nil
                                    elseif subsidyName == "猪" then
                                        subsidyData["鱼"] = nil
                                    elseif subsidyName == "DPS" then
                                        for i = 1, 10 do
                                            subsidyData["DPS" .. i] = nil
                                        end
                                    elseif subsidyName:match("^DPS%d+$") then
                                        subsidyData["DPS"] = nil
                                    elseif subsidyName == "T" then
                                        subsidyData["主T"] = nil
                                        subsidyData["副T"] = nil
                                        subsidyData["双休T"] = nil
                                    elseif subsidyName == "主T" or subsidyName == "副T" or subsidyName == "双休T" then
                                        subsidyData["T"] = nil
                                    end
                                    SubsidyFrame:Update()
                                end
                            })
                        end
                    end
                    return menuList
                end
                ZL.GUI:ToggleMenu(self, tempfunc(), "TOPLEFT", self, "BOTTOMRIGHT", 0, 0)
            end)

            f.singleMoneybox = CreateEditBox(f, singleMoneyWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a, "SubsidyFrameSingleMoneyAddBoxChild" .. v)
            f.singleMoneybox:SetPoint("LEFT", f.subsidyTypebox, "RIGHT", 0, 0)
            f.singleMoneybox.Background:SetColorTexture(0,0,0,0)
            f.singleMoneybox.fontstring = f.singleMoneybox:CreateFontString(nil, "OVERLAY")
            f.singleMoneybox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.singleMoneybox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.singleMoneybox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.singleMoneybox.fontstring:SetWordWrap(false)
            f.singleMoneybox.fontstring:SetJustifyH("RIGHT")
            f.singleMoneybox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.singleMoneybox:SetScript("OnLeave", function(self)
                OnLeave(self)
                GameTooltip:Hide()
            end)
            f.singleMoneybox:SetScript("OnEditFocusGained", function (self)
                self.fontstring:Hide()
                local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                local subsidyName = f.subsidyName
                self:SetText(subsidyData[subsidyName])
                self:HighlightText()
            end)
            f.singleMoneybox:SetScript("OnEditFocusLost", function (self)
                self.fontstring:Show()
                local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                local subsidyName = f.subsidyName
                self.fontstring:SetText(subsidyData[subsidyName])
                self:SetText("")
                self:HighlightText(0, 0)
            end)
            f.singleMoneybox:SetScript("OnMouseWheel", function(self, delta)
                if self:HasFocus() then
                    local number = self:GetNumber()
                    if delta > 0 then
                        number = number + 100
                    else
                        number = number - 100
                    end
                    if number < 0 then
                        number = 0
                    end
                    self:SetNumber(number)
                end
            end)
            f.singleMoneybox:SetScript("OnEnterPressed", function (self)
                singleMoneyboxTextChanged(self)
            end)

            f.meetMembersbox = CreateEditBox(f, meetMembersWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a, "SubsidyFramemeetMembersAddBoxChild" .. v)
            f.meetMembersbox:SetPoint("LEFT", f.singleMoneybox, "RIGHT", 0, 0)
            f.meetMembersbox.Background:SetColorTexture(0,0,0,0)
            f.meetMembersbox.fontstring = f.meetMembersbox:CreateFontString(nil, "OVERLAY")
            f.meetMembersbox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.meetMembersbox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.meetMembersbox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.meetMembersbox.fontstring:SetWordWrap(false)
            f.meetMembersbox.fontstring:SetJustifyH("RIGHT")
            f.meetMembersbox.fontstring:SetJustifyV("MIDDLE")
            f.meetMembersbox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.meetMembersbox:Disable()
            f.meetMembersbox:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.meetMembersbox:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)

            f.actualMembersbox = CreateEditBox(f, actualMembersWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a, "SubsidyFrameactualMembersAddBoxChild" .. v)
            f.actualMembersbox:SetPoint("LEFT", f.meetMembersbox, "RIGHT", 0, 0)
            f.actualMembersbox.Background:SetColorTexture(0,0,0,0)
            f.actualMembersbox.fontstring = f.actualMembersbox:CreateFontString(nil, "OVERLAY")
            f.actualMembersbox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.actualMembersbox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.actualMembersbox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.actualMembersbox.fontstring:SetWordWrap(false)
            f.actualMembersbox.fontstring:SetJustifyH("RIGHT")
            f.actualMembersbox.fontstring:SetJustifyV("MIDDLE")
            f.actualMembersbox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.actualMembersbox:Disable()
            f.actualMembersbox:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.actualMembersbox:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)

            f.totalMoneybox = CreateEditBox(f, totalMoneyWidth, lineHeight, 12, "CENTER", true, nil, board_r, board_g, board_b, board_a, "SubsidyFrameTotalMoneyAddBoxChild" .. v)
            f.totalMoneybox:SetPoint("LEFT", f.actualMembersbox, "RIGHT", 0, 0)
            f.totalMoneybox.Background:SetColorTexture(0,0,0,0)
            f.totalMoneybox.fontstring = f.totalMoneybox:CreateFontString(nil, "OVERLAY")
            f.totalMoneybox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.totalMoneybox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.totalMoneybox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.totalMoneybox.fontstring:SetWordWrap(false)
            f.totalMoneybox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.totalMoneybox:Disable()
            f.totalMoneybox:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.totalMoneybox:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)
            --设置TAB事件
            do
                local editboxList = {"SubsidyFrameSubsidyTypeAddBoxChild" .. v, "SubsidyFrameSingleMoneyAddBoxChild" .. v, "SubsidyFrameTotalMoneyAddBoxChild" .. v}
                local function OnTabPressed(self)
                    EditBox_HandleTabbing(self, editboxList)
                end
                f.subsidyTypebox:SetScript("OnTabPressed", OnTabPressed)
                f.singleMoneybox:SetScript("OnTabPressed", OnTabPressed)
                f.totalMoneybox:SetScript("OnTabPressed", OnTabPressed)
            end

            f.delBtn = CreateButton(nil, f, "-", "LEFT", f.totalMoneybox, "RIGHT", 0, 0, delWidth, lineHeight)
            f.delBtn:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.delBtn:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)
            f.delBtn:SetScript("OnClick", function (self)
                local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                subsidyData[f.subsidyName] = nil
                SubsidyFrame:Update()
            end)

            t[v] = f
            return f
        end
    })
    ZL.opt.subsidyProfile = ZL.opt.subsidyProfile or {}
    if not next(ZL.opt.subsidyProfile) then
        ZL.opt.subsidyProfile["默认"] = {
            ["RL"] = 0, ["T"] = 0, ["N"] = 0, ["DPS"] = 0,
        }
    end
    ZL.opt.subsidyProfileSelect = (ZL.opt.subsidyProfileSelect and ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]) and ZL.opt.subsidyProfileSelect or "默认"
    function SubsidyFrame:Update()
        for _, f in ipairs(SubsidyFrame.entries) do f:Hide() end
        local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
        local index = 1
        for _, subsidyName in ipairs(subsidyTypeList) do
            local subsidyMoney = subsidyData[subsidyName]
            if subsidyMoney then
                local f = SubsidyFrame.entries[index]
                f.subsidyName = subsidyName
                local subsidyNameGsub = subsidyName:gsub("%d+", "")
                if subsidyName == "主T" or subsidyName == "副T" or subsidyName == "双休T" then
                    subsidyNameGsub = "T"
                end
                local icon = subsidyTypeFunc[subsidyNameGsub].icon or "|T:13|t"
                f.subsidyTypebox.fontstring:SetText(icon .. subsidyName)
                f.singleMoneybox.fontstring:SetText(subsidyMoney)
                if subsidyTypeFunc[subsidyNameGsub].OnLeftButtonMouseDown then
                    f.singleMoneybox:SetScript("OnMouseDown", function (self, button)
                        if button == "LeftButton" then
                            subsidyTypeFunc[subsidyNameGsub].OnLeftButtonMouseDown(self)
                        elseif button == "RightButton" and self:HasFocus() then
                            C_Timer.After(0.5, function ()
                                singleMoneyboxTextChanged(self)
                            end)
                        end
                    end)
                else
                    f.singleMoneybox:SetScript("OnMouseDown", function (self, button)
                        if button == "LeftButton" then
                            local function tempfunc(self)
                                local menuList = {}
                                    if IsInRaid(1) then
                                        for i = 1, MAX_RAID_MEMBERS do
                                            local name, _, _, _, _, fileName = GetRaidRosterInfo(i)
                                            if name and ZL_PLAYERLIST.playerInfo and ZL_PLAYERLIST.playerInfo[name]
                                            and ZL_PLAYERLIST.playerInfo[name][subsidyNameGsub] then
                                                tinsert(menuList, {
                                                    text = GetClassColorName(name, fileName),
                                                    checkable = 1,
                                                    isNotRadio = 1,
                                                    keepShownOnClick = 1,
                                                    checked = true,
                                                    func = function ()
                                                        
                                                    end,
                                                })
                                            end
                                        end
                                    end
                                return menuList
                            end
                            local menuList = tempfunc(self)
                            if #menuList > 0 then
                                tinsert(menuList, 1, {
                                    text = icon .. subsidyName .. "：",
                                    isTitle = true,
                                })
                            else
                                tinsert(menuList, {
                                    text = "没有数据",
                                    isTitle = true,
                                })
                            end
                            ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
                        elseif button == "RightButton" and self:HasFocus() then
                            C_Timer.After(0.5, function ()
                                singleMoneyboxTextChanged(self)
                            end)
                        end
                    end)
                end
                if subsidyTypeFunc[subsidyNameGsub].toolTip then
                    f.singleMoneybox:SetScript("OnEnter", function (self)
                        OnEnter(self)
                        subsidyTypeFunc[subsidyNameGsub].toolTip(self)
                    end)
                else
                    f.singleMoneybox:SetScript("OnEnter", function (self)
                        OnEnter(self)
                        GameTooltipShow(self, "BOTTOMLEFT", "TOPRIGHT")
                        GameTooltip:AddLine("输入|cff4080FF不小于0的数|r")
                        GameTooltip:AddLine("支持鼠标滚轮快速输入数字")
                        GameTooltip:AddLine("需按|cff4080FFEnter|r或|cff4080FF右键|r保存！")
                        GameTooltip:Show()
                    end)
                end
                f:Show()
                index = index + 1
            end
        end
    end

    SubsidyFrame:RegisterEvent("CHAT_MSG_SYSTEM")
    SubsidyFrame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
    SubsidyFrame:RegisterEvent("INSPECT_READY")
    SubsidyFrame:SetScript("OnEvent", function (self, event, ...)
        local arg = ZL.emptytable(...)
        if event == "COMBAT_LOG_EVENT_UNFILTERED" then -- and IsMasterLooter()
            if IsInRaid(1) and IsInInstance() and (select(2, IsInInstance()) == "raid") then --and IsMasterLooter() 
                local _, subevent, _, sourceGUID, _, _, _, _, _, _, _, spellId = CombatLogGetCurrentEventInfo()
                if subevent == "SPELL_CAST_SUCCESS" then
                    if spellId == 57426 or spellId == 57301 then
                        local _, englishClass, _, _, _, playerName = GetPlayerInfoByGUID(sourceGUID)
                        local colorPlayerName = GetClassColorName(playerName, englishClass)
                        ZL_PLAYERLIST.playerInfo = ZL_PLAYERLIST.playerInfo or {}
                        ZL_PLAYERLIST.playerInfo[playerName] = ZL_PLAYERLIST.playerInfo[playerName] or {}
                        ZL_PLAYERLIST.playerInfo[playerName].classFile = englishClass
                        ZL_PLAYERLIST.playerInfo[playerName].colorName = colorPlayerName
                        ZL_PLAYERLIST.subsidyFoodFirst = ZL_PLAYERLIST.subsidyFoodFirst or sourceGUID
                        local msgStr
                        local subsidyData = ZL.opt.subsidyProfile[ZL.opt.subsidyProfileSelect]
                        if spellId == 57426 then
                            ZL_PLAYERLIST.playerInfo[playerName]["鱼"] = true
                            ZL_PLAYERLIST.playerInfo[playerName].fishCount = (ZL_PLAYERLIST.playerInfo[playerName].fishCount or 0) + 1
                            if not ZL_PLAYERLIST.subsidyFishFirst then
                                ZL_PLAYERLIST.subsidyFishFirst = playerName
                                -- if subsidyData["鱼"] and subsidyData["鱼"] > 0 then
                                --     msgStr = format("%s释放了%s，已记录食物补贴：%dg，注意及时补放。", playerName, GetSpellLink(spellId), subsidyData["鱼"])
                                -- else
                                --     msgStr = format(
                                --         "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                --         playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].fishCount
                                --     )
                                -- end
                                msgStr = format(
                                    "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                    playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].fishCount
                                )
                            else
                                msgStr = format(
                                    "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                    playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].fishCount
                                )
                            end
                        elseif spellId == 57301 then
                            ZL_PLAYERLIST.playerInfo[playerName]["猪"] = true
                            ZL_PLAYERLIST.playerInfo[playerName].pigCount = (ZL_PLAYERLIST.playerInfo[playerName].pigCount or 0) + 1
                            if not ZL_PLAYERLIST.subsidyPigFirst then
                                ZL_PLAYERLIST.subsidyPigFirst = playerName
                                -- if subsidyData["猪"] and subsidyData["猪"] > 0 then
                                --     msgStr = format("%s释放了%s，已记录食物补贴：%dg，注意及时补放。", playerName, GetSpellLink(spellId), subsidyData["猪"])
                                -- else
                                --     msgStr = format(
                                --         "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                --         playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].fishCount
                                --     )
                                -- end
                                msgStr = format(
                                    "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                    playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].fishCount
                                )
                            else
                                msgStr = format(
                                    "%s释放了%s，记录次数%d，请大家文明就餐，不要遮挡。",
                                    playerName, GetSpellLink(spellId), ZL_PLAYERLIST.playerInfo[playerName].pigCount
                                )
                            end
                        end
                        if IsMasterLooter() then
                            SendChatMessage(msgStr, "RAID")
                        end
                        ZL.Print(msgStr)
                    end
                end
                subevent = nil
                sourceGUID = nil
                spellId = nil
            end
        elseif event == "INSPECT_READY" then
            local _, englishClass, _, _, _, playerName = GetPlayerInfoByGUID(arg[1])
            -- if not UnitInRaid(playerName) then return end
            local colorPlayerName = GetClassColorName(playerName, englishClass)
            ZL_PLAYERLIST.playerInfo = ZL_PLAYERLIST.playerInfo or {}
            ZL_PLAYERLIST.playerInfo[playerName] = ZL_PLAYERLIST.playerInfo[playerName] or {}
            ZL_PLAYERLIST.playerInfo[playerName].classFile = englishClass
            ZL_PLAYERLIST.playerInfo[playerName].colorName = colorPlayerName
            -- 获取装备
            local itemId = GetInventoryItemID(playerName, 16)
            if itemId == 46017 then  -- 瓦兰奈尔，远古王者之锤
                ZL_PLAYERLIST.playerInfo[playerName]["橙锤"] = true
            elseif itemId == 49623 then
                ZL_PLAYERLIST.playerInfo[playerName]["橙斧"] = true
            end
            -- 获取天赋
            local activeTalentIndex = GetActiveTalentGroup(true) --当前激活的天赋
            local mainTalentName
            local mainTalenPointsSpent = 0
            local mainTalenIcon
            for i = 1, GetNumTalentTabs(true) do --天赋种类，一般为3个，如戒律、神圣、暗影
                local _, talentName, _, talentIcon, pointsSpent = GetTalentTabInfo(i, true, nil, activeTalentIndex)
                if mainTalenPointsSpent >= pointsSpent then
                    mainTalentName = mainTalentName or talentName
                    mainTalenIcon = mainTalenIcon or talentIcon
                else
                    mainTalenPointsSpent = pointsSpent
                    mainTalentName = talentName
                    mainTalenIcon = talentIcon
                end
                if mainTalentName == "鲜血" or mainTalentName == "野性战斗" then
                    for j = 1, GetNumTalents(i, true) do --当前天赋种类里面有多少个天赋技能
                        --名称, iconID, 行， 列, 点了几点技能， 最大可以点的技能
                        local _name, _, _, _, rank = GetTalentInfo(i, j, true, nil, activeTalentIndex)
                        if _name == "符文刃舞" then --鲜血DK
                            if rank == 0 then
                                mainTalentName = "鲜血坦克"
                            else
                                mainTalentName = "鲜血输出"
                            end
                            break
                        elseif _name == "厚皮" then --德鲁伊
                            if rank > 0 then
                                mainTalentName = "野性坦克"
                            else
                                mainTalentName = "野性输出"
                            end
                        end
                    end
                end
            end
            if mainTalentName then
                -- print(colorPlayerName .. "主天赋是：".. "|T" .. mainTalenIcon .. ":14|t" .. mainTalentName)
                ZL_PLAYERLIST.playerInfo[playerName].talentName = ZL_PLAYERLIST.playerInfo[playerName].talentName or {}
                ZL_PLAYERLIST.playerInfo[playerName].talentName[mainTalentName] = true
                getSubsidyTypeFromTalentInfo(playerName, mainTalentName)
                if englishClass == "PALADIN" and mainTalentName == "神圣" then
                    ZL_PLAYERLIST.playerInfo[playerName]["NQ"] = true
                end
            end
        end
        arg:Release()
    end)
end