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
local isNotLoot

local QUICKMASTERITEMS = {
    50274, 45038, 22726, 77952, 50231, 50226, 52019
}
local function quickMasterItemsMenu(self)
    local menuList = {}
    for _, itemId in ipairs(QUICKMASTERITEMS) do
        local item = Item:CreateFromItemID(itemId)
        if item:GetItemID() then
            item:ContinueOnItemLoad(function()
                local _, itemLink, _, _, _, _, _, _, _, itemTexture = cGetItemInfo(itemId)
                tinsert(menuList, {
                    text = "|T" .. itemTexture .. ":14|t" .. itemLink,
                    func = function ()
                        self:SetText(itemLink)
                        self:ClearFocus()
                    end,
                    tooltipMore = function(tip, data, button)
                        tip:SetHyperlink(itemLink)
                        tip:Show()
                    end,
                })
            end)
        end
    end
    return menuList
end
--缓存一次物品信息
quickMasterItemsMenu()
do
    local function lootMsg(self, event, arg1, arg2, _, _, arg5)
        if event == "TRADE_ACCEPT_UPDATE" then
            if arg1 == 1 or arg2 == 1 then
                isNotLoot = true
            else
                isNotLoot = nil
            end
        elseif event == "TRADE_CLOSED" then
            isNotLoot = nil
        elseif event == "MERCHANT_UPDATE" or event == "QUEST_TURNED_IN" or event == "QUEST_FINISHED" then
            isNotLoot = true
            C_Timer.After(0.5, function()
                isNotLoot = nil
            end)
        elseif event == "ENCOUNTER_END" then
            -----副本数据收集开始
            local name, _, _, _, _, _, _, instanceID = GetInstanceInfo()
            ZL.opt.encounterData = ZL.opt.encounterData or {}
            ZL.opt.encounterData[name..":"..instanceID] = ZL.opt.encounterData[name..":"..instanceID] or {}
            ZL.opt.encounterData[name..":"..instanceID][arg1] = arg2
            -----副本数据收集结束
            if arg5 == 1 then
                ZL_CURRENT.bossName = ZL.encounterData[arg1] or "其他"
                local count = 0
                local function tempfunc()
                    if not ZL_CURRENT.bossName then return end
                    if not IsInRaid(1) or count >=3 then
                        ZL_CURRENT.bossName = nil
                        return
                    end
                    if ZL_PLAYERLIST.lootList and ZL_PLAYERLIST.lootList[ZL_CURRENT.bossName] and
                    next(ZL_PLAYERLIST.lootList[ZL_CURRENT.bossName]) then
                        C_Timer.After(60, function ()  --ROLL拾取方式最大ROLL时长为60秒
                            ZL_CURRENT.bossName = nil
                        end)
                    else
                        if ZL.PlayerIsML() and not UnitIsDeadOrGhost("player") then
                            ZL.Print("|cffff0000[" .. ZL_CURRENT.bossName .. "]|r：请及时拾取BOSS掉落物品！")
                            ZL.SpeakText("请及时拾取BOSS掉落物品")
                        end
                        count = count + 1
                        C_Timer.After(30, function ()
                            tempfunc()
                        end)
                    end
                end
                C_Timer.After(10, function ()
                    tempfunc()
                end)
            end
        elseif event == "CHAT_MSG_LOOT" then
            if isNotLoot then return end
            local lootplayer, itemlink, count
            itemlink, count = strmatch(arg1, string.gsub(string.gsub(LOOT_ITEM_SELF_MULTIPLE, "%%s", "(.+)"), "%%d", "(%%d+)"));
            if (not itemlink) then
                itemlink, count = strmatch(arg1, string.gsub(string.gsub(LOOT_ITEM_PUSHED_SELF_MULTIPLE, "%%s", "(.+)"), "%%d", "(%%d+)"));
                if (not itemlink) then
                    itemlink = arg1:match(LOOT_ITEM_SELF:gsub("%%s", "(.+)"));
                    if (not itemlink) then
                        itemlink = arg1:match(LOOT_ITEM_PUSHED_SELF:gsub("%%s", "(.+)"));
                        if (not itemlink) then
                            lootplayer, itemlink, count = strmatch(arg1, string.gsub(string.gsub(LOOT_ITEM_MULTIPLE, "%%s", "(.+)"), "%%d", "(%%d+)"));
                            if (not itemlink) then
                                lootplayer, itemlink, count = strmatch(arg1, string.gsub(string.gsub(LOOT_ITEM_PUSHED_MULTIPLE, "%%s", "(.+)"), "%%d", "(%%d+)"));
                                if (not itemlink) then
                                    lootplayer, itemlink = arg1:match("^" .. LOOT_ITEM:gsub("%%s", "(.+)"));
                                    if (not itemlink) then
                                        lootplayer, itemlink = arg1:match("^" .. LOOT_ITEM_PUSHED:gsub("%%s", "(.+)"));
                                    end
                                end
                            end
                        end
                    end
                end
            end
            if not itemlink then return end
            lootplayer = lootplayer or UnitName("player")
            count = count or 1
            count = tonumber(count)
            local itemID = GetItemInfoInstant(itemlink)
            --记录自动分配装备的数量
            if ZL.PlayerIsML() and IsInRaid(1) and ZL_CURRENT.buyerItemList and #ZL_CURRENT.buyerItemList > 0 then
                for _, data in ipairs(ZL_CURRENT.buyerItemList) do
                    if data.itemId == itemID and lootplayer == ParseClassColorName(data.buyerName) then
                        data.hasLootCounts = data.hasLootCounts + count
                        local msgStr, msgStr2
                        if data.hasLootCounts < data.itemCounts then
                            msgStr = format("%s已分配给>>>%s<<<，进度：%d/%d", itemlink, GetClassColorName(lootplayer), data.hasLootCounts, data.itemCounts)
                            msgStr2 = format("%s已分配给>>>%s<<<，进度：%d/%d", itemlink, lootplayer, data.hasLootCounts, data.itemCounts)
                        elseif data.hasLootCounts == data.itemCounts then
                            msgStr = format("%s已分配给>>>%s<<<，进度：%d/%d，|cff4080FF已完成|r。", itemlink, GetClassColorName(lootplayer), data.hasLootCounts, data.itemCounts)
                            msgStr2 = format("%s已分配给>>>%s<<<，进度：%d/%d，已完成。", itemlink, lootplayer, data.hasLootCounts, data.itemCounts)
                        else
                            msgStr = format("|cffff0000警告！警告！|r%s已分配给>>>%s<<<，进度：%d/%d，|cffff0000已超额分配|r！", itemlink, GetClassColorName(lootplayer), data.hasLootCounts, data.itemCounts)
                            msgStr2 = format("警告！警告！%s已分配给>>>%s<<<，进度：%d/%d，已超额分配！", itemlink, lootplayer, data.hasLootCounts, data.itemCounts)
                        end
                        ZL.Print(msgStr, true)
                        SendChatMessage(msgStr2, "RAID")
                        if ZL.BuyItemsFrame and ZL.BuyItemsFrame:IsShown() then
                            ZL.BuyItemsFrame:Update()
                        end
                        break
                    end
                end
            end
            --记录自动分配装备的总数量
            if ZL.opt.buyerHistory and #ZL.opt.buyerHistory > 0 then
                for _, data in ipairs(ZL.opt.buyerHistory) do
                    if data.itemId == itemID and lootplayer == ParseClassColorName(data.buyerName) then
                        data.total = (data.total or 0) + count
                    end
                end
            end
            --拾取记录
            local _, _, quality, level, _, _, _, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
            if bindType == 4 then return end  --任务物品不记录
            local lootMinQuality = (ZL.opt.lootMinQuality == -1 and GetLootThreshold() or ZL.opt.lootMinQuality)
            if quality < lootMinQuality then return end
            ZL_CURRENT.bossName = ZL_CURRENT.bossName or "其他"
            local _bossName
            if stackCount > 1 then
                _bossName = "其他"
            else
                if itemID == 47242 then --北伐奖章放到 其他 里面
                    _bossName = "其他"
                else
                    _bossName = ZL_CURRENT.bossName
                end
            end
            if lootplayer == UnitName("player") then
                C_Timer.After(2, function ()
                    ZL.AuctionFrame2:Update()
                end)
            end
            lootplayer = ZL.GetClassColorName(lootplayer)
            if not ZL_PLAYERLIST.lootList then ZL_PLAYERLIST.lootList = {type="拾取记录"} end
            if not ZL_PLAYERLIST.lootList[_bossName] then ZL_PLAYERLIST.lootList[_bossName] = {} end
            if not ZL_PLAYERLIST.lootList[_bossName][itemlink] then ZL_PLAYERLIST.lootList[_bossName][itemlink] = {} end
            if not ZL_PLAYERLIST.lootList[_bossName][itemlink]["拾取1"] then ZL_PLAYERLIST.lootList[_bossName][itemlink]["拾取1"] = {lootName=lootplayer} end
            ZL_PLAYERLIST.lootList[_bossName][itemlink]["拾取1"]["counts"] = (ZL_PLAYERLIST.lootList[_bossName][itemlink]["拾取1"]["counts"] or 0) + count
            ZL_PLAYERLIST.lootList[_bossName][itemlink]["拾取1"]["itemLevel"] = level
            local selectCharKey = ZL.GetClassColorName(UnitName("player")) .. " - " .. GetRealmName()
            if ZL.opt.concernList and ZL.opt.concernList[selectCharKey]
            and ZL.opt.concernList[selectCharKey]["itemList"][itemID] and select(4, ZL.GetItemNumbers(itemID)) == 0 then
                local msgStr = "已掉落您关注的物品：" .. itemlink
                ZL.SpeakText(msgStr)
                ZL.Print(msgStr)
            end
        end
    end

    local f = CreateFrame("Frame")
    f:RegisterEvent("TRADE_ACCEPT_UPDATE")
    f:RegisterEvent("TRADE_CLOSED")
    f:RegisterEvent("MERCHANT_UPDATE")
    f:RegisterEvent("QUEST_TURNED_IN")
    f:RegisterEvent("QUEST_FINISHED")
    f:RegisterEvent("ENCOUNTER_END")
    f:RegisterEvent("CHAT_MSG_LOOT")
    f:SetScript("OnEvent", lootMsg)
end

local function quickMaster(isTooltip)
    local NumLootItems = GetNumLootItems()
    if ZL.PlayerIsML() and NumLootItems > 0 then
        local isFirst
        for i = 1, NumLootItems do
            if ZL.LootSlotIsItem(i) then
                local itemlink = GetLootSlotLink(i)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                for _, data in ipairs(ZL_CURRENT.buyerItemList) do
                    local isBreak
                    if data.itemId == itemId and data.hasLootCounts < data.itemCounts then
                        local buyerName = ParseClassColorName(data.buyerName)
                        local candidateIndex = 1
                        local candidateName = GetMasterLootCandidate(i, candidateIndex)
                        while candidateName do
                            if candidateName == buyerName then
                                if isTooltip then
                                    if not isFirst then
                                        GameTooltip:AddLine(" ")
                                        isFirst = true
                                    end
                                    GameTooltip:AddDoubleLine(
                                        itemlink, GetClassColorName(data.buyerName) .. "(" .. data.hasLootCounts .. "/" .. data.itemCounts .. ")",
                                        nil, nil, nil, 1, 1, 1
                                    )
                                else
                                    GiveMasterLoot(i, candidateIndex)
                                end
                                isBreak = true
                                break
                            end
                            candidateIndex = candidateIndex + 1
                            candidateName = GetMasterLootCandidate(i, candidateIndex)
                        end
                    end
                    if isBreak then break end
                end
            end
        end
        if isFirst then
            GameTooltip:AddLine(" ")
        end
    end
end

local parentFrame = _G["ElvLootFrame"] or _G["XLootFrame"] or _G["LootFrame"]
ZL.quickMasterButton = CreateButton(nil, parentFrame, "包\n装\n备\n一\n键\n分\n配", "TOPLEFT", parentFrame, "TOPRIGHT", 0, 0, 20, parentFrame:GetHeight())
local quickMasterButton = ZL.quickMasterButton
quickMasterButton:RegisterForClicks("LeftButtonUp", "RightButtonUp")
quickMasterButton:SetScript("OnClick", function (self, button)
    if button == "LeftButton" then
        quickMaster()
    else
        if not ZL.BuyItemsFrame then ZL:CreateBuyItemsFrame() end
        ZL.BuyItemsFrame:Show()
    end
end)
quickMasterButton:SetScript("OnEnter", function (self)
    GameTooltipShow(self, "TOPLEFT", "TOPRIGHT")
    GameTooltip:AddLine("包装备一键分配")
    quickMaster(true)
    GameTooltip:AddLine("左键：|cffffffff直接分配给指定人|r")
    GameTooltip:AddLine("右键：|cffffffff打开包装备清单窗口|r")
    GameTooltip:Show()
end)
quickMasterButton:SetScript("OnLeave", function ()
    GameTooltip:Hide()
end)

local function quickMasterButtonShow(self)
    local isShow
    local NumLootItems = GetNumLootItems()
    if ZL.PlayerIsML() and ZL_CURRENT.buyerItemList and #ZL_CURRENT.buyerItemList > 0 and NumLootItems > 0 then
        for i = 1, NumLootItems do
            if ZL.LootSlotIsItem(i) then
                local itemlink = GetLootSlotLink(i)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                for _, data in ipairs(ZL_CURRENT.buyerItemList) do
                    if data.itemId == itemId then
                        isShow = true
                        break
                    end
                end
                if isShow then break end
            end
        end
    end
    if isShow then
        quickMasterButton:Show()
    else
        quickMasterButton:Hide()
    end
end
if WOW_PROJECT_ID ~= 1 then
    hooksecurefunc("LootFrame_Show", quickMasterButtonShow)
end
if _G["LootFrame"] then
    _G["LootFrame"]:HookScript("OnShow", quickMasterButtonShow)
end

if _G["ElvLootFrame"] then
    _G["ElvLootFrame"]:HookScript("OnShow", quickMasterButtonShow)
end
if _G["XLootFrame"] then
    _G["XLootFrame"]:HookScript("OnShow", quickMasterButtonShow)
end

--包物品清单窗口
function ZL:CreateBuyItemsFrame()
    ZL.BuyItemsFrame = ZLCreateFrame("ZLBuyItemsFrame", ZL, nil, nil, nil, true, true, "包装备清单")
    local BuyItemsFrame = ZL.BuyItemsFrame
    BuyItemsFrame:Hide()
    tinsert(UISpecialFrames, BuyItemsFrame:GetName())
    BuyItemsFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
        if not ZL.glb.ZLBuyItemsFrame then ZL.glb.ZLBuyItemsFrame = {} end
        ZL.glb.ZLBuyItemsFrame.point, _, ZL.glb.ZLBuyItemsFrame.relative, ZL.glb.ZLBuyItemsFrame.x, ZL.glb.ZLBuyItemsFrame.y = self:GetPoint()
    end)
    BuyItemsFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    BuyItemsFrame:SetScript("OnShow", function (self)
        BuyItemsFrame:Update()
    end)
    local resizeButton = BuyItemsFrame.resizeButton
    -- 设置鼠标按下时开始调整大小
    resizeButton:SetScript("OnMouseDown", function(self, button)
        if button == "LeftButton" then
            BuyItemsFrame:StartSizing("BOTTOMRIGHT")
        end
    end)
    -- 鼠标松开时停止调整大小
    resizeButton:SetScript("OnMouseUp", function(self, button)
        BuyItemsFrame:StopMovingOrSizing()
        ZL.db.global.ZLAuctionFrame = ZL.db.global.ZLAuctionFrame or {}
        ZL.db.global.ZLAuctionFrame.Width,  ZL.db.global.ZLAuctionFrame.Height= BuyItemsFrame:GetSize()
    end)
    BuyItemsFrame:ClearAllPoints()
    if ZL.glb.ZLBuyItemsFrame and ZL.glb.ZLBuyItemsFrame.point then
        BuyItemsFrame:SetPoint(ZL.glb.ZLBuyItemsFrame.point, UIParent, ZL.glb.ZLBuyItemsFrame.relative, ZL.glb.ZLBuyItemsFrame.x, ZL.glb.ZLBuyItemsFrame.y)
    else
        BuyItemsFrame:SetPoint("CENTER")
    end

    local itemNameWidth, itemCountsWidth, buyerNameWidth, stateWidth, delWidth = 120, 40, 120, 50, 30
    local totalWidth = itemNameWidth + itemCountsWidth + buyerNameWidth + stateWidth + delWidth + 26
    BuyItemsFrame:SetResizeBounds(totalWidth, 350, totalWidth, GetScreenHeight()-110)
    if ZL.db.global.ZLAuctionFrame and ZL.db.global.ZLAuctionFrame.Height then
        BuyItemsFrame:SetSize(totalWidth, ZL.db.global.ZLAuctionFrame.Height)
    end
    local lineHeight = 20

    local function textChanged()
        local itemNameAddBoxText = BuyItemsFrame.itemNameAddBox:GetText()
        local buyerNameAddBoxText = BuyItemsFrame.buyerNameAddBox:GetText()
        if itemNameAddBoxText and #itemNameAddBoxText > 0 and BuyItemsFrame.itemCountsAddBox:GetNumber() > 0 and buyerNameAddBoxText and #buyerNameAddBoxText > 0 then
            BuyItemsFrame.addBtn:Enable()
        else
            BuyItemsFrame.addBtn:Disable()
        end
    end
    BuyItemsFrame.itemNameAddBox = CreateEditBox(BuyItemsFrame, itemNameWidth, lineHeight, 12, nil, nil, nil, nil, nil, nil, nil, "BuyItemsFrameItemNameAddBox")
    local itemNameAddBox = BuyItemsFrame.itemNameAddBox
    itemNameAddBox:SetPoint("TOPLEFT", BuyItemsFrame.TitleBottom, "BOTTOMLEFT", 3, -5)
    itemNameAddBox.Background:SetColorTexture(0,0,0,1)
    itemNameAddBox:SetScript("OnTextChanged", function ()
        textChanged()
    end)
    itemNameAddBox:SetScript("OnEnterPressed", function (self)
        self:ClearFocus()
        if BuyItemsFrame.addBtn:IsEnabled() then BuyItemsFrame.addBtn:Click() end
    end)
    itemNameAddBox:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("|cff4080FF物品ID|r或|cff4080FF物品链接|r", 1, 1, 1)
        GameTooltip:AddLine("不支持物品文字", 1, 0, 0)
        GameTooltip:Show()
    end)
    itemNameAddBox:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    itemNameAddBox:SetScript("OnMouseDown", function (self, button)
        if button == "LeftButton" then
            local menuList = quickMasterItemsMenu(self)
            if #menuList > 0 then
                ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0) --'cursor'
            end
        end
    end)

    BuyItemsFrame.itemCountsAddBox = CreateEditBox(BuyItemsFrame, itemCountsWidth, lineHeight, 12, nil, true, nil, nil, nil, nil, nil, "BuyItemsFrameItemCountsAddBox")
    local itemCountsAddBox = BuyItemsFrame.itemCountsAddBox
    itemCountsAddBox:SetPoint("LEFT", itemNameAddBox, "RIGHT")
    itemCountsAddBox.Background:SetColorTexture(0,0,0,1)
    itemCountsAddBox:SetScript("OnTextChanged", function (self)
        local text = self:GetText()
        textChanged()
        if text and #text > 0 and self:GetNumber() < 1 then self:SetNumber(1) end
    end)
    itemCountsAddBox:SetScript("OnEnterPressed", function (self)
        self:ClearFocus()
        if BuyItemsFrame.addBtn:IsEnabled() then BuyItemsFrame.addBtn:Click() end
    end)
    itemCountsAddBox:SetScript("OnMouseDown", function (self, button)
        if self:HasFocus() and button == "RightButton" then
            C_Timer.After(0.5, function ()
                self:ClearFocus()
                if BuyItemsFrame.addBtn:IsEnabled() then BuyItemsFrame.addBtn:Click() end
            end)
        end
    end)
    itemCountsAddBox:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("数量")
        GameTooltip:AddLine("鼠标滚轮可快速输入", 1, 1, 1)
        GameTooltip:Show()
    end)
    itemCountsAddBox:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    itemCountsAddBox:SetScript("OnMouseWheel", function(self, delta)
        if self:HasFocus() then
            local number = self:GetNumber()
            if delta > 0 then
                number = number + 1
            else
                number = number - 1
            end
            if number < 1 then
                number = 1
            end
            self:SetNumber(number)
        end
    end)

    BuyItemsFrame.buyerNameAddBox = CreateEditBox(BuyItemsFrame, buyerNameWidth, lineHeight, 12, nil, nil, nil, nil, nil, nil, nil, "BuyItemsFrameBuyerNameAddBox")
    local buyerNameAddBox = BuyItemsFrame.buyerNameAddBox
    buyerNameAddBox:SetPoint("LEFT", itemCountsAddBox, "RIGHT")
    buyerNameAddBox.Background:SetColorTexture(0,0,0,1)
    buyerNameAddBox:SetScript("OnTextChanged", function ()
        textChanged()
    end)
    buyerNameAddBox:SetScript("OnEnterPressed", function (self)
        self:ClearFocus()
        if BuyItemsFrame.addBtn:IsEnabled() then BuyItemsFrame.addBtn:Click() end
    end)
    buyerNameAddBox:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("玩家名")
        GameTooltip:Show()
    end)
    buyerNameAddBox:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    buyerNameAddBox:SetScript("OnMouseDown", function (self, button)
        if button == "LeftButton" then
            local function tempfunc(_, data)
                self:SetText(data.text)
                self:ClearFocus()
                ZL.GUI:CloseMenu()
            end
            local menuList = ZL.GroupMembersMenu(self, true, tempfunc)
            if #menuList > 0 then
                ZL.GUI:ToggleMenu(self, menuList, 'TOPLEFT', self, 'BOTTOMRIGHT', 0, 0)
            end
        end
    end)

    --设置TAB事件
    do
        local editboxList = {"BuyItemsFrameItemNameAddBox", "BuyItemsFrameItemCountsAddBox", "BuyItemsFrameBuyerNameAddBox"}
        local function OnTabPressed(self)
            EditBox_HandleTabbing(self, editboxList)
        end
        itemNameAddBox:SetScript("OnTabPressed", OnTabPressed)
        itemCountsAddBox:SetScript("OnTabPressed", OnTabPressed)
        buyerNameAddBox:SetScript("OnTabPressed", OnTabPressed)
    end
    BuyItemsFrame.addBtn = CreateButton(nil, BuyItemsFrame, "添加", "LEFT", buyerNameAddBox, "RIGHT", 3, 0, 47)
    local addBtn = BuyItemsFrame.addBtn
    addBtn:Disable()
    addBtn:SetScript("OnClick", function (self)
        local itemName, buyerName = itemNameAddBox:GetText(), buyerNameAddBox:GetText()
        local itemCounts = itemCountsAddBox:GetNumber()
        if not (#itemName > 0 and itemCounts > 0 and #buyerName > 0) then
            return
        end
        local itemId = cGetItemInfoInstant(itemName)
        if not itemId then
            ZL.Print("物品不存在！")
            return
        end
        ZL_CURRENT.buyerItemList = ZL_CURRENT.buyerItemList or {}
        local isExist
        buyerName = ParseClassColorName(buyerName)
        for index, data in ipairs(ZL_CURRENT.buyerItemList) do
            if itemId == data.itemId and buyerName == ParseClassColorName(data.buyerName) then
                isExist = index
                break
            end
        end
        if isExist then
            ZL_CURRENT.buyerItemList[isExist].itemCounts = itemCounts
            ZL_CURRENT.buyerItemList[isExist].buyerName = GetClassColorName(buyerName)

        else
            tinsert(ZL_CURRENT.buyerItemList, {
                itemId = itemId,
                itemCounts = itemCounts,
                buyerName = GetClassColorName(buyerName),
                hasLootCounts = 0,
            })
        end
        ZL.opt.buyerHistory = ZL.opt.buyerHistory or {}
        local _isExist
        for _, data in ipairs(ZL.opt.buyerHistory) do
            if data.itemId == itemId and ParseClassColorName(data.buyerName) == buyerName then
                _isExist = true
                break
            end
        end
        if not _isExist then
            tinsert(ZL.opt.buyerHistory, {
                itemId = itemId,
                buyerName = GetClassColorName(buyerName),
            })
        end
        itemNameAddBox:SetText("")
        buyerNameAddBox:SetText("")
        itemCountsAddBox:SetText("")
        itemNameAddBox:ClearFocus()
        buyerNameAddBox:ClearFocus()
        itemCountsAddBox:ClearFocus()
        BuyItemsFrame:Update()
    end)

    BuyItemsFrame.historyBtn = CreateButton(nil, BuyItemsFrame, "历史", "LEFT", addBtn, "RIGHT", 3, 0, 45)
    local historyBtn = BuyItemsFrame.historyBtn
    historyBtn:SetScript("OnClick", function (self)
        local function tempfunc()
            local menuList = {
                {text="末尾累计分配数量仅供参考", isTitle=1},
                {isSeparator = true},
            }
            if ZL.opt.buyerHistory and #ZL.opt.buyerHistory > 0 then
                tinsert(menuList, {
                    text = "|T131070:25|t|cffff0000全部删除|r",
                    func = function ()
                        ZL.opt.buyerHistory = {}
                    end
                })
                tinsert(menuList, {isSeparator = true})
                local item
                for index, data in ipairs(ZL.opt.buyerHistory) do
                    item = Item:CreateFromItemID(data.itemId)
                    if item:GetItemID() then
                        item:ContinueOnItemLoad(function()
                            local _, itemLink, _, _, _, _, _, _, _, itemTexture = cGetItemInfo(data.itemId)
                            local buyerName = GetClassColorName(data.buyerName)
                            tinsert(menuList, {
                                text = "|T" .. itemTexture .. ":14|t" .. itemLink .. " - " .. buyerName .. " - " .. (data.total or 0) ,
                                func = function ()
                                    itemNameAddBox:SetText(itemLink)
                                    buyerNameAddBox:SetText(buyerName)
                                    itemCountsAddBox:SetFocus()
                                end,
                                hasArrow = true,
                                menuTable = {
                                    {
                                        text = "校正累计数量",
                                        func = function ()
                                            StaticPopup_Show("ZL_CORRECTBUYERTOTAL", nil, nil, index)
                                        end
                                    },
                                    {
                                        text = "删除",
                                        func = function ()
                                            tremove(ZL.opt.buyerHistory, index)
                                            ZL.GUI:CloseMenu()
                                        end
                                    },
                                },
                            })
                        end)
                    end
                end
                item = nil
            end
            return menuList
        end
        local menuList = tempfunc()
        if #menuList == 0 then
            tinsert(menuList, {
                text = "没有历史记录",
                isTitle = true,
            })
        end
        ZL.GUI:ToggleMenu(self, menuList, 'cursor')
    end)

    local btnTexture = [[Interface\ACHIEVEMENTFRAME\UI-Achievement-Parchment-Horizontal]]

    BuyItemsFrame.itemNameBtn = CreateButton(nil, BuyItemsFrame, "物品名称", "TOPLEFT", itemNameAddBox, "BOTTOMLEFT", 0, -5, itemNameWidth)
    local itemNameBtn = BuyItemsFrame.itemNameBtn
    itemNameBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    itemNameBtn:SetNormalTexture(btnTexture)
    itemNameBtn:ClearHighlightTexture()

    BuyItemsFrame.itemCountsBtn = CreateButton(nil, BuyItemsFrame, "数量", "LEFT", itemNameBtn, "RIGHT", 0, 0, itemCountsWidth)
    local itemCountsBtn = BuyItemsFrame.itemCountsBtn
    itemCountsBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    itemCountsBtn:SetNormalTexture(btnTexture)
    itemCountsBtn:ClearHighlightTexture()

    BuyItemsFrame.buyerNameBtn = CreateButton(nil, BuyItemsFrame, "玩家名", "LEFT", itemCountsBtn, "RIGHT", 0, 0, buyerNameWidth)
    local buyerNameBtn = BuyItemsFrame.buyerNameBtn
    buyerNameBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    buyerNameBtn:SetNormalTexture(btnTexture)
    buyerNameBtn:ClearHighlightTexture()

    BuyItemsFrame.stateBtn = CreateButton(nil, BuyItemsFrame, "进度", "LEFT", buyerNameBtn, "RIGHT", 0, 0, stateWidth)
    local stateBtn = BuyItemsFrame.stateBtn
    stateBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
    stateBtn:SetNormalTexture(btnTexture)
    stateBtn:ClearHighlightTexture()

    BuyItemsFrame.autoMaster = CreateFrame("CheckButton", nil, BuyItemsFrame, "ChatConfigCheckButtonTemplate")
    local autoMaster = BuyItemsFrame.autoMaster
    autoMaster:SetPoint("LEFT", stateBtn, "RIGHT", 0, 0)
    autoMaster.Text:SetText("自动")
    autoMaster.Text:SetFont(GameFontNormal:GetFont(), 13, "")
    autoMaster.Text:ClearAllPoints()
    autoMaster.Text:SetPoint("LEFT", autoMaster , "RIGHT", -3, 0)
    autoMaster:SetHitRectInsets(0, -autoMaster.Text:GetWidth(), 0, 0)
    autoMaster:SetChecked(ZL.opt.autoMaster)
    autoMaster:SetScript("OnClick", function (self)
        ZL.opt.autoMaster = self:GetChecked()
    end)
    autoMaster:SetScript("OnEnter", function (self)
        GameTooltipShowAnchor(self)
        GameTooltip:AddLine("注意")
        GameTooltip:AddLine("勾选后将按顺序自动分配给指定的人", 1, 1, 1)
        GameTooltip:AddLine("注意包装备的人跳车造成资损", 1, 0, 0)
        GameTooltip:Show()
    end)
    autoMaster:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)

    --创建滚动条
    BuyItemsFrame.scrollFrame = CreateFrame("ScrollFrame", nil, BuyItemsFrame, "UIPanelScrollFrameTemplate")
    BuyItemsFrame.scrollFrame:SetFrameLevel(BuyItemsFrame:GetFrameLevel() + 1) -- 设置为比父框架高1级
    BuyItemsFrame.scrollFrame:SetPoint("TOPLEFT", itemNameBtn, "BOTTOMLEFT", -3, 0)
    BuyItemsFrame.scrollFrame:SetPoint("BOTTOMRIGHT", BuyItemsFrame, "BOTTOMRIGHT", 0, 3)
    BuyItemsFrame.scrollFrame:SetClipsChildren(true) --必须设置为true，scrollFrame所有的子元素才会被剪切
    BuyItemsFrame.scrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel) --重设滑动条鼠标滚轮事件
    --重设ScrollBar位置，放置到scrollFrame内，防止被剪切掉
    BuyItemsFrame.scrollFrame.ScrollBar:ClearAllPoints()
    BuyItemsFrame.scrollFrame.ScrollBar:SetPoint("TOPLEFT", BuyItemsFrame.scrollFrame, "TOPRIGHT", -20, -17)
    BuyItemsFrame.scrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", BuyItemsFrame.scrollFrame, "BOTTOMRIGHT", 0, 16)
    BuyItemsFrame.scrollFrame.content = CreateFrame("Frame", nil, BuyItemsFrame.scrollFrame)
    local content = BuyItemsFrame.scrollFrame.content
    content:SetPoint("TOPLEFT", BuyItemsFrame.scrollFrame, "TOPLEFT", 0, 0)
    content:SetSize(BuyItemsFrame.scrollFrame:GetWidth()-20, 100)
    BuyItemsFrame.scrollFrame:SetScrollChild(content)
    BuyItemsFrame.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
    BuyItemsFrame.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.itemicon = CreateButton(nil, f, "", "LEFT", f, "LEFT", 0, 0, lineHeight, lineHeight)
            f.itemicon:SetScript("OnEnter", function(self)
                OnEnter(self)
                if not f.itemLink then return end
                GameTooltip:ClearAllPoints()
                GameTooltip:ClearLines()
                if self:GetCenter() > UIParent:GetWidth()/2 then
                    GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT")
                else
                    GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
                end
                GameTooltip:SetHyperlink(f.itemLink)
                GameTooltip:Show()
            end)
            f.itemicon:SetScript("OnLeave", function(self)
                OnLeave(self)
                GameTooltip:Hide()
            end)

            f.itemNamebox = CreateEditBox(f, itemNameWidth-lineHeight, lineHeight, 12, "LEFT", nil, nil, board_r, board_g, board_b, board_a, "BuyItemsFrameItemNameAddBoxChild" .. v)
            f.itemNamebox:SetPoint("LEFT", f.itemicon, "RIGHT", 0, 0)
            f.itemNamebox.Background:SetColorTexture(0,0,0,0)
            f.itemNamebox.fontstring = f.itemNamebox:CreateFontString(nil, "OVERLAY")
            f.itemNamebox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.itemNamebox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.itemNamebox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.itemNamebox.fontstring:SetWordWrap(false)
            f.itemNamebox.fontstring:SetJustifyH("LEFT")
            f.itemNamebox.fontstring:SetJustifyV("MIDDLE")
            f.itemNamebox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.itemNamebox:Disable()
            f.itemNamebox:SetScript("OnEnter", function(self)
                OnEnter(self)
                if not f.itemLink then return end
                GameTooltip:ClearAllPoints()
                GameTooltip:ClearLines()
                if self:GetCenter() > UIParent:GetWidth()/2 then
                    GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT")
                else
                    GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
                end
                GameTooltip:SetHyperlink(f.itemLink)
                GameTooltip:Show()
            end)
            f.itemNamebox:SetScript("OnLeave", function(self)
                OnLeave(self)
                GameTooltip:Hide()
            end)

            f.itemCountsbox = CreateEditBox(f, itemCountsWidth, lineHeight, 12, "CENTER", true, nil, board_r, board_g, board_b, board_a, "BuyItemsFrameItemCountsAddBoxChild" .. v)
            f.itemCountsbox:SetPoint("LEFT", f.itemNamebox, "RIGHT", 0, 0)
            f.itemCountsbox.Background:SetColorTexture(0,0,0,0)
            f.itemCountsbox.fontstring = f.itemCountsbox:CreateFontString(nil, "OVERLAY")
            f.itemCountsbox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.itemCountsbox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.itemCountsbox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.itemCountsbox.fontstring:SetWordWrap(false)
            f.itemCountsbox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.itemCountsbox:SetScript("OnEnter", function(self)
                OnEnter(self)
                GameTooltipShowAnchor(self, "ANCHOR_TOP")
                GameTooltip:AddLine("鼠标滚轮可快速输入")
                GameTooltip:AddLine("按|cff4080FFEnter|r或|cff4080FF右键|r保存")
                GameTooltip:Show()
            end)
            f.itemCountsbox:SetScript("OnLeave", function(self)
                OnLeave(self)
                GameTooltip:Hide()
            end)
            f.itemCountsbox:SetScript("OnEditFocusGained", function (self)
                self.fontstring:Hide()
            end)
            f.itemCountsbox:SetScript("OnEditFocusLost", function (self)
                self.fontstring:Show()
                self.fontstring:SetText(ZL_CURRENT.buyerItemList[v].itemCounts)
                self:SetText("")
            end)
            f.itemCountsbox:SetScript("OnMouseWheel", function(self, delta)
                if self:HasFocus() then
                    local number = self:GetNumber()
                    if delta > 0 then
                        number = number + 1
                    else
                        number = number - 1
                    end
                    if number < 1 then
                        number = 1
                    end
                    self:SetNumber(number)
                end
            end)
            f.itemCountsbox:SetScript("OnTextChanged", function (self)
                if self:GetText() and #self:GetText() > 0 and self:GetNumber() < 1 then self:SetNumber(1) end
            end)
            f.itemCountsbox:SetScript("OnEnterPressed", function (self)
                if self:GetNumber() > 0 then
                    ZL_CURRENT.buyerItemList[v].itemCounts = self:GetNumber()
                end
                self:ClearFocus()
                BuyItemsFrame:Update()
            end)
            f.itemCountsbox:SetScript("OnMouseDown", function (self, button)
                if button == "RightButton" and self:HasFocus() then
                    C_Timer.After(0.5, function ()
                        if self:GetNumber() > 0 then
                            ZL_CURRENT.buyerItemList[v].itemCounts = self:GetNumber()
                        end
                        self:ClearFocus()
                        BuyItemsFrame:Update()
                    end)
                end
            end)

            f.buyerNamebox = CreateEditBox(f, buyerNameWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a, "BuyItemsFrameBuyerNameAddBoxChild" .. v)
            f.buyerNamebox:SetPoint("LEFT", f.itemCountsbox, "RIGHT", 0, 0)
            f.buyerNamebox.Background:SetColorTexture(0,0,0,0)
            f.buyerNamebox.fontstring = f.buyerNamebox:CreateFontString(nil, "OVERLAY")
            f.buyerNamebox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.buyerNamebox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.buyerNamebox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.buyerNamebox.fontstring:SetWordWrap(false)
            f.buyerNamebox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.buyerNamebox:SetScript("OnEnter", function(self)
                OnEnter(self)
                GameTooltipShowAnchor(self, "ANCHOR_TOP")
                GameTooltip:AddLine("手动输入时记得")
                GameTooltip:AddLine("按|cff4080FFEnter|r或|cff4080FF右键|r保存")
                GameTooltip:Show()
            end)
            f.buyerNamebox:SetScript("OnLeave", function(self)
                OnLeave(self)
                GameTooltip:Hide()
            end)
            f.buyerNamebox:SetScript("OnEditFocusGained", function (self)
                self.fontstring:Hide()
            end)
            f.buyerNamebox:SetScript("OnEditFocusLost", function (self)
                self.fontstring:Show()
                self.fontstring:SetText(ZL_CURRENT.buyerItemList[v].buyerName)
                self:SetText("")
            end)
            local function buyerNameboxChanged(self)
                local buyerName = ParseClassColorName(self:GetText())
                if #buyerName > 0 then
                    ZL_CURRENT.buyerItemList[v].buyerName = ParseClassColorName(self:GetText())
                end
                self:ClearFocus()
                BuyItemsFrame:Update()
            end
            f.buyerNamebox:SetScript("OnEnterPressed", function (self)
                buyerNameboxChanged(self)
            end)
            f.buyerNamebox:SetScript("OnMouseDown", function (self, button)
                if button == "LeftButton" then
                    local function tempfunc(_, data)
                        self:SetText(data.text)
                        ZL.GUI:CloseMenu()
                        buyerNameboxChanged(self)
                    end
                    local menuList = ZL.GroupMembersMenu(self, true, tempfunc)
                    if #menuList > 0 then
                        ZL.GUI:ToggleMenu(self, menuList, 'cursor')
                    end
                elseif button == "RightButton" and self:HasFocus() then
                    C_Timer.After(0.5, function ()
                        buyerNameboxChanged(self)
                    end)
                end
            end)
            --设置TAB事件
            do
                local editboxList = {"BuyItemsFrameItemNameAddBoxChild" .. v, "BuyItemsFrameItemCountsAddBoxChild" .. v, "BuyItemsFrameBuyerNameAddBoxChild" .. v}
                local function OnTabPressed(self)
                    EditBox_HandleTabbing(self, editboxList)
                end
                f.itemNamebox:SetScript("OnTabPressed", OnTabPressed)
                f.itemCountsbox:SetScript("OnTabPressed", OnTabPressed)
                f.buyerNamebox:SetScript("OnTabPressed", OnTabPressed)
            end
            f.statebox = CreateEditBox(f, stateWidth, lineHeight, 12, "CENTER", nil, nil, board_r, board_g, board_b, board_a)
            f.statebox:SetPoint("LEFT", f.buyerNamebox, "RIGHT", 0, 0)
            f.statebox.Background:SetColorTexture(0,0,0,0)
            f.statebox:Disable()
            f.statebox.fontstring = f.statebox:CreateFontString(nil, "OVERLAY")
            f.statebox.fontstring:SetPoint("TOPLEFT", 3, -1)
            f.statebox.fontstring:SetPoint("BOTTOMRIGHT", -3, 1)
            f.statebox.fontstring:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.statebox.fontstring:SetWordWrap(false)
            f.statebox.fontstring:SetTextColor(0.95, 0.95, 0.95, 1)
            f.statebox:SetScript("OnEnter", function(self)
                OnEnter(self)
            end)
            f.statebox:SetScript("OnLeave", function(self)
                OnLeave(self)
            end)

            f.delBtn = CreateButton(nil, f, "-", "LEFT", f.statebox, "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)
                if not StaticPopupDialogs["ZL_DELBUYITEMSCONFIRM"] then
                    --更改拍卖模式警告提醒
                    StaticPopupDialogs["ZL_DELBUYITEMSCONFIRM"] = {
                        text = "%s",
                        button1 = "确定",
                        button2 = "取消",
                        OnAccept = function(self, data)
                            tremove(ZL_CURRENT.buyerItemList, data)
                            BuyItemsFrame:Update()
                        end,
                        timeout = 0,
                        whileDead = true,
                        hideOnEscape = true,
                    }
                end
                StaticPopup_Show("ZL_DELBUYITEMSCONFIRM", "确定删除这条记录？", nil, v)
            end)

            t[v] = f
            return f
        end
    })

    function BuyItemsFrame:Update()
        for _, f in ipairs(BuyItemsFrame.entries) do f:Hide() end
        if not ZL_CURRENT.buyerItemList then return end
        for index, data in ipairs(ZL_CURRENT.buyerItemList) do
            local f = BuyItemsFrame.entries[index]
            local item = Item:CreateFromItemID(data.itemId)
            if item:GetItemID() then
                item:ContinueOnItemLoad(function()
                    local _, itemLink, _, _, _, _, _, _, _, itemTexture = cGetItemInfo(data.itemId)
                    f.itemLink = itemLink
                    f.itemicon:SetNormalTexture(itemTexture)
                    f.itemNamebox.fontstring:SetText(itemLink)
                    f.itemCountsbox.fontstring:SetText(data.itemCounts)
                    f.buyerNamebox.fontstring:SetText(GetClassColorName(data.buyerName))
                    if data.hasLootCounts < data.itemCounts then
                        f.statebox.fontstring:SetText(tostring(data.hasLootCounts) .. "/" .. tostring(data.itemCounts))
                    elseif data.hasLootCounts == data.itemCounts then
                        f.statebox.fontstring:SetText("|T136814:16|t")
                    else
                        f.statebox.fontstring:SetText("|cffff0000" .. tostring(data.hasLootCounts) .. "/" .. tostring(data.itemCounts) .. "|r")
                    end
                    f:Show()
                end)
            end
        end
    end
end
