local addonName, ZLAUTO= ...
ZLAUTO.mainFrame = CreateFrame("Frame", nil, UIParent) --主框架
ZLAUTO.mainFrame:SetPoint("CENTER")
ZLAUTO.mainFrame:SetSize(1, 1)
local ZL = ZLAUTO.mainFrame
ZL.GUI = LibStub('tdGUI-1.0')
local GetAddOnMetadata = C_AddOns and C_AddOns.GetAddOnMetadata or GetAddOnMetadata
local GetItemCount = C_Item and C_Item.GetItemCount or GetItemCount
ZL.addonVersion = GetAddOnMetadata(addonName, "Version")
ZL.addonVersionA, ZL.addonVersionB, ZL.addonVersionC = ZL.addonVersion:match("^V(%d+)%.(%d+)%.(%d+)")
ZL.addonVersionA = tonumber(ZL.addonVersionA) or 0
ZL.addonVersionB = tonumber(ZL.addonVersionB) or 0
ZL.addonVersionC = tonumber(ZL.addonVersionC) or 0
local MyAddon = LibStub("AceAddon-3.0"):GetAddon("FastAuction", true)
if not MyAddon then
    MyAddon = LibStub("AceAddon-3.0"):NewAddon("FastAuction", "AceComm-3.0", 'LibClass-2.0', 'AceEvent-3.0') --
end
ZL.MyAddon = MyAddon
ZLAUTO.MyAddon = MyAddon
local REALM_SEPARATOR_LIST = {}
for s in REALM_SEPARATORS:gmatch(".") do tinsert(REALM_SEPARATOR_LIST, s) end

--设置消息前缀为[FastAuction]
function ZL.Prefix(...)
    return string.join(" ", format("|cff4080FF%s|r", "[FastAuction]"), tostringall(...))
end

--聊天窗口默认不显示, 滚动消息默认显示
function ZL.Print(msgStr, ChatFrame, notScrollFrame, r, g, b)
    r = r or 1
    g = g or 0.82
    b = b or 0
    if ChatFrame then
        DEFAULT_CHAT_FRAME:AddMessage(ZL.Prefix(msgStr), r, g, b)
    end
    if not notScrollFrame then
        ZL.ScrollingMessageFrame:AddMessage(msgStr, r, g, b)
    end
end

-- 如果GetUnitName不能解析名字为unitID，需我们自己的定义，手动解析
function ZL.localNameOnly(name)
	for _, s in ipairs(REALM_SEPARATOR_LIST) do
		local i = name:find(s, 1, true)
		if i then name = name:sub(1, i - 1) end
	end
	return name
end
--自定义手动解析玩家名字
function ZL.pruneCrossRealm(name)
	return GetUnitName(name, true) or ZL.localNameOnly(name)
end
--创建默认按钮
function ZL.CreateButton(ButtonName, parent, ButtonText, point, relativeto, relativePoint, offsetX, offsetY, Width, Height, fontSize, NormalTexture, BorderA)
	offsetX = offsetX or 0
	offsetY = offsetY or 0
	Width = Width or 70
	Height = Height or 20
	fontSize = fontSize or 14
    BorderA = BorderA or 0.5
	local btn = CreateFrame("Button", ButtonName, parent) -- , "UIPanelButtonTemplate"
    ZL.CreateBorder(btn, 0.24, 0.25, 0.3, BorderA, "OVERLAY", 1)
	btn:SetText(ButtonText or " ")
	btn:SetSize(Width, Height)
    btn:SetPoint(point, relativeto, relativePoint, offsetX, offsetY)
    do
        local texture = btn:CreateTexture(nil,"BACKGROUND")
		texture:SetColorTexture(0,0,0,1)
		texture:SetPoint("TOPLEFT")
		texture:SetPoint("BOTTOMRIGHT")
        btn.Background = texture
    end

    if NormalTexture then
        local texture = btn:CreateTexture(nil,"BACKGROUND")
        texture:SetColorTexture(1,1,1,1)
        texture:SetGradient("VERTICAL",CreateColor(0.05,0.06,0.09,1), CreateColor(0.20,0.21,0.25,1))
        texture:SetPoint("TOPLEFT")
        texture:SetPoint("BOTTOMRIGHT")
        btn:SetNormalTexture(texture)
    end
    do
        local texture = btn:CreateTexture()
        texture:SetColorTexture(0.9,0.9,0.9,.2)
        texture:SetPoint("TOPLEFT")
        texture:SetPoint("BOTTOMRIGHT")
        btn:SetHighlightTexture(texture)
    end
    -- do
    --     local texture = btn:CreateTexture()
    --     texture:SetColorTexture(.9,.8,.1,.3)
    --     texture:SetPoint("TOPLEFT")
    --     texture:SetPoint("BOTTOMRIGHT")
    --     btn:SetPushedTexture(texture)
    -- end
	btn:SetNormalFontObject("GameFontNormal")
	btn:SetHighlightFontObject("GameFontHighlight")
	btn:SetDisabledFontObject("GameFontDisable")
    local fontString = btn:GetFontString()
    if fontString then
	    fontString:SetFont(GameFontNormal:GetFont(), fontSize)
    end
	return btn
end

function ZL.CreateHeaderButton(parent, width, height, size)
    local btn = CreateFrame("Button", nil, parent)
    btn:SetSize(width or 40, height or 21)

    -- 背景层
    local backgroundLeft = btn:CreateTexture("backgroundLeft", "BACKGROUND")
    backgroundLeft:SetTexture("Interface\\ChatFrame\\ChatFrameTab")
    backgroundLeft:SetSize(8, height)
    backgroundLeft:SetPoint("TOPLEFT")
    backgroundLeft:SetTexCoord(0.0625, 0.1875, 0.34375, 1)

    local backgroundRight = btn:CreateTexture("backgroundRight", "BACKGROUND")
    backgroundRight:SetTexture("Interface\\ChatFrame\\ChatFrameTab")
    backgroundRight:SetSize(8, height)
    backgroundRight:SetPoint("TOPRIGHT")
    backgroundRight:SetTexCoord(0.8125, 0.9375, 0.34375, 1)
    -- backgroundRight:SetColorTexture(0.25, 0.25, 0.25, 1)
    
    local backgroundMid = btn:CreateTexture("backgroundMid", "BACKGROUND")
    backgroundMid:SetTexture("Interface\\ChatFrame\\ChatFrameTab")
    backgroundMid:SetSize(0, height)
    backgroundMid:SetPoint("TOPLEFT", 8, 0)
    backgroundMid:SetPoint("TOPRIGHT", -8, 0)
    backgroundMid:SetTexCoord(0.1875, 0.8125, 0.34375, 1)
    -- backgroundMid:SetColorTexture(0.25, 0.25, 0.25, 1)

    do
        local texture = btn:CreateTexture()
        texture:SetColorTexture(0, 0, 1, 0.2)
        texture:SetPoint("TOPLEFT")
        texture:SetPoint("BOTTOMRIGHT")
        btn:SetHighlightTexture(texture)
    end
    -- 按钮文本
    -- local customFont = CreateFont("CustomFont")
    -- customFont:SetFont(GameFontNormal:GetFont(), size or 14, "")  -- 字体路径、大小、字体样式
    -- customFont:SetTextColor(1, 1, 1)
	-- btn:SetNormalFontObject(customFont) --GameFontNormal
    btn:SetNormalFontObject("GameFontNormal")
	btn:SetHighlightFontObject("GameFontHighlight")
	btn:SetDisabledFontObject("GameFontDisable")
    -- local fontString = btn:GetFontString()
	-- fontString:SetFont(GameFontNormal:GetFont(), size)

    return btn
end
--创建边框
function ZL.CreateBorder(frame, r, g, b, a, drawLayer, size)
    drawLayer = drawLayer or "BACKGROUND"
    size = size or 1
    frame.BorderTop = frame.BorderTop or frame:CreateTexture(nil,drawLayer) --BACKGROUND  OVERLAY
    frame.BorderTop:SetColorTexture(r,g,b,a)
    -- frame.BorderTop:SetTexture([[Interface\Common\UI-TooltipDivider-Transparent]])
    frame.BorderTop:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
    frame.BorderTop:SetPoint("BOTTOMRIGHT",frame,"TOPRIGHT",0,-size)
    -- frame.BorderTop = frame.BorderTop or frame:CreateLine()
    -- frame.BorderTop:SetColorTexture(r,g,b,a)
    -- frame.BorderTop:SetStartPoint("TOPLEFT", 0, 0)
    -- frame.BorderTop:SetEndPoint("TOPRIGHT", 0, 0)
    -- frame.BorderTop:SetThickness(size)

    frame.BorderLeft = frame.BorderLeft or frame:CreateTexture(nil,drawLayer)
    frame.BorderLeft:SetColorTexture(r,g,b,a)
    frame.BorderLeft:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
    frame.BorderLeft:SetPoint("BOTTOMRIGHT",frame,"BOTTOMLEFT",size,0)
    -- frame.BorderLeft = frame.BorderLeft or frame:CreateLine()
    -- frame.BorderLeft:SetColorTexture(r,g,b,a)
    -- frame.BorderLeft:SetStartPoint("TOPLEFT", 0, 0)
    -- frame.BorderLeft:SetEndPoint("BOTTOMLEFT", 0, 0)
    -- frame.BorderLeft:SetThickness(size)


    frame.BorderBottom = frame.BorderBottom or frame:CreateTexture(nil,drawLayer)
    frame.BorderBottom:SetColorTexture(r,g,b,a)
    -- frame.BorderBottom:SetTexture([[Interface\Common\UI-TooltipDivider-Transparent]])
    frame.BorderBottom:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0)
    frame.BorderBottom:SetPoint("TOPRIGHT",frame,"BOTTOMRIGHT",0,size)
    -- frame.BorderBottom = frame.BorderBottom or frame:CreateLine()
    -- frame.BorderBottom:SetColorTexture(r,g,b,a)
    -- frame.BorderBottom:SetStartPoint("BOTTOMLEFT", 0, 0)
    -- frame.BorderBottom:SetEndPoint("BOTTOMRIGHT", 0, 0)
    -- frame.BorderBottom:SetThickness(size)

    frame.BorderRight = frame.BorderRight or frame:CreateTexture(nil,drawLayer)
    frame.BorderRight:SetColorTexture(r,g,b,a)
    frame.BorderRight:SetPoint("TOPLEFT",frame,"TOPRIGHT",0,0)
    frame.BorderRight:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-1,0)
    -- frame.BorderRight = frame.BorderRight or frame:CreateLine()
    -- frame.BorderRight:SetColorTexture(r,g,b,a)
    -- frame.BorderRight:SetStartPoint("TOPRIGHT", 0, 0)
    -- frame.BorderRight:SetEndPoint("BOTTOMRIGHT", 0, 0)
    -- frame.BorderRight:SetThickness(size)
end

--创建框架
function ZL.ZLCreateFrame(FrameName, parent, Width, Height, FrameStrata, ClampedToScreen, Movable, TitleText)
    local f = CreateFrame("Frame", FrameName, parent or ZL)
    ZL.CreateBorder(f, 1, 1, 1, 0.5, "OVERLAY", 1)
    f:SetSize(Width or 305, Height or 350)
    f:SetFrameStrata(FrameStrata or "DIALOG")
    f:SetClampedToScreen(ClampedToScreen and true or false)
    f:SetMovable(Movable and true or false)
    f:SetResizable(true)
    f:SetToplevel(true)
    f:SetResizeBounds(305, 219, GetScreenWidth()-30, GetScreenHeight()-50) -- 设置最小尺寸，以避免框架被缩小到看不见
    ZL.CreateResizeButton(f)

    f.Background = f:CreateTexture(nil,"BACKGROUND")
    f.Background:SetColorTexture(0, 0, 0, .8)
    f.Background:SetPoint("TOPLEFT")
    f.Background:SetPoint("BOTTOMRIGHT")

    f.TitleBottom = f:CreateTexture(nil,"ARTWORK")
    f.TitleBottom:SetColorTexture(1, 1, 1, 0.5)
    f.TitleBottom:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -26)
    f.TitleBottom:SetPoint("BOTTOMRIGHT", f, "TOPRIGHT", 0, -27)

    f.Title = f:CreateFontString(nil, "OVERLAY")
    f.Title:SetFont(GameFontNormal:GetFont(), 15, "")
    f.Title:SetTextColor(1, 0.82, 0)
    f.Title:SetWordWrap(false)
    f.Title:SetJustifyH("CENTER")
    f.Title:SetJustifyV("MIDDLE")
    f.Title:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -1)
    f.Title:SetPoint("TOPRIGHT", f, "TOPRIGHT", -20, 0)
    f.Title:SetHeight(26)
    f.Title:SetText(TitleText or "")

    f.closeButton = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    f.closeButton:SetPoint("LEFT", f.Title, "RIGHT", -5, 0)
    f.closeButton:SetSize(25, 25)
    f.closeButton:SetScript("OnClick", function (self)
        f:Hide()
    end)
    if Movable then
        f:SetScript("OnMouseUp", function (self)
            self:StopMovingOrSizing()
        end)
        f:SetScript("OnMouseDown", function (self)
            self:StartMoving()
        end)
    end
    return f
end
--创建文本框
--parent, width, heigth, fontSize, justifyH, numeric, multiLine, r, g, b, a, name
function ZL.CreateEditBox(parent, width, heigth, fontSize, justifyH, numeric, multiLine, r, g, b, a, name)
    r = r or 0.24
    g = g or 0.25
    b = b or 0.3
    a = a or 1
    local editBox = CreateFrame("EditBox", name, parent, BackdropTemplateMixin and "BackdropTemplate")
    editBox:EnableMouse(true)
    ZL.CreateBorder(editBox, r, g, b, a, "OVERLAY", 1)

    editBox.Background = editBox:CreateTexture(nil,"BACKGROUND")
    editBox.Background:SetColorTexture(0,0,0,1)
    editBox.Background:SetPoint("TOPLEFT")
    editBox.Background:SetPoint("BOTTOMRIGHT")

    editBox:SetFontObject("ChatFontNormal")

    editBox:SetTextInsets(4, 4, 0, 0)
    editBox:SetSize(width or 60, heigth or 20)
    editBox:SetFont(GameFontNormal:GetFont(), fontSize or 14, "")
    editBox:SetMultiLine(multiLine)
    editBox:SetTextColor(0.95, 0.95, 0.95)
    editBox:SetAutoFocus(false)
    editBox:SetNumeric(numeric)
    editBox:SetJustifyH(justifyH or "CENTER")

    editBox:SetScript("OnEscapePressed",function (self)
        self:ClearFocus()
    end)
    editBox:SetScript("OnEnterPressed", function (self)
        self:ClearFocus()
    end)
    editBox:SetScript("OnEditFocusLost",function (self)
        self:HighlightText(0, 0)
    end)
    editBox:SetScript("OnEditFocusGained",function (self)
        self:HighlightText()
    end)

    return editBox
end

--创建拉升按钮
function ZL.CreateResizeButton(parent)
    -- 创建右下角的拉伸角标
    -- AuctionFrame.resizeButton = CreateFrame("Button", nil, AuctionFrame)
    local resizeButton = CreateFrame("Button", nil, parent)
    resizeButton:SetSize(16, 16)
    resizeButton:SetPoint("BOTTOMRIGHT")

    -- 设置拉伸角标的纹理，可以是默认的角标图案
    resizeButton.texture = resizeButton:CreateTexture(nil, "BACKGROUND")
    resizeButton.texture:SetAllPoints()
    resizeButton.texture:SetTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Up") -- 默认拉伸图标
    -- 鼠标悬停和点击效果
    resizeButton:SetHighlightTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Highlight")
    resizeButton:SetPushedTexture("Interface\\ChatFrame\\UI-ChatIM-SizeGrabber-Down")
    -- 设置鼠标按下时开始调整大小
    resizeButton:SetScript("OnMouseDown", function(self, button)
        if button == "LeftButton" then
            parent:StartSizing("BOTTOMRIGHT")
        end
    end)
    -- 鼠标松开时停止调整大小
    resizeButton:SetScript("OnMouseUp", function(self, button)
        parent:StopMovingOrSizing()
    end)
    parent.resizeButton = resizeButton
end

--重写滑动条鼠标滚动事件
function ZL.ScrollFrame_OnMouseWheel(self, delta)
    local newValue = self:GetVerticalScroll() - (delta * 20)
    if newValue < 0 then
        newValue = 0
    elseif newValue > self:GetVerticalScrollRange() then
        newValue = self:GetVerticalScrollRange()
    end
    self:SetVerticalScroll(newValue)
end

--格式为：“2025-01-01”, endtime 默认为今天，返回秒数
function ZL.GetDiffTime(_startTime, _endTime)
    _endTime = _endTime or date("%Y-%m-%d", GetServerTime())
    local agoYear, agoMonth, agoDay = _startTime:match("(%d+)-(%d+)-(%d+)")
    local startTime = time{year=agoYear, month=agoMonth, day=agoDay, hour=0, min=0, sec=0}

    local endyear, endmonth, endday = _endTime:match("(%d+)-(%d+)-(%d+)")
    local endTime = time{year=endyear, month=endmonth, day=endday, hour=0, min=0, sec=0} -- 当前时间
    return difftime(endTime, startTime)
end
-- 计算指定天数前的日期
function ZL.getDateDaysAgo(days)
    return date("%Y-%m-%d", time() - (days * 86400))
end

--定义空元表
function ZL.emptytable(...)
    local logTableRequests = false
    local tables = {}
    local meta = {
        __index = {
            Release=function(t,noRecursion)
                if not noRecursion then
                    for key,val in pairs(t) do
                        if (type(val) == "table") and (getmetatable(val) == "TempTable") then
                            val:Release()
                        end
                    end
                end
                table.wipe(t)
                if not tContains(tables,t) then
                    tinsert(tables,t)
                end
            end,
        },
        __metatable = "TempTable",
    }
    if logTableRequests then
        TempTables_RequestLog = {}
    end
    local t = tremove(tables) or setmetatable({},meta)
    for i=1,select('#',...) do
        t[i] = (select(i,...))
    end
    if logTableRequests then
        local tostrT = tostring(t)
        TempTables_RequestLog[tostrT] = TempTables_RequestLog[tostrT] or {}
        tinsert(TempTables_RequestLog[tostrT],debugstack())
    end
    return t
end

--提示消息1
function ZL.GameTooltipShow(self, point, relativePoint, offsetX, offsetY)
    offsetX = offsetX or 0
    offsetY = offsetY or 0
    GameTooltip:ClearAllPoints()
    GameTooltip:ClearLines()
    GameTooltip:SetOwner(self, "ANCHOR_NONE")
    GameTooltip:SetPoint(point, self, relativePoint, offsetX, offsetY)
end

--获取物品装备、背包、银行中的数量
function ZL.GetItemNumbers(itemId)
    if not type(itemId) == "number" or itemId <= 0 then return end
    local inventoryCount = 0
    for slot = 1, 19 do -- 遍历所有装备栏（1-19）
        local item = GetInventoryItemID("player", slot)
        if item == itemId then
            inventoryCount = inventoryCount + 1
        end
    end
    local itemBagCount = GetItemCount(itemId) --获取背包+角色装备物品数量
    local bagCount = itemBagCount - inventoryCount --背包数量
    local itemTotalCount = GetItemCount(itemId, true) --获取背包+角色装备+银行物品数量
    local itemBankCount = itemTotalCount - itemBagCount --银行物品数量
    return inventoryCount, bagCount, itemBankCount, itemTotalCount
end

--创建滚动消息框架
function ZL:CreateScrollingMessageFrame()
    ZL.ScrollingMessageFrame = CreateFrame("ScrollingMessageFrame", "MyScrollingMessageFrame", UIParent)
    local ScrollingMessageFrame = ZL.ScrollingMessageFrame
    ScrollingMessageFrame:SetSize(1000, 150)
    ScrollingMessageFrame:SetPoint("TOP", UIParent, "TOP", 0, 0)
    ScrollingMessageFrame:SetFrameStrata("FULLSCREEN_DIALOG")
    ScrollingMessageFrame:SetClampedToScreen(true)  --不能超出游戏屏幕，false可以超出游戏屏幕
    ScrollingMessageFrame:SetFont(GameFontNormal:GetFont(), 20, "OUTLINE")
    ScrollingMessageFrame:SetJustifyH("CENTER")
    ScrollingMessageFrame:SetJustifyV("TOP")
    ScrollingMessageFrame:SetMaxLines(5)
    ScrollingMessageFrame:SetSpacing(3)
    ScrollingMessageFrame:SetFadeDuration(2)
    ScrollingMessageFrame:SetTimeVisible(6)
    ScrollingMessageFrame:SetHyperlinksEnabled(true)
    ScrollingMessageFrame:SetScript("OnHyperlinkEnter", function(self, link)
        local itemID = GetItemInfoInstant(link)
        if itemID then
            GameTooltip:SetOwner(self, "ANCHOR_CURSOR", 0, 0)
            GameTooltip:ClearLines()
            GameTooltip:SetHyperlink(link)
            GameTooltip:Show()
        end
    end)
    ScrollingMessageFrame:SetScript("OnHyperlinkLeave", function(self)
        GameTooltip:Hide()
    end)
    ScrollingMessageFrame:SetScript("OnHyperlinkClick", function (self, link, _, button)
        local linkType, missionID, txt, arg4 = strsplit(":", link)
        if linkType == "garrmission" then
            if missionID == "FastAuction" then
                if txt == "unAuctionSortLock" then
                    ZL.HookAuctionFrame.lockBtn:Click()
                    local _link = "搜索排序已解锁，可能无法自动获取到最低一口价" .. format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "FastAuction", "AuctionSortLock", "锁定")
                    ZL.Print(_link)
                elseif txt == "AuctionSortLock" then
                    ZL.HookAuctionFrame.lockBtn:Click()
                    local _link = "搜索排序已锁定" .. format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "FastAuction", "unAuctionSortLock", "解锁")
                    ZL.Print(_link)
                        
                end
            end
        end
    end)
end

--文字转语音
function ZL.SpeakText(text)
    C_VoiceChat.StopSpeakingText()
    C_Timer.After(0.1, function ()
        C_VoiceChat.SpeakText(C_TTSSettings.GetVoiceOptionID(0),  text, 1, 4, 100)
    end)
end