local addonName, ZLAUTO = ...

local ZL = ZLAUTO.mainFrame
if ZL.BUILD_DATA >= 4 then return end

local ScrollFrame_OnMouseWheel = ZL.ScrollFrame_OnMouseWheel
local ZLCreateFrame = ZL.ZLCreateFrame
local CreateButton = ZL.CreateButton
local CreateEditBox = ZL.CreateEditBox
local GameTooltipShow = ZL.GameTooltipShow
local emptytable = ZL.emptytable

local function SetCopper(money, frameType)
    if not money or type(money) ~= "number" then return end
    frameType = frameType or "UnitPrice"  --StackPrice
    local gold = floor(money / (COPPER_PER_GOLD))
	local silver = floor((money - (gold * COPPER_PER_GOLD)) / COPPER_PER_SILVER)
	local copper = mod(money, COPPER_PER_SILVER)
    HookAuctionFrame = ZL.HookAuctionFrame
    if frameType == "UnitPrice" then
        HookAuctionFrame.UnitGoldPrice:SetNumber(gold)
        HookAuctionFrame.UnitSilverPrice:SetNumber(silver)
        HookAuctionFrame.UnitCopperPrice:SetNumber(copper)
    elseif frameType == "StackPrice" then
        HookAuctionFrame.StackGoldPrice:SetNumber(gold)
        HookAuctionFrame.StackSilverPrice:SetNumber(silver)
        HookAuctionFrame.StackCopperPrice:SetNumber(copper)
    else
        return
    end
end
local function GetAuctionSortColumn(sortTable)
	local existingSortColumn, existingSortReverse = GetAuctionSort(sortTable, 1);
    if (existingSortColumn == "totalbuyout" or existingSortColumn == "unitbid" or existingSortColumn == "unitprice") then
		existingSortColumn = "bid";
	end
	return existingSortColumn, existingSortReverse
end
local function Set_AuctionSort_Column(sortTable)
    SetCVar("auctionSortByBuyoutPrice", 1)
    SetCVar("auctionSortByUnitPrice", 1)
    AuctionFrame_SetSort(sortTable or "list", "bid", false)
end

local function MoneyInputEidtBox(parent, maxLetters, width, atlasName)
    -- local editBox = CreateFrame("EditBox", nil, parent or ZL.HookAuctionFrame, "InputBoxTemplate")
    local editBox = CreateEditBox(parent or ZL.HookAuctionFrame, width or 40, 20, 14, "RIGHT", true, nil, nil, nil, nil, nil)
    if maxLetters then
        editBox:SetMaxLetters(maxLetters)
    end
    if atlasName then
        editBox.Icon = editBox:CreateTexture(nil, "ARTWORK")
        editBox.Icon:SetSize(12, 14)
        editBox.Icon:SetPoint("RIGHT", 13, -2)
        editBox.Icon:SetAtlas(atlasName)
    end
    return editBox
end

local function UpdateSortAnim(isPlay)
    local sortBtn  = ZL.HookAuctionFrame.sortBtn
    if isPlay then
        sortBtn.SpellHighlightAnim:Play()
        sortBtn.SpellHighlightTexture:Show()
    else
        sortBtn.SpellHighlightAnim:Stop()
        sortBtn.SpellHighlightTexture:Hide()
    end
end
local function UpdateUnitPrice()
    local HookAuctionFrame = ZL.HookAuctionFrame
    local gold = HookAuctionFrame.StackGoldPrice:GetNumber()
    local silver = HookAuctionFrame.StackSilverPrice:GetNumber()
    local copper = HookAuctionFrame.StackCopperPrice:GetNumber()
    local count = HookAuctionFrame.StackCount:GetNumber()
    local stackMoney = gold*10000 + silver*100 + copper
    local unitMoney = floor(stackMoney/count)
    SetCopper(unitMoney)
end
local function UpdateStackPrice()
    local HookAuctionFrame = ZL.HookAuctionFrame
    local gold = HookAuctionFrame.UnitGoldPrice:GetNumber()
    local silver = HookAuctionFrame.UnitSilverPrice:GetNumber()
    local copper = HookAuctionFrame.UnitCopperPrice:GetNumber()
    local count = HookAuctionFrame.StackCount:GetNumber()
    local unitMoney = gold*10000 + silver*100 + copper
    local stackMoney = unitMoney*count
    SetCopper(stackMoney, "StackPrice")
end
local function UpdateDepositMoney()
    local HookAuctionFrame = ZL.HookAuctionFrame
    local StackSize = HookAuctionFrame.StackCount:GetNumber()
    local NumStacks = HookAuctionFrame.NumStacks:GetNumber()
    local perDepositMoney = GetAuctionDeposit(1, 1, 1, StackSize, 1) --AuctionFrameAuctions.duration or 0, startPrice, buyoutPrice, AuctionsStackSizeEntry:GetNumber(), AuctionsNumStacksEntry:GetNumber())
    HookAuctionFrame.depositMoneyLabel:SetText(format("单组保管费：|cffffffff%s|r", GetMoneyString(perDepositMoney)))
    HookAuctionFrame.totalDepositMoneyLabel:SetText(format("所有保管费：|cffffffff%s|r", GetMoneyString(perDepositMoney*NumStacks)))
end
local f = CreateFrame("Frame")
f:RegisterEvent("AUCTION_HOUSE_SHOW")
f:SetScript("OnEvent", function (slef, event, ...)
    if event == "AUCTION_HOUSE_SHOW" then
        if not ZL.HookAuctionFrame then
            if AuctionFrame and _G["BrowseButton1"] then
                ZL:CreateHookAuctionFrame()
                local id = 1
                local btn = _G["BrowseButton" .. id]
                while btn do
                    btn:HookScript("OnClick", function (self)
                        local itemID = select(10, GetAuctionSellItemInfo())
                        local _itemID = select(17, GetAuctionItemInfo("list", self.itemIndex==50 and 50 or mod(self.itemIndex,50)))
                        if itemID and itemID == _itemID and self.buyoutPrice and self.buyoutPrice > 0 then
                            local UnitPrice = floor(self.buyoutPrice/self.itemCount) - 1
                            -- print("UnitPrice", UnitPrice, self.itemIndex, self.buyoutPrice)
                            SetCopper(UnitPrice)
                            SetCopper(UnitPrice*HookAuctionFrame.StackCount:GetNumber(), "StackPrice")
                        end
                    end)
                    id = id + 1
                    btn = _G["BrowseButton" .. id]
                end
                btn = nil
            end
        end
        Set_AuctionSort_Column()
    end
end)

function ZL:CreateHookAuctionFrame()
    ZL.HookAuctionFrame = ZLCreateFrame(nil, AuctionFrame, 300, AuctionFrame:GetHeight()-27, nil, nil, nil, "AutoAuction(|cffffffff拍卖|r)")
    local HookAuctionFrame = ZL.HookAuctionFrame
    HookAuctionFrame.Background:SetColorTexture(0.05, 0.05, 0.05, 1)
    HookAuctionFrame:SetPoint("TOPLEFT", AuctionFrame, "TOPRIGHT", 0, -15)
    HookAuctionFrame.resizeButton:Hide()
    HookAuctionFrame:SetScript("OnShow", function ()
        HookAuctionFrame.New_Auction_Update()
        UpdateDepositMoney()
    end)
    HookAuctionFrame:SetScript("OnMouseUp", function (self, button)
        if button == "LeftButton" then
            local edit = GetCurrentKeyBoardFocus()
            if edit then
                edit:ClearFocus()
            end
        end
    end)
    local showBtn = CreateButton(nil, AuctionFrame, ">>", "LEFT", BrowseSearchButton, "RIGHT", 13, 3, 30, BrowseSearchButton:GetHeight()-4, 14, true, 0)
    HookAuctionFrame.showBtn = showBtn
    showBtn:SetScript("OnClick", function ()
        if HookAuctionFrame:IsShown() then
            HookAuctionFrame:Hide()
        else
            HookAuctionFrame:Show()
        end
    end)
    local lockBtnFrame = CreateFrame("Button", nil, HookAuctionFrame)
    HookAuctionFrame.lockBtnFrame = lockBtnFrame
    lockBtnFrame:SetPoint("TOPLEFT", _G["BrowseQualitySort"], "TOPLEFT")
    lockBtnFrame:SetPoint("BOTTOMRIGHT", _G["BrowsePriceOptionsButtonFrame"].Button, "BOTTOMRIGHT")

    local ItemName = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    ItemName:SetSize(HookAuctionFrame:GetWidth() - 114, 20)
    ItemName:SetJustifyH("LEFT")
    ItemName:SetPoint("TOPLEFT", 5, -30)
    HookAuctionFrame.ItemName = ItemName

    local infoBtn = CreateFrame("Button", nil, HookAuctionFrame)
    HookAuctionFrame.infoBtn = infoBtn
    infoBtn:SetSize(30, 30)
    infoBtn:SetPoint("LEFT", ItemName, "RIGHT", 0, 0)
    infoBtn:SetNormalTexture(616343)
    infoBtn:SetHighlightTexture(616343)
    infoBtn:SetScript("OnClick", function ()
        ZL.Print("按Ctrl+V复制观看")
        ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
        ChatEdit_InsertLink("https://www.bilibili.com/video/BV1qjmcB7EM5/")
        ChatEdit_ChooseBoxForSend():HighlightText()
    end)
    infoBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(HookAuctionFrame, "TOPLEFT", "TOPRIGHT")
        GameTooltip:AddLine("使用方法")
        GameTooltip:AddLine("1、禁用其他带有拍卖功能的插件，避免卡顿；", 1, 1, 1)
        GameTooltip:AddLine("2、拍卖行选择搜索界面；", 1, 1, 1)
        GameTooltip:AddLine("3、背包|CFFFFDE00Shift+左键|r选择需要拍卖的物品；", 1, 1, 1)
        GameTooltip:AddLine("4、点击搜索", 1, 1, 1)
        GameTooltip:AddLine("5、确认单价、堆叠数和组数无误", 1, 1, 1)
        GameTooltip:AddLine("6、点击|CFFFFDE00开始拍卖|r", 1, 1, 1)
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("注意事项")
        GameTooltip:AddLine("1、搜索文本只支持原生方法：", 1, 1, 1)
        GameTooltip:AddLine("如:手动输入、复制粘贴、Shift+左键点击物品\n或链接", 1, 1, 1)
        GameTooltip:AddLine("2、有些插件会污染原生Shift+左键点击功能，\n造成搜索卡顿", 1, 1, 1)
        GameTooltip:AddLine("3、只能手动点击搜索按钮，其他一切方法都\n会造成搜索卡顿", 1, 1, 1)
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("点击观看视频")
        GameTooltip:Show()
    end)
    infoBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    local lockBtn = CreateFrame("Button", nil, HookAuctionFrame)
    HookAuctionFrame.lockBtn = lockBtn
    lockBtn:SetSize(30, 30)
    lockBtn:SetPoint("LEFT", infoBtn, "RIGHT", -4, 0)
    local lockTexture = [[Interface\BUTTONS\LockButton-Locked-Up.blp]]
    local unlockTexture = [[Interface\BUTTONS\LockButton-Unlocked-Up.blp]]
    if ZL.opt.AuctionSortLock then
        lockBtn:SetNormalTexture(lockTexture)
        lockBtn:SetHighlightTexture(lockTexture)
        lockBtnFrame:Show()
    else
        lockBtn:SetNormalTexture(unlockTexture)
        lockBtn:SetHighlightTexture(unlockTexture)
        lockBtnFrame:Hide()
    end
    lockBtn:SetScript("OnClick", function ()
        if ZL.opt.AuctionSortLock then
            ZL.opt.AuctionSortLock = false
        else
            ZL.opt.AuctionSortLock = true
        end
        if ZL.opt.AuctionSortLock then
            Set_AuctionSort_Column()
            HookAuctionFrame.sortBtn.SpellHighlightAnim:Stop()
            HookAuctionFrame.sortBtn.SpellHighlightTexture:Hide()
            lockBtn:SetNormalTexture(lockTexture)
            lockBtn:SetHighlightTexture(lockTexture)
            lockBtnFrame:Show()
        else
            lockBtn:SetNormalTexture(unlockTexture)
            lockBtn:SetHighlightTexture(unlockTexture)
            lockBtnFrame:Hide()
        end
    end)
    lockBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        if ZL.opt.AuctionSortLock then
            GameTooltip:AddLine("提示")
            GameTooltip:AddLine("左侧排序按钮已锁定，点击解锁", 1, 1, 1)
        else
            GameTooltip:AddLine("注意")
            GameTooltip:AddLine("排序未锁定，单价可能无法自动\n获取到最低价，点击锁定", 1, 0, 0)
        end
        GameTooltip:Show()
    end)
    lockBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    local sortBtn = CreateButton(nil, HookAuctionFrame, "排序", "LEFT", lockBtn, "RIGHT", 2, 0, 45, 20, 14, true, 0)
    sortBtn:SetScript("OnClick", function ()
        Set_AuctionSort_Column()
        UpdateSortAnim()
    end)
    sortBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("提示")
        GameTooltip:AddLine("按钮如发光，表示未按指定要求排序;", 1, 1, 1)
        GameTooltip:AddLine("单价可能无法自动获取到最低一口价;", 1, 1, 1)
        GameTooltip:AddLine("点击左侧按钮可锁定排序", 1, 1, 1)
        GameTooltip:Show()
    end)
    sortBtn.SpellHighlightTexture = sortBtn:CreateTexture("SpellHighlightTexture1", "OVERLAY", nil, 1)
    local SpellHighlightTexture = sortBtn.SpellHighlightTexture
    SpellHighlightTexture:SetAtlas("bags-newitem")
    SpellHighlightTexture:SetSize(60, 26)
    SpellHighlightTexture:SetPoint("CENTER")
    SpellHighlightTexture:SetBlendMode("ADD")
    SpellHighlightTexture:Hide()
    -- 创建 SpellHighlightAnim 动画组（循环播放）
    sortBtn.SpellHighlightAnim = SpellHighlightTexture:CreateAnimationGroup() --"SpellHighlightAnim"
    local SpellHighlightAnim = sortBtn.SpellHighlightAnim
    SpellHighlightAnim:SetLooping("REPEAT")
    -- 第一个 Alpha 动画（淡入）
    local alpha1 = SpellHighlightAnim:CreateAnimation("Alpha")
    alpha1:SetChildKey("SpellHighlightTexture")
    alpha1:SetSmoothing("OUT")
    alpha1:SetDuration(0.75)
    alpha1:SetOrder(1)
    alpha1:SetFromAlpha(0)
    alpha1:SetToAlpha(1)
    -- 第二个 Alpha 动画（淡出）
    local alpha2 = SpellHighlightAnim:CreateAnimation("Alpha")
    alpha2:SetChildKey("SpellHighlightTexture")
    alpha2:SetSmoothing("IN")
    alpha2:SetDuration(0.75)
    alpha2:SetOrder(2)
    alpha2:SetFromAlpha(1)
    alpha2:SetToAlpha(0)
    HookAuctionFrame.sortBtn = sortBtn
    local ItemButton = CreateFrame("Button", nil, HookAuctionFrame)
    ItemButton:SetSize(40, 40)
    ItemButton:SetPoint("TOPLEFT", ItemName, "BOTTOMLEFT", 0, -5)
    ItemButton:SetHighlightTexture([[Interface\Buttons\ButtonHilight-Square]])
    ItemButton:SetPushedTexture([[Interface\Buttons\UI-Quickslot-Depress]])
    ItemButton:SetScript("OnEnter", function (self)
        if self.itemID then
            GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
            GameTooltip:SetItemByID(self.itemID)
            GameTooltip:Show()
        end
    end)
    ItemButton:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    ItemButton:SetScript("OnClick", function (self)
        if self.itemID then
            _G["BrowseName"]:SetText(ItemName:GetText())
        end
    end)
    ItemButton.EmptySlot = ItemButton:CreateTexture(nil, "BACKGROUND")
    ItemButton.EmptySlot:SetTexture("Interface\\BUTTONS\\UI-Slot-Background")
    ItemButton.EmptySlot:SetDrawLayer("BACKGROUND", 1) -- 设置textureSubLevel
    ItemButton.EmptySlot:SetAllPoints()
    ItemButton.EmptySlot:SetTexCoord(0, 0.640625, 0, 0.640625)

    ItemButton.icon = ItemButton:CreateTexture(nil, "BACKGROUND")
    -- ItemButton.icon:SetTexture(132881)
    ItemButton.icon:SetDrawLayer("BACKGROUND", 2)
    ItemButton.icon:SetAllPoints()

    ItemButton.IconBorder = ItemButton:CreateTexture(nil, "BACKGROUND")
    ItemButton.IconBorder:SetTexture("Interface\\Common\\WhiteIconFrame")
    ItemButton.IconBorder:SetDrawLayer("BACKGROUND", 3)
    ItemButton.IconBorder:SetAllPoints()
    HookAuctionFrame.ItemButton = ItemButton

    local UnitPriceLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    UnitPriceLabel:SetText("单价")
    UnitPriceLabel:SetHeight(20)
    UnitPriceLabel:SetPoint("TOPLEFT", ItemButton, "TOPRIGHT", 5, 0)
    local UnitGoldPrice = MoneyInputEidtBox(HookAuctionFrame, 8, 90, "auctionhouse-icon-coin-gold")
    UnitGoldPrice:SetPoint("LEFT", UnitPriceLabel, "RIGHT", 8, 0)
    UnitGoldPrice:SetScript("OnTextChanged", function ()
        UpdateStackPrice()
    end)
    HookAuctionFrame.UnitGoldPrice = UnitGoldPrice
    local UnitSilverPrice = MoneyInputEidtBox(HookAuctionFrame, 2, 30, "auctionhouse-icon-coin-silver")
    UnitSilverPrice:SetPoint("LEFT", UnitGoldPrice, "RIGHT", 20, 0)
    UnitSilverPrice:SetScript("OnTextChanged", function ()
        UpdateStackPrice()
    end)
    HookAuctionFrame.UnitSilverPrice = UnitSilverPrice
    local UnitCopperPrice = MoneyInputEidtBox(HookAuctionFrame, 2, 30, "auctionhouse-icon-coin-copper")
    UnitCopperPrice:SetPoint("LEFT", UnitSilverPrice, "RIGHT", 20, 0)
    UnitCopperPrice:SetScript("OnTextChanged", function ()
        UpdateStackPrice()
    end)
    HookAuctionFrame.UnitCopperPrice = UnitCopperPrice

    local StackPriceLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    StackPriceLabel:SetText("堆叠")
    StackPriceLabel:SetHeight(20)
    StackPriceLabel:SetPoint("TOPLEFT", UnitPriceLabel, "BOTTOMLEFT", 0, -3)
    local StackGoldPrice = MoneyInputEidtBox(HookAuctionFrame, 8, 90, "auctionhouse-icon-coin-gold")
    StackGoldPrice:SetPoint("LEFT", StackPriceLabel, "RIGHT", 8, 0)
    StackGoldPrice:SetScript("OnTextChanged", function ()
        UpdateUnitPrice()
    end)
    HookAuctionFrame.StackGoldPrice = StackGoldPrice
    local StackSilverPrice = MoneyInputEidtBox(HookAuctionFrame, 2, 30, "auctionhouse-icon-coin-silver")
    StackSilverPrice:SetPoint("LEFT", StackGoldPrice, "RIGHT", 20, 0)
    StackSilverPrice:SetScript("OnTextChanged", function ()
        UpdateUnitPrice()
    end)
    HookAuctionFrame.StackSilverPrice = StackSilverPrice
    local StackCopperPrice = MoneyInputEidtBox(HookAuctionFrame, 2, 30, "auctionhouse-icon-coin-copper")
    StackCopperPrice:SetPoint("LEFT", StackSilverPrice, "RIGHT", 20, 0)
    StackCopperPrice:SetScript("OnTextChanged", function ()
        UpdateUnitPrice()
    end)
    HookAuctionFrame.StackCopperPrice = StackCopperPrice

    local StackCountLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    StackCountLabel:SetText("堆叠数")
    StackCountLabel:SetHeight(20)
    StackCountLabel:SetPoint("TOPLEFT", ItemButton, "BOTTOMLEFT", 0, -10)
    local StackCount = MoneyInputEidtBox(nil, nil, 42)
    StackCount:SetPoint("LEFT", StackCountLabel, "RIGHT", 8, 0)
    StackCount:SetNumber(1)
    StackCount:SetScript("OnTextChanged", function (self)
        local number = self:GetNumber()
        local name, _, _, _, _, _, _, stackCount, totalCount = GetAuctionSellItemInfo()
        if name then
            local maxStackCount = min(stackCount, totalCount)
            if number > maxStackCount then
                self:SetNumber(maxStackCount)
            elseif self:GetNumber() == 0 then
                self:SetNumber(1)
            end
            local oldNumStacks = HookAuctionFrame.NumStacks:GetNumber()
            local maxNumStacks = floor(totalCount/self:GetNumber())
            if oldNumStacks > maxNumStacks then
                HookAuctionFrame.NumStacks:SetNumber(maxNumStacks)
            end
            HookAuctionFrame.MaxNumStacksBtn:SetText("最大值:" .. totalCount)
        elseif self:GetNumber() == 0 then
            self:SetNumber(1)
        end
        UpdateStackPrice()
        UpdateDepositMoney()
    end)
    HookAuctionFrame.StackCount = StackCount
    local MaxStackCountBtn = CreateFrame("Button", nil, HookAuctionFrame)
    MaxStackCountBtn:SetSize(StackCountLabel:GetWidth() + 8 + StackCount:GetWidth(), 20)
    MaxStackCountBtn:SetNormalFontObject("GameFontNormalSmall")
    MaxStackCountBtn:SetHighlightFontObject("GameFontHighlightSmall")
    MaxStackCountBtn:SetHighlightTexture("UIPanelButtonHighlightTexture")
    MaxStackCountBtn:SetText("最大值:")
    do
        local fontString = MaxStackCountBtn:GetFontString()
        fontString:SetFont(GameFontNormal:GetFont(), 13)
        fontString:ClearAllPoints()
        fontString:SetPoint("LEFT")
        fontString:SetJustifyH("LEFT")
    end
    MaxStackCountBtn:SetPoint("TOPLEFT", StackCountLabel, "BOTTOMLEFT", 0, -3)
    MaxStackCountBtn:SetScript("OnClick", function ()
        local name, _, _, _, _, _, _, stackCount, totalCount = GetAuctionSellItemInfo()
        if name then
            StackCount:SetNumber(min(stackCount, totalCount))
        end
    end)
    HookAuctionFrame.MaxStackCountBtn = MaxStackCountBtn

    local NumStacksLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    NumStacksLabel:SetText("组数")
    NumStacksLabel:SetHeight(20)
    NumStacksLabel:SetPoint("LEFT", StackCount, "RIGHT", 10, 0)
    local NumStacks = MoneyInputEidtBox(nil, 3, 43)
    NumStacks:SetPoint("LEFT", NumStacksLabel, "RIGHT", 8, 0)
    NumStacks:SetNumber(1)
    NumStacks:SetScript("OnTextChanged", function (self)
        local number = self:GetNumber()
        local _stackCount = StackCount:GetNumber()
        local name, _, _, _, _, _, _, stackCount, totalCount = GetAuctionSellItemInfo()
        if name then
            if number > totalCount then
                self:SetNumber(totalCount)
            elseif number == 0 then
                self:SetNumber(1)
            end
            local maxStackCount = min(stackCount, totalCount, floor(totalCount/self:GetNumber()))
            if _stackCount > maxStackCount then
                StackCount:SetNumber(maxStackCount)
            end
            MaxStackCountBtn:SetText("最大值:" .. min(stackCount, totalCount))
        elseif self:GetNumber() == 0 then
            self:SetNumber(1)
        end
        UpdateDepositMoney()
    end)
    HookAuctionFrame.NumStacks = NumStacks
    local MaxNumStacksBtn = CreateFrame("Button", nil, HookAuctionFrame)
    MaxNumStacksBtn:SetSize(NumStacksLabel:GetWidth() + 8 + NumStacks:GetWidth(), 20)
    MaxNumStacksBtn:SetNormalFontObject("GameFontNormalSmall")
    MaxNumStacksBtn:SetHighlightFontObject("GameFontHighlightSmall")
    MaxNumStacksBtn:SetHighlightTexture("UIPanelButtonHighlightTexture")
    MaxNumStacksBtn:SetText("最大值:")
    do
        local fontString = MaxNumStacksBtn:GetFontString()
        fontString:SetFont(GameFontNormal:GetFont(), 13)
        fontString:ClearAllPoints()
        fontString:SetPoint("LEFT")
        fontString:SetJustifyH("LEFT")
    end
    MaxNumStacksBtn:SetPoint("TOPLEFT", NumStacksLabel, "BOTTOMLEFT", 0, -3)
    MaxNumStacksBtn:SetScript("OnClick", function ()
        local name, _, _, _, _, _, _, _, totalCount = GetAuctionSellItemInfo()
        if name then
            NumStacks:SetNumber(totalCount)
        end
    end)
    HookAuctionFrame.MaxNumStacksBtn = MaxNumStacksBtn
    HookAuctionFrame.StartAuctionBtn = CreateButton(nil, HookAuctionFrame, "开始拍卖", "TOPLEFT", NumStacks, "TOPRIGHT", 10, 0, 80, 43, 14, true, 0)
    local StartAuctionBtn = HookAuctionFrame.StartAuctionBtn
    StartAuctionBtn:SetScript("OnClick", function (self)
        local name, texture, _, quality, _, _, _, _, _, itemID = GetAuctionSellItemInfo()
        if texture then
            local stackSize = StackCount:GetNumber()
            local numStacks = NumStacks:GetNumber()
            local buyoutPrice = (UnitGoldPrice:GetNumber()*10000 + UnitSilverPrice:GetNumber()*100 + UnitCopperPrice:GetNumber()) * stackSize
            local minBid = buyoutPrice * 0.99
            local runTime = 1
            if stackSize > 0 and numStacks > 0 and buyoutPrice > 0 then
                if PostAuction(minBid, buyoutPrice, runTime, stackSize, numStacks, false) then
                    AuctionsCreateAuctionButton:ClearPost();
                else
                    AuctionsCreateAuctionButton:CachePendingPost(minBid, buyoutPrice, runTime, stackSize, numStacks, false);
                end
            end
        end
    end)

    local depositMoneyLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    depositMoneyLabel:SetSize(HookAuctionFrame:GetWidth() - 10, 18)
    depositMoneyLabel:SetFont(GameFontNormal:GetFont(), 13)
    depositMoneyLabel:SetJustifyH("LEFT")
    depositMoneyLabel:SetTextColor(1, 0.82, 0)
    depositMoneyLabel:SetPoint("TOPLEFT", MaxStackCountBtn, "BOTTOMLEFT", 0, -5)
    -- depositMoneyLabel:SetText("保管费：")
    HookAuctionFrame.depositMoneyLabel = depositMoneyLabel

    local totalDepositMoneyLabel = HookAuctionFrame:CreateFontString(nil, "ARTWORK")
    totalDepositMoneyLabel:SetSize(HookAuctionFrame:GetWidth() - 10, 18)
    totalDepositMoneyLabel:SetFont(GameFontNormal:GetFont(), 13)
    totalDepositMoneyLabel:SetJustifyH("LEFT")
    totalDepositMoneyLabel:SetTextColor(1, 0.82, 0)
    totalDepositMoneyLabel:SetPoint("TOPLEFT", depositMoneyLabel, "BOTTOMLEFT", 0, -3)
    -- totalDepositMoneyLabel:SetText("总金额：")
    HookAuctionFrame.totalDepositMoneyLabel = totalDepositMoneyLabel

    function HookAuctionFrame.New_Auction_Update()
        local name, texture, _, quality, _, _, _, stackCount, totalCount, itemID = GetAuctionSellItemInfo()
        if name then
            ItemButton:Enable()
            ItemButton.icon:SetTexture(texture)
            ItemButton.itemID = itemID
            ItemName:SetText(name)
            local color = ITEM_QUALITY_COLORS[quality]
            ItemName:SetVertexColor(color.r, color.g, color.b)
            local maxStackCount = min(stackCount, totalCount)
            if StackCount:GetNumber() > maxStackCount then
                StackCount:SetNumber(maxStackCount)
            end
            if NumStacks:GetNumber() > totalCount then
                NumStacks:SetNumber(totalCount)
            end
            MaxStackCountBtn:SetText("最大值:" .. min(stackCount, totalCount))
            MaxNumStacksBtn:SetText("最大值:" .. totalCount)
        else
            ItemButton:Disable()
            ItemButton.icon:SetTexture()
            ItemButton.itemID = nil
            ItemName:SetText("")
            UnitGoldPrice:SetNumber(0)
            UnitSilverPrice:SetNumber(0)
            UnitCopperPrice:SetNumber(0)
            StackGoldPrice:SetNumber(0)
            StackSilverPrice:SetNumber(0)
            StackCopperPrice:SetNumber(0)
            -- StackCount:SetNumber(1)
            -- NumStacks:SetNumber(1)
            MaxStackCountBtn:SetText("最大值:")
            MaxNumStacksBtn:SetText("最大值:")
        end
    end
    local New_Auction_Update = HookAuctionFrame.New_Auction_Update
    HookAuctionFrame:RegisterEvent("NEW_AUCTION_UPDATE")
    HookAuctionFrame:RegisterEvent("AUCTION_ITEM_LIST_UPDATE")
    HookAuctionFrame:SetScript("OnEvent", function (self, event, ...)
        local arg = emptytable(...)
        if event == "NEW_AUCTION_UPDATE" then
            New_Auction_Update()
            UpdateDepositMoney()
        elseif event == "AUCTION_ITEM_LIST_UPDATE" then
            local existingSortColumn, existingSortReverse = GetAuctionSortColumn("list")
            if existingSortColumn ~= "bid" or existingSortReverse ~= false then
                SpellHighlightTexture:Show()
                UpdateSortAnim(true)
                return
            else
                SpellHighlightTexture:Hide()
                UpdateSortAnim()
            end
            local itemID = select(10, GetAuctionSellItemInfo())
            if not itemID then return end
            local _, totalAuctions = GetNumAuctionItems("list")
            if totalAuctions == 0 then
                return
            elseif totalAuctions > 50 then
                if AuctionFrameBrowse.page and AuctionFrameBrowse.page > 0 then
                    return
                end
            end
            local _, _, count, _, _, _, _, _, _, buyoutPrice, _, _, _, _, _, _, itemId = GetAuctionItemInfo("list", 1)
            if itemId == itemID and buyoutPrice then
                local UnitPrice = floor(buyoutPrice/count) - 1
                SetCopper(UnitPrice)
                SetCopper(UnitPrice*HookAuctionFrame.StackCount:GetNumber(), "StackPrice")
            end
        end
        arg:Release()
    end)
end