local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local pruneCrossRealm = ZL.pruneCrossRealm
local Prefix = ZL.Prefix
local emptytable = ZL.emptytable
local PlayerIsML = ZL.PlayerIsML
local GetStartAndIncrementBid = ZL.GetStartAndIncrementBid
local GetAuctioningCount = ZL.GetAuctioningCount
local fullwidthToHalfwidth = ZL.fullwidthToHalfwidth
local tableSort = ZL.tableSort
local LootSlotIsItem = ZL.LootSlotIsItem
local isFilterItem = ZL.isFilterItem
local TransmitAddonInfo_Pro = ZL.TransmitAddonInfo_Pro
local padZeros = ZL.padZeros
local msg_gsub = ZL.msg_gsub
local GetCurrentRoster = ZL.GetCurrentRoster
local GetMasterLootCandidates = ZL.GetMasterLootCandidates
local GetClassColorName = ZL.GetClassColorName
local ParseClassColorName = ZL.ParseClassColorName
local GetMLname = ZL.GetMLname
local CheckWaVersion = ZL.CheckWaVersion
local cGetItemInfo, cGetItemIcon
if WOW_PROJECT_ID == 1 then
    cGetItemInfo = C_Item.GetItemInfo
    cGetItemIcon = C_Item.GetItemIconByID
else --WOW_PROJECT_ID == 11 then
    cGetItemInfo = GetItemInfo
    cGetItemIcon = GetItemIcon
end
local previousRoster = {} --初始化团队成员
ZL.count = 0

local defaults = {
	profile = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 30,
		startBid = 300,
		increment = 100,
        baseAmount1 = 5000,
        baseAmount2 = 10000,
        baseAmount3 = 50000,
        bidIncrement1 = 500,
        bidIncrement2 = 1000,
        bidIncrement3 = 1000,
		minQuality = -1,
        lootMinQuality = -1,
		awardToML = false,
		buttonReenableDelay = 1,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = false,
        developerMode = false,
        announceRaidWarning = false,
        CountdownAnnounceRaidWarning = true,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistory = false,
        autoClearHistoryDays = 30,
        overrideArchive = true,
        profanityFilter = true,
        IsVoiceReminder = true,
        IsTradeRemainingVoiceReminder = true,
        TradeRemainingTimer = 30,
        TradeRemainingReminderPinlv = 5,
        RLBuTieType = 1,
        ZLAuctionFrameTabId = 1,
        showAllWages = false,
        wagesGroupMembers = 0,
        MLChangeGroup = false,
        liupaiToggle = false,
        liupaiBagId = 0,
        liupaiBagId2 = 1,
        liupaiDirection = false,
        selfToggle = false,
        selfBagId = 0,
        selfDirection = false,
        BOEToggle = false,
        BOEBagId = 0,
        BOEDirection = false,
        emptyOneSpace = true,
        isSYNCAll = false,
        waitingBagHighLight = false,
        auctioningBagHighLight = false,
        successBagHighLight = false,
        failedBagHighLight = false,
        lgnoreBagHighLight = false,
        tipShow = false,
        levelSort = false,
        timeSort = "up",
        autoAddStartBid = false,
        AuctionFrameHide = false,
        RemainingTradeTimeFrameHide = true,
        ItemSettingFrameHide = true,
        AuctionRecordFrameHide = true,
        SettingFrameHide = true,
        VoiceReminderSoundType = 1,
        startAuctionSound = true,
        intervalBidIncrement = false,
        maxFrameHide = false,
        bidColumnHide = false,
        startbidColumnHide = false,
        functionColumnHide = false,
        itemLevelHide = false,
        itemCountHide = false,
        itemIndexHide = false,
        itemNameHide = false,
        bidEditBoxHide = false,
        bidBtnHide = false,
        lgnoreBtnHide = true,
        bidCountsHide = false,
        startBidHide = false,
        inrementHide = false,
        startBtnHide = false,
        pauseBtnHide = false,
        countdownBtnHide = false,
        packageBtnHide = false,
        reverseBidBtnHide = false,
        syncBtnHide = false,
        delAuctionBtnHide = false,
        floatBidFrameHide = false,
        floatStartBidFrameHide = false,
        floatFunctionFrameHide = false,
        ShortcutTipHide = false,
        currentDetailToolTipHide = false,
        xiaoFeiToolTipHide = false,
        recordShortcutTipHide = false,
	}
}
function ZL:OnProfileEnable()
	ZL.opt = ZL.db.profile
    TransmitAddonInfo_Pro()
end

local fZL = CreateFrame("Frame")

local filterItemId = {
    {
        ["itemlink"] = "|cffff8000|Hitem:22726::::::::80:::::::::|h[埃提耶什的碎片]|h|r",
        ["auction"] = false,
        ["loot"] = true,
        ["itemId"] = 22726,
    }, -- [1]
    {
        ["itemlink"] = "|cffff8000|Hitem:45038::::::::80:::::::::|h[瓦兰奈尔的碎片]|h|r",
        ["itemId"] = 45038,
        ["auction"] = false,
        ["loot"] = true,
    }, -- [2]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cff0070dd|Hitem:46110::::::::80:::::::::|h[炼金师的宝箱]|h|r",
        ["itemId"] = 46110,
    }, -- [3]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:50274::::::::80:::::::::|h[影霜碎片]|h|r",
        ["itemId"] = 50274,
    }, -- [4]
}

local function mainInit(self, event, ...)
    local arg = emptytable(...)
    local AuctionFrame = ZL.AuctionFrame2
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        -- local f = CreateFrame("ScrollingMessageFrame", "BG.FrameLootMsg", UIParent, "BackdropTemplate")
        for i = 1, NUM_CHAT_WINDOWS do
            _G["ChatFrame"..i.."EditBox"]:SetAltArrowKeyMode(true)
        end

        SLASH_ZL_RELOAD1 = "/rl"
        SlashCmdList.ZL_RELOAD = ReloadUI
        SLASH_ZL_TOOLBOX1 ="/ac"
        SlashCmdList.ZL_TOOLBOX = function ()
            -- _G["ZLAuctionFrame"]:Show()
            ZL.maxFrame:Hide()
            ZL.AuctionFrame2:Show()
        end

        local itemLevelSetting = {
            {
                ["minLevel"] = 225,
                ["sanJianStartBid"] = 300,
                ["wuQiStartBid"] = 500,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 300,
                ["maxLevel"] = 225,
            }, -- [1]
            {
                ["minLevel"] = 232,
                ["sanJianStartBid"] = 500,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 1000,
                ["maxLevel"] = 232,
            }, -- [2]
            {
                ["minLevel"] = 238,
                ["maxLevel"] = 239,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 1000,
            }, -- [3]
            {
                ["minLevel"] = 245,
                ["maxLevel"] = 245,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 1000,
            }, -- [4]
            {
                ["minLevel"] = 252,
                ["maxLevel"] = 252,
                ["wuQiStartBid"] = 3000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 3000,
            }, -- [5]
            {
                ["minLevel"] = 258,
                ["maxLevel"] = 258,
                ["wuQiStartBid"] = 5000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 3000,
                ["sanJianStartBid"] = 3000,
            }, -- [6]
            {
                ["minLevel"] = 272,
                ["maxLevel"] = 272,
                ["wuQiStartBid"] = 10000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 10000,
            }, -- [7]
        }
        ZL_CURRENT = ZL_CURRENT or {}
        ZL_HISTORY = ZL_HISTORY or {}
        ZL_SETTING = ZL_SETTING or {itemLevelSetting=itemLevelSetting, itemIdSetting={}, filterItemId=filterItemId}

        ZL.db = LibStub("AceDB-3.0"):New("ZL_Profile", defaults) --创建默认配置数据库
        ZL.db.RegisterCallback(ZL, "OnProfileChanged", "OnProfileEnable")
		ZL.db.RegisterCallback(ZL, "OnProfileCopied", "OnProfileEnable")
		ZL.db.RegisterCallback(ZL, "OnProfileReset", "OnProfileEnable")
        ZL.opt = ZL.db.profile

        ZL.options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(ZL.db)
		ZL.options.args.profiles.order = -1
		LibStub("AceConfig-3.0"):RegisterOptionsTable("金团拍卖助手", ZL.options)
        LibStub("AceConfigDialog-3.0"):SetDefaultSize("金团拍卖助手", 700, 500)
        --将选项表添加到暴雪的内置“界面”选项面板中
        if WOW_PROJECT_ID ~= 2 then
            LibStub("AceConfigDialog-3.0"):AddToBlizOptions("金团拍卖助手", "|cff0011ffAutoAuction|r")
        end
        --Minimap Icon Creation
		ZL.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga",
			OnClick = function(self, button)
                if button == "LeftButton" and IsShiftKeyDown() then
                    ReloadUI()
                else
                    ZL.OpenAceConfigDialog("金团拍卖助手")
                end

			end,
			OnTooltipShow = function(tooltip)
				tooltip:AddLine("金团拍卖助手(|cffffffff" .. ZL.addonVersion .. "|r)")
				tooltip:AddLine("自动化拍卖、出价、记账、工资分配、一键批量邮寄工资和补贴、离队计算工资等", 1, 1, 1, true)
				tooltip:AddLine(" ")
				tooltip:AddLine("左键点击|cffffffff : 打开设置窗口|r ")
                tooltip:AddLine("Shift+左键点击：|cffffffff重新加载用户界面|r")
			end
		})
        ZL.minimapicon = LibStub("LibDBIcon-1.0")
		ZL.minimapicon:Register("ZLAUTOLDB", ZL.LDB, ZL.db.global)
        ZL.opt.lgnoreBtnHide = true --忽略按钮已取消，强制隐藏

        -- if not ZL.AuctionFrame then ZL:CreateAuctionFrame() end
        if not ZL.AuctionRecordFrame then ZL:CreateAuctionRecordFrame() end
        if not ZL.AuctionFrame2 then ZL:CreateAuctionFrame2() end
        if not ZL.FloatAuctionFrame then ZL:CreateFloatAuctionFrame() end
        if not ZL.maxFrame then ZL:CreateMaxAuctionFrame() end
        if not ZL.ItemSettingFrame then ZL:CreateItemSettingFrame() end
        
        if not ZL.ZLRemainingTradeTimeFrame then ZL:CreateZLRemainingTradeTimeFrame() end
        if not ZL.ShowAuctionRecordFrame then ZL:CreateShowAuctionRecordFrame() end
        if not ZL.BidderListFrame then ZL:CreateBidderListFrame() end
        if not ZL.PackageListFrame then ZL:CreatePackageListFrame() end
        if not ZL.ScrollingMessageFrame then ZL:CreateScrollingMessageFrame() end

        ZL.opt.ZLAuctionRecordFrameIsShown = false
        --CTR+右键点击物品链接自动创建拍卖物品
        --CTR+左键点击物品链接流拍物品自动开始拍卖
        hooksecurefunc("SetItemRef", function(link, text, button)
            local linkType, linkData = strsplit(":", link)
            if linkType == "myaddon" then
                if button == "LeftButton" then
                    -- 当点击超链接时，显示一个自定义窗口
                    print("Hyperlink clicked! Displaying custom window...")
                    -- 在这里添加显示窗口的代码
                end
            else
                local _, itemLink, _, _, _, _, _, stackCount = cGetItemInfo(link)
                if itemLink and PlayerIsML() and IsInRaid() and IsControlKeyDown() then
                    if button == "RightButton" then
                        if stackCount == 1 then
                            ZL.ManualCreateAuctionItem(itemLink, 1)
                            print(Prefix("警告！非背包物品创建，可能存在部分功能无法实现！已创建拍卖物品：" .. itemLink))
                        else
                            local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
                            StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=nil})
                        end
                    elseif button == "LeftButton" then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for index, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.state == "failed" or data.state == "waiting") and data.itemlink == itemLink then
                                    local f = ZL.AuctionFrame2.entries[index]
                                    f.MLframe.functionFrame.CancelBtn:Click()
                                    break
                                end
                            end
                        end
                    end
                elseif button == "LeftButton" and IsShiftKeyDown then
                    ZL.ChatEditInsertLink(itemLink)
                end
            end
        end)
        --CTR+右键点击背包物品自动创建拍卖物品
        hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", function(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            local itemLink = containerInfo.hyperlink
            if PlayerIsML() and IsInRaid() and button == "RightButton" and IsControlKeyDown() then
                local itemLoc = ItemLocation:CreateFromBagAndSlot(self:GetParent():GetID(), self:GetID())
                local itemGuid = C_Item.GetItemGUID(itemLoc)
                if (not ZL_CURRENT["itemGUIDUsed"]) or (not ZL_CURRENT["itemGUIDUsed"][itemGuid]) then
                    if not ZL_CURRENT["itemGUIDUsed"] then ZL_CURRENT["itemGUIDUsed"] = {} end
                    local itemId = containerInfo.itemID
                    local stackCount = select(8, cGetItemInfo(itemLink))
                    if stackCount == 1 then
                        ZL.ManualCreateAuctionItem(itemLink, 1, itemGuid)
                        ZL_CURRENT["itemGUIDUsed"][itemGuid] = true
                        print(Prefix("已创建拍卖物品：" .. itemLink))
                    else
                        StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=itemGuid})
                    end
                else
                    print(Prefix("注意：" .. itemLink .. "已存在，请勿重复创建！"))
                end
                itemLoc:Clear()
            elseif button == "LeftButton" and IsShiftKeyDown() then
                ZL.ChatEditInsertLink(itemLink)
            end
        end)

        hooksecurefunc("ContainerFrameItemButton_OnEnter", function(self, button)
            -- local link = C_Container.GetContainerItemLink(self:GetParent():GetID(), self:GetID())
            -- GameTooltip:AddLine(link)
            -- GameTooltip:AddLine(link)
            -- GameTooltip:AddLine(link)
        end)
        --增加鼠标提示信息
        hooksecurefunc(GameTooltip, "SetBagItem", function(self, bag, slot)
            if not ZL.opt.tipShow then return end
            local itemLocation = ItemLocation:CreateFromBagAndSlot(bag, slot)
            if C_Item.DoesItemExist(itemLocation) then
                local itemGuid = C_Item.GetItemGUID(itemLocation)
                if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                    for _, data in ipairs(ZL_CURRENT.auctionlist) do
                        if data.itemGUID and next(data.itemGUID, nil) then
                            for key, value in pairs(data.itemGUID) do
                                if key == itemGuid then
                                    local r, g, b, a = unpack(ZL.colorList[data.state])
                                    local str
                                    if data.state == "waiting" then
                                        str = ZL.RGBAToHex(r*255, g*255, b*255, a*255) .. "待拍卖" .. "|r"
                                    elseif data.state == "auctioning" then
                                        str = ZL.RGBAToHex(r*255, g*255, b*255, a*255) .. "拍卖中" .. "|r"
                                    elseif data.state == "success" then
                                        if value.isUsed then
                                            str = ZL.RGBAToHex(r*255, g*255, b*255, a*255) .. "拍卖成功" .. "|r，|cffffffff获胜者：|r" .. value.isUsed
                                        else
                                            str = ZL.RGBAToHex(r*255, g*255, b*255, a*255) .. "拍卖成功"
                                        end
                                    elseif data.state == "failed" then
                                        str = ZL.RGBAToHex(r*255, g*255, b*255, a*255) .. "流拍" .. "|r"
                                    end
                                    if str then
                                        self:AddLine(" ")
                                        self:AddLine("|T" .. "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga" .. ":10|t|cff3399ffAutoAuction|r")
                                        -- self:AddLine(itemGuid)
                                        self:AddLine("  " .. str)
                                        self:Show()
                                    end
                                    return
                                end
                            end
                        end
                    end
                end
            end
            itemLocation:Clear()
        end)
        --如果当前插件有激活输入框，则发送链接到输入框
        hooksecurefunc("HandleModifiedItemClick", function (itemlink)
            -- local edit = GetCurrentKeyBoardFocus()
            -- if edit then
            --     edit:Insert(itemlink)
            -- end
            -- if ZL.focusEditBox then
            --     ZL.focusEditBox:Insert(itemlink)
            -- end
        end)
        --监控WA发送状态
        hooksecurefunc(C_ChatInfo, "SendAddonMessage", function(prefix, message, chatType, target)
            local loaded, total, waName = strsplit(" ", message)
            if not (prefix == "WeakAurasProg" and waName:find("%[AutoAuction%]金团拍卖助手")) then return end
            local dashIndex = target:find("-")
            if dashIndex then
                target = target:sub(1, dashIndex - 1)
            end
            if not ZL.WaLoadStateFrame then ZL:CreateWaLoadStateFrame() end
            if not ZL.WaLoadInfo then ZL.WaLoadInfo = {} end
            if not ZL.WaLoadInfo[target] then ZL.WaLoadInfo[target] = {} end
            if not ZL.WaLoadInfo[target].index then
                ZL.WaLoadInfo[target].loadCount = 0
                for num, f in ipairs(ZL.WaLoadStateFrame.entries) do
                    if (not f.sb.playerName:GetText()) or f.sb.playerName:GetText() == "" then
                        ZL.WaLoadInfo[target].index = num
                        break
                    end
                end
                if not ZL.WaLoadInfo[target].index then
                    ZL.WaLoadInfo[target].index = #ZL.WaLoadStateFrame.entries+1
                end
            end
            local f = ZL.WaLoadStateFrame.entries[ZL.WaLoadInfo[target].index]
            local loadState
            f.btn:SetEnabled(false)
            if loaded == total then
                loadState = math.floor(loaded*100/total) .. "%(传输完成)"
                ZL.WaLoadInfo[target].loadCount = ZL.WaLoadInfo[target].loadCount + 1
                SendChatMessage("您已传输完成，请选择【导入】或【更新光环-更新】后点【加载UI】生效！", "WHISPER", nil ,target)
                f.btn:SetEnabled(true)
            else
                loadState = math.floor(loaded*100/total) .. "%(传输中)"
            end
            local r, g, b = 1, 0.82, 0
            local classFilename = UnitClassBase(target)
            if classFilename then
                r, g, b = GetClassColor(classFilename)
            end
            f:SetValues(total, loaded, r, g, b, target, loadState)
        end)
        DEFAULT_CHAT_FRAME:AddMessage(Prefix("欢迎回来  >>>" .. UnitName("player") .."<<<"))
    end
    if event == "PLAYER_LOGIN" then
        ZL:FrameUpdate()
        local tabId = ZL.opt.ZLAuctionFrameTabId
        _G["ZL_NewAuctionFrameTab0"]:Click()
        AuctionFrame:SetWidth(AuctionFrame:GetWidth()+0.5)
        C_Timer.After(0.5, function ()
            AuctionFrame:SetWidth(AuctionFrame:GetWidth()-0.5)
        end)
        _G["ZL_NewAuctionFrameTab" .. tabId]:Click()

        ZL.reloadUITime = GetServerTime()
        -- ZL.TradeRemainingReminderTime = GetServerTime() - ZL.opt.TradeRemainingReminderPinlv * 60 + 120
        if PlayerIsML() then
            ZL.mailRegOpen = true
            ZL.AuctionRecordFrame.currentIncomeFrame.mailConfirmBtn:SetText("|cff948cff邮寄登记中|r")
        end
        --检测V1.2.04之前版本物品过滤设置
        if ZL_CURRENT.filterItemId and #ZL_CURRENT.filterItemId > 0 then
            for _, data in ipairs(ZL_CURRENT.filterItemId) do
                if data["loot"] == nil then
                    data["loot"] = true
                end
                if data["auction"] == nil then
                    data["auction"] = true
                end
            end
        end
        --检测老板本数据库历史数据是否有缺少日期的，如果有缺少赋值为"1970-01-01 00:01"
        if ZL_HISTORY and #ZL_HISTORY > 0 then
            for i = #ZL_HISTORY, 1, -1 do
                if (not ZL_HISTORY[i]["auctiondate"]) then
                    ZL_HISTORY[i]["auctiondate"] = "1970-01-01 00:01"
                    -- table.remove(ZL_HISTORY, i)
                end
            end
            --删除历史数据
            if ZL.opt.autoClearHistory then
                local autoClearHistoryDiff = ZL.opt.autoClearHistoryDays * 86400 -- 天数*1天的秒数
                for i = #ZL_HISTORY, 1, -1 do
                    local startyear, startmonth, startday = ZL_HISTORY[i]["auctiondate"]:match("(%d+)-(%d+)-(%d+)")
                    local startTime = time{year=startyear, month=startmonth, day=startday, hour=0, min=0, sec=0}
                    local endyear, endmonth, endday = date("%Y-%m-%d", time()):match("(%d+)-(%d+)-(%d+)")
                    local endTime = time{year=endyear, month=endmonth, day=endday, hour=0, min=0, sec=0} -- 当前时间
                    -- 计算时间差
                    local diff = difftime(endTime, startTime)
                    if diff >= autoClearHistoryDiff then
                        table.remove(ZL_HISTORY, i)
                    end
                end
            end
        end

        --检测V1.2.10(含)之前版本ZL_SETTING["itemLevelSetting"]数据库，以适应新版的
        if ZL_SETTING["itemLevelSetting"] and #ZL_SETTING["itemLevelSetting"] > 0 then
            for index, data in ipairs(ZL_SETTING["itemLevelSetting"]) do
                if (not data.sanJianStartBid) and data.startbid then data.sanJianStartBid = data.startbid end
                if (not data.wuQiStartBid) and data.startbid then data.wuQiStartBid = data.startbid end
                if (not data.taoZhuangStartBid) and data.startbid then data.taoZhuangStartBid = data.startbid end
                ZL_SETTING["itemLevelSetting"][index].startbid = nil
            end
        end

        --检测过滤名单，强制添加拾取绑定并且没有2小时交易时间的物品为不自动拾取
        for _, data in ipairs(filterItemId) do
            local isExist = false
            if not ZL_SETTING["filterItemId"] then ZL_SETTING["filterItemId"] = {} end
            for _, _data in ipairs(ZL_SETTING["filterItemId"]) do
                if _data.itemId == data.itemId then
                    if _data.loot ~= true then _data.loot = true end
                    isExist = true
                end
            end
            if not isExist then
                table.insert(ZL_SETTING["filterItemId"], data)
            end
        end

        if ZL.opt.profanityFilter then SetCVar("profanityFilter", "0") end --关闭语言过滤器
        if ZL.opt.overrideArchive then SetCVar("overrideArchive", "0") end --反和谐
        ZL.SoundType = ZL.SoundTypeList[ZL.opt.VoiceReminderSoundType] or "甜美女声"

        -- local guid = "Vehicle-0-4516-603-13103-33288-000078057B"
        -- local unitType, _, _, _, _, npcID, spawnUID = strsplit("-", guid)
        -- print("npcID：", npcID)
        -- local npcName = GetItemInfo(194821)
        -- print(npcName)
        -- if unitType == "Creature" or unitType == "Vehicle" or unitType == "GameObject" then
        --     local spawnEpoch = GetServerTime() - (GetServerTime() % 2^23)
        --     local spawnEpochOffset = bit.band(tonumber(string.sub(spawnUID, 5), 16), 0x7fffff)
        --     local spawnIndex = bit.rshift(bit.band(tonumber(string.sub(spawnUID, 1, 5), 16), 0xffff8), 3)
        --     local spawnTime = spawnEpoch + spawnEpochOffset

        --     if spawnTime > GetServerTime() then
        --         -- This only occurs if the epoch has rolled over since a unit has spawned.
        --         spawnTime = spawnTime - ((2^23) - 1)
        --     end

        --     print(guid)
        --     print("Spawned at:", date("%Y-%m-%d %H:%M:%S", spawnTime))
        --     print("Spawn index:", spawnIndex)
        -- end
    end
    if event == "GROUP_ROSTER_UPDATE" then
        -- 函数：获取当前团队成员列表
        local function _GetCurrentRoster()
            local roster = {}
            for i = 1, MAX_RAID_MEMBERS do
                local name = GetRaidRosterInfo(i)
                if name then
                    table.insert(roster, name)
                end
            end
            return roster
        end
        -- 函数：检测是否有新成员加入
        local function CheckForNewMembers()
            local currentRoster = _GetCurrentRoster()
            if next(previousRoster, nil) then
                for _, name in ipairs(currentRoster) do
                    if (not previousRoster[name]) then
                        -- 新成员加入，发送密语
                        if (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (name ~= UnitName("player")) and ZL.opt.welcomeMessageEnable and
                            ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0) then
                            -- SendChatMessage(ZL.opt.MessageString, "WHISPER", nil, name)
                            SendChatMessage(ZL.opt.MessageString, "RAID")
                            -- TransmitAddonInfo_Pro() --同步拍卖插件全局参数
                        end
                    end
                end
            end
            -- 更新之前的团队成员列表
            previousRoster = {}
            for _, name in ipairs(currentRoster) do
                previousRoster[name] = true
            end
        end
        if IsInRaid() or IsInGroup() then
            CheckForNewMembers()
        else
            previousRoster = {}
        end
        ZL_CURRENT.MLname = ZL.GetMLname()
        AuctionFrame:Update(true)
    end
    --更换ML人员需要用到这个事件
    if event == "PARTY_LOOT_METHOD_CHANGED" then
        ZL_CURRENT.MLname = ZL.GetMLname()
        AuctionFrame:Update(true)
    end
    --如果是ML打开掉落则开始创建待拍卖窗口
    if event == "LOOT_OPENED" and PlayerIsML() and IsInInstance() and (select(2, IsInInstance()) == "raid")
        then
        local NumLootItems = GetNumLootItems()
        if NumLootItems <= 0 then return end
        if (not ZL_CURRENT.sourceGUID) then ZL_CURRENT.sourceGUID = {} end
        local sourceGUID
        for i = 1, NumLootItems do
            sourceGUID = GetLootSourceInfo(i)
            if sourceGUID then break end
        end
        if (not sourceGUID) or ZL_CURRENT.sourceGUID[sourceGUID] then
            return
        end

        if not ZL_CURRENT.sourceGUID[sourceGUID] then ZL_CURRENT.sourceGUID[sourceGUID] = {} end
        ZL_CURRENT.sourceGUID[sourceGUID].time = tostring(date("%Y-%m-%d %H:%M:%S", time()))

        local msgStr = ""
        local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality) --GetLootThreshold()获取当前团队的战利品分配阈值
        local lootMinQuality = (ZL.opt.lootMinQuality == -1 and GetLootThreshold() or ZL.opt.lootMinQuality)
        local lootList = {}
        local lootAuctionList = {}
        local candidates = {}
        local isGetCandidates = false
        --先创建完所有的记录
        for numLoot = 1, NumLootItems do
            if LootSlotIsItem(numLoot) then
                local itemlink = GetLootSlotLink(numLoot)
                local _, _, lootQuantity, _, lootQuality, _, isQuestItem = GetLootSlotInfo(numLoot)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                if (not isQuestItem) then
                    local _, auctionFilter, lootFilter = isFilterItem(itemId)
                    --拍卖
                    if lootQuality >= minQuality then
                        if (not auctionFilter) then --并且不是拍卖过滤物品则自动创建拍卖
                            lootAuctionList[itemlink] = (lootAuctionList[itemlink] or 0) + lootQuantity
                        end
                        --获取候选人
                        if (not isGetCandidates) then
                            candidates = GetMasterLootCandidates(numLoot) --获取候选人信息
                            isGetCandidates = true
                        end
                    end
                    --蓝装以上拾取通报
                    if lootQuality > 2 then
                        lootList[itemlink] = (lootList[itemlink] or 0) + lootQuantity
                     end
                    --自动拾取
                    if lootQuality >= lootMinQuality then
                        if ZL.opt.awardToML and (not lootFilter) then --掉落不是拾取过滤物品自动分配给ML
                            local candidateIndex = 1
                            local candidateName = GetMasterLootCandidate(numLoot, candidateIndex) --用于获取在团队副本中分配战利品时的候选者信息
                            while candidateName do
                                if PlayerIsML(candidateName) then --当候选人是ML时
                                    GiveMasterLoot(numLoot, candidateIndex)
                                    break
                                end
                                candidateIndex = candidateIndex + 1
                                candidateName = GetMasterLootCandidate(numLoot, candidateIndex)
                            end
                        end
                    end
                end
            end
        end

        ZL_CURRENT.sourceGUID[sourceGUID].candidates = candidates
        ZL_CURRENT.sourceGUID[sourceGUID].lootAuctionList = lootAuctionList
        -- ZL_CURRENT.sourceGUID[sourceGUID].lootList = lootList
        if ZL.opt.confirmLootAnnounce and next(lootList, nil) then  --拾取通报
            SendChatMessage("[AutoAuction]拾取通报：", "RAID")
            C_Timer.After(0.3, function ()
                for link, num in pairs(lootList) do
                    if num > 1 then
                        SendChatMessage(link .. "x" .. num, "RAID")
                    else
                        SendChatMessage(link, "RAID")
                    end
                end
            end)
        end
        --开始创建拍卖物品
        if next(lootAuctionList, nil) then
            local keyList = {}
            for key, _ in pairs(lootAuctionList) do
                table.insert(keyList, key)
            end
            local sendData = {type="拾取创建", data={}}
            for _, itemlink in ipairs(keyList) do
                --bindType 1为拾取绑定
                local _, _, _, itemLevel, _, _, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                local lootQuantity = lootAuctionList[itemlink]
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                local indexList = {}
                local itemindex = nil
                if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                    for num, data in ipairs(ZL_CURRENT.auctionlist) do
                        if (data.itemlink == itemlink) then
                            itemindex = data.itemindex
                            if (data.state ~= "success") then
                                table.insert(indexList, num) --可能因交易名单不同存在多个拍卖记录
                            end
                        end
                    end
                end
                if (not itemindex )then
                    itemindex = 1
                else
                    itemindex = itemindex + 1
                end
                local data = {}
                local index
                if #indexList > 0 then
                    for _, _index in ipairs(indexList) do
                        local fdata = ZL_CURRENT.auctionlist[_index]
                        if fdata.bindType ~= 1 then --不是拾取绑定的物品，不是拍卖成功的都可以创建到一个拍卖记录上面
                            index = _index
                            break
                        else --拾取绑定的物品
                            --如果是通过自动创建的，有sourceGUID的则判断与第一个sourceGUID交易名单差异
                            if fdata.type == "自动创建" and fdata.sourceGUID and #fdata.sourceGUID > 0 then
                                local _sourceGUID = fdata.sourceGUID[1]
                                local _candidates = ZL_CURRENT.sourceGUID[_sourceGUID].candidates
                                --判断当前的交易名单跟前面的名单对比，有几个不在前面的名单内
                                local curChaYi = 0
                                for name, _ in pairs(candidates) do
                                    --不在前面交易名单内
                                    if (not _candidates[name]) then
                                        curChaYi = curChaYi + 1
                                    end
                                end
                                --判断前面的交易名单跟现在的对比，有几个不在当前名单内并且还在团队内
                                local hisChaYi = 0
                                for name, _ in pairs(_candidates) do
                                    if (not candidates[name]) and UnitInRaid(ParseClassColorName(name)) then
                                        hisChaYi = hisChaYi + 1
                                    end
                                end
                                --如果当前的差异不大于拾取数量并且历史差异不大于历史物品数量，则合并拍卖
                                if curChaYi <= lootQuantity and hisChaYi <= fdata.itemCount then
                                    index = _index
                                    break
                                end
                            end
                        end
                    end
                end
                if index then
                    local fdata = ZL_CURRENT.auctionlist[index]
                    -- table.insert(ZL_CURRENT.auctionlist[index]["candidates"], candidates)  --暂时不能删除
                    table.insert(ZL_CURRENT.auctionlist[index]["sourceGUID"], sourceGUID)
                    ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                    if fdata.isPackage then
                        --如果是打包物品则更新[打包拍卖]数量
                        local __data, __index = ZL.FetchDataFromItemId("[打包拍卖]", 1)
                        if __index then
                            ZL_CURRENT.auctionlist[__index]["itemList"][itemlink]["itemCount"] = __data["itemList"][itemlink]["itemCount"] + lootQuantity
                            ZL.AuctionFrame2.entries[__index].MLframe.functionFrame.syncBtn:Click()
                        end
                    end
                    fdata = ZL_CURRENT.auctionlist[index]
                    if fdata.state == "auctioning" then --如果是正在拍卖中的物品，则发送消息全员更新，否则不发送消息，只更新RL的数量
                        local _, _, tarbidamount, bidCount = ZL.GetNewBidAmount(index)
                        local bidderlist = fdata.bidderlist
                        tableSort(bidderlist)
                        local hasbidamount = ""
                        local totalBidCount = 0
                        for _, bidData in ipairs(bidderlist) do
                            if totalBidCount < fdata.itemCount then
                                local count = bidData["bidCount"] or 1
                                local newTotalBidCount = totalBidCount + count
                                if newTotalBidCount > fdata.itemCount then
                                    count = fdata.itemCount - totalBidCount
                                end
                                if count  > 1 then
                                    hasbidamount = hasbidamount .. ParseClassColorName(bidData.bidder) .. "(" .. bidData.bidamount .. "x" .. count .. ")，"
                                else
                                    hasbidamount = hasbidamount .. ParseClassColorName(bidData.bidder) .. "(" .. bidData.bidamount .. ")，"
                                end
                                totalBidCount = newTotalBidCount
                            else
                                break
                            end
                        end
                        if hasbidamount == "" then
                            msgStr = ("注意：%s拍卖数量更新为：%d，当前无人出价，下次最低出价：%d，对应最大数量%d"):format(
                                fdata.itemlink, fdata.itemCount, tarbidamount, bidCount
                            )
                        else
                            msgStr = ("注意：%s拍卖数量更新为：%d，当前出价：%s下次最低出价：%d，对应最大数量%d"):format(
                                fdata.itemlink, fdata.itemCount, hasbidamount, tarbidamount, bidCount
                            )
                        end
                        SendChatMessage(msgStr, ZL.MsgChannel())
                    elseif fdata.state == "failed" then
                        --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                        C_Timer.After(20, function ()
                            local curAuctionList = ZL_CURRENT.auctionlist[index]
                            local itemGUIDList = {}
                            if curAuctionList["itemGUID"] and next(curAuctionList["itemGUID"], nil) then
                                for itemGUID, _ in pairs(curAuctionList["itemGUID"]) do
                                    table.insert(itemGUIDList, itemGUID)
                                end
                            end
                            local _index = 1
                            local function changeBag()
                                if _index <= #itemGUIDList then
                                    local itemGUID = itemGUIDList[_index]
                                    ZL.PutAuctionItemInBag(itemGUID, ZL.opt.liupaiBagId, ZL.opt.liupaiDirection)
                                    _index = _index + 1
                                    C_Timer.After(1, changeBag)
                                end
                            end
                            changeBag()
                        end)
                    end
                    -- local f = AuctionFrame.entries[index]
                    -- f:SetValues(index)
                    data = {
                        type = "数量更新",
                        data2 = ZL_CURRENT.auctionlist[index],
                    }
                else
                    local function linshi()
                        if (not ZL_CURRENT.globalConfig) or (ZL_CURRENT.globalConfig.intervalBidIncrement == nil) then
                            TransmitAddonInfo_Pro()
                            C_Timer.After(1, linshi)
                        else
                            --不存在则创建
                            local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                            if ZL_CURRENT.globalConfig.intervalBidIncrement then
                                if startbidamount < ZL_CURRENT.globalConfig.baseAmount1 then
                                    bidIncrement = bidIncrement
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount2 then
                                    bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement1, bidIncrement)
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount3 then
                                    bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement2, bidIncrement)
                                else
                                    bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement3, bidIncrement)
                                end
                            end
                            --ML自己创建，不参与插件同步创建
                            local data2 = {
                                type = "自动创建",
                                itemId = itemId,
                                itemlink = itemlink,
                                itemindex = itemindex,
                                startbidamount = startbidamount,
                                bidIncrement = bidIncrement,
                                state = "waiting",
                                lgnore = false,
                                countdownremaining = 0,
                                auctionTimerRefresh = ZL.opt.auctionTimerRefresh,
                                isPaused = false,
                                bidderlist = {},
                                itemCount = lootQuantity,
                                sourceGUID = {sourceGUID},
                                itemGUID = {},
                                Frame1IsShown = false,
                                stackCount = stackCount,
                                bindType = bindType,
                                itemLevel = itemLevel,
                                itemSubType = itemSubType,
                                createTime = date("%Y-%m-%d %H:%M:%S", time()),
                            }
                            ZL.CreateAuctionList()
                            table.insert(ZL_CURRENT.auctionlist, data2)
                            local index2 = #ZL_CURRENT.auctionlist
                            data = {
                                type = "创建拍卖",
                                data2 = ZL_CURRENT.auctionlist[index2],
                            }
                        end
                    end
                    linshi()
                end
                table.insert(sendData.data, data)
            end
            ZL.AuctionListSort(true)
            MyAddon:TransmitAddonInfo("AUTOAUC SYNC0", sendData)
        end
    end
    if event == "LOOT_CLOSED" and PlayerIsML() then
        C_Timer.After(3, ZL.GetLootItemGUID)
    end
    if (event == "CHAT_MSG_RAID") or (event == "CHAT_MSG_RAID_LEADER") or (event == "CHAT_MSG_RAID_WARNING") then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        if (strfind(msg, "YY") or strfind(msg, "yy") or strfind(msg, "歪歪")) and (not strfind(msg, "待命") and not strfind(msg, "声") and not strfind(msg, "说") and not strfind(msg, "在") and not strfind(msg, "YY:"))
        and not strfind(msg, "开") and not InCombatLockdown() and (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (sender~= UnitName("player")) and ZL.opt.welcomeMessageEnable and
        ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0)  then
            SendChatMessage(ZL.opt.MessageString, "RAID")
        end
        --监控全员信息出价
        local AuctioningCount, _index = GetAuctioningCount()
        local isFailedAuction --流拍物品重启拍卖
        local msgStr = ""
        local newBid, index
        local bidCount
        local cmsg = fullwidthToHalfwidth(msg)
        cmsg = msg_gsub(cmsg)
        if cmsg:match("^(|c........|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") or cmsg:match("^(%[打包拍卖%])(%d+%.?%d*)[gGkKwW]?$") then
            local matchStr = ""
            if cmsg:match("^(|c........|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") then
                matchStr = "(|c........|Hitem:.+|r)"
            else
                matchStr = "(%[打包拍卖%])"
            end
            local bidItemLink
            bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[wW][%*%-xX×]?(%d*)")
            if (not bidItemLink) then
                bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[kK][%*%-xX×]?(%d*)")
                if (not bidItemLink) then
                    bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.[0-9]*)[%*%-xX×]?(%d*)")
                    if (not bidItemLink) then
                        bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "(%d+)[gG]*[%*%-xX×]?(%d*)")
                        if (not bidItemLink) then
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = ("【%s】不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(sender, bidItemLink)
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                -- SendChatMessage(msgStr, "RAID")
                            end
                            newBid = nil
                        end
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 1000)
                end
            else
                newBid = math.floor(tonumber(newBid) * 10000)
            end
            if bidItemLink then
                if AuctioningCount > 0 then
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == bidItemLink) and (data.state == "auctioning") then
                                index = num
                                break
                            end
                        end
                    end
                end
                if not index then
                    if AuctioningCount > 0 then
                        --如果此物品没有正在拍卖，则判断是否为多拍模式，多拍模式下，如果是流拍物品，则启动拍卖
                        if ZL.opt.allowMultipleAuctions then
                            isFailedAuction = true
                        else
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                return
                            end
                        end
                    else
                        --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                        isFailedAuction = true
                    end
                end
                if isFailedAuction then
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                index = num
                                break
                            end
                        end
                    end
                    if not index then
                        if PlayerIsML() and ZL.opt.remindInvalidBid then
                            msgStr = bidItemLink .. "没有此流拍物品"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                        end
                    end
                end
            end
        elseif cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX]?(%d*)$") then
            if AuctioningCount == 1 then
                index = _index
                newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[wW][%*%-xX×]?([0-9]*)")  --万，检测1W，1.1w
                if (not newBid) then
                    newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[kK][%*%-xX×]?([0-9]*)")  --千，检测1k,1.1K
                    if (not newBid) then
                        newBid, bidCount = cmsg:match("([0-9]+%.[0-9]*)[%*%-xX×]?([0-9]*)") --检测1.1这种数字
                        if (not newBid) then
                            newBid, bidCount = cmsg:match("(%d+)[gG]*[%*%-xX×]?([0-9]*)") --检测不带小数点的数字，可能带有g或G
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 1000)
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 10000)
                end
            elseif AuctioningCount > 1 then
                if PlayerIsML() and ZL.opt.remindInvalidBid and ZL_CURRENT.auctionlist[_index].itemlink then
                    msgStr = "出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                    msgStr = ">>>" .. sender .. "<<<，出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                    SendChatMessage(msgStr, "RAID")
                end
                return
            else
                return
            end
        end
        if index and newBid and (tonumber(newBid) <= 10000000) then
            newBid = tonumber(newBid)
            bidCount = bidCount and tonumber(bidCount) or 1
            local fdata = ZL_CURRENT.auctionlist[index]
            if (not ZL.IsCandidate(index, sender)) then
                if PlayerIsML() then
                    msgStr = fdata.itemlink .. "不能交易给你，无法参与竞拍"
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                    msgStr = ">>>" .. sender .. "<<<".. fdata.itemlink .. "不能交易，无法参与竞拍，出价无效"
                    SendChatMessage(msgStr, "RAID")
                    return
                end
                return
            end
            if newBid == 666 then
                if PlayerIsML() then
                    msgStr = ("\"666\"为高频易混淆词，如需竞价请在后面添加一个0，如：%d0，如不竞价，忽略这条提醒"):format(newBid)
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                end
                return
            end
            local oldBid = newBid
            --将小数点替换掉
            newBid = string.gsub(tostring(newBid),"%.", "")
            newBid = tonumber(newBid)
            local Frame1 = ZL.AuctionFrame2.entries[index]
            local bidderlist = fdata.bidderlist
            local baseamount, bidIncrement, tarbidamount = ZL.GetNewBidAmount(index)
            newBid = padZeros(newBid, tarbidamount, bidIncrement, baseamount)
            if ((newBid - baseamount) % bidIncrement) or ((newBid - (baseamount - (baseamount % bidIncrement))) % bidIncrement) == 0 then --按照加价幅度整数倍出价
                if newBid >= tarbidamount then
                    if isFailedAuction then
                        if PlayerIsML() then
                            --如果存在此流拍物品则先启动拍卖，然后将出价直接添加到数据库里
                            TransmitAddonInfo_Pro()
                            local curAuctionList = ZL_CURRENT.auctionlist[index]
                            if not ZL.IsCanAuction(curAuctionList) then
                                msgStr = curAuctionList.itemlink .. "无法拍卖，原因可能是：已分解或已无法交易"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                return
                            end
                            if not ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                _G["ZL_NewAuctionFrameTab1"]:Click()
                            end
                            local f = AuctionFrame.entries[index]
                            local MLframe = f.MLframe
                            local _bidIncrement = MLframe.startbidFrame.incrementEditbox:GetNumber()
                            local startbidamount = MLframe.startbidFrame.startbidEditbox:GetNumber()
                            if ZL_CURRENT.globalConfig.intervalBidIncrement then
                                if startbidamount < ZL_CURRENT.globalConfig.baseAmount1 then
                                    _bidIncrement = _bidIncrement
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount2 then
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement1, _bidIncrement)
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount3 then
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement2, _bidIncrement)
                                else
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement3, _bidIncrement)
                                end
                            end
                            bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount
                            local bindType = curAuctionList.bindType
                            if curAuctionList.itemCount == 1 then
                                if bindType == 2 then
                                    SendChatMessage(("装绑%s开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                else
                                    if curAuctionList.itemlink == "[打包拍卖]" then
                                        local itemList = ZL_CURRENT.auctionlist[v]["itemList"]
                                        if itemList and next(itemList, nil) then
                                            SendChatMessage("打包拍卖清单：", "RAID")
                                            C_Timer.After(0.3, function ()
                                                for _itemlink, data in pairs(itemList) do
                                                    msgStr = _itemlink .. "x" .. data.itemCount
                                                    SendChatMessage(msgStr, "RAID")
                                                end
                                                C_Timer.After(0.3, function ()
                                                    SendChatMessage(("以上%s，起拍价：%d，加价幅度：%d"):format(
                                                        curAuctionList.itemlink, startbidamount, _bidIncrement), ZL.MsgChannel()
                                                    )
                                                end)
                                            end)
                                        else
                                            print(Prefix("没有打包拍卖物品，请先添加！"))
                                            return
                                        end
                                    else
                                        SendChatMessage(("%s开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                            curAuctionList.itemlink, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                        )
                                    end
                                end
                            else
                                if bindType == 2 then
                                    SendChatMessage(("装绑%sx%d，开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, curAuctionList.itemCount, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                else
                                    SendChatMessage(("%sx%d，开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, curAuctionList.itemCount, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                end
                            end
                            --如果是流拍的物品重新拍卖，检测流拍物品是否在流拍包里，如果在移动到其他包里
                            if curAuctionList.state == "failed" and ZL.opt.liupaiToggle and curAuctionList["itemGUID"] and next(curAuctionList["itemGUID"], nil) then
                                local itemList = {}
                                for key, _ in pairs(curAuctionList["itemGUID"]) do
                                    local bagID, slotIndex = ZL.FindItemInBag(key)
                                    if bagID and bagID == ZL.opt.liupaiBagId then
                                        --从第一个背包开始查询空闲的格子，如果不是流拍背包，也不是自己拍到的背包，则放进去
                                        local targetBagID, targetslotIndex
                                        for _bagID = 0, NUM_BAG_SLOTS do
                                            if _bagID ~= ZL.opt.liupaiBagId and (ZL.opt.selfToggle and _bagID ~= ZL.opt.selfBagId) then
                                                for _slotIndex = 1, C_Container.GetContainerNumSlots(_bagID) do
                                                    local currentInfo = C_Container.GetContainerItemInfo(_bagID, _slotIndex)
                                                    if not currentInfo then
                                                        targetBagID = _bagID
                                                        targetslotIndex = _slotIndex
                                                        break
                                                    end
                                                end
                                            end
                                        end
                                        if targetBagID then
                                            table.insert(itemList, {
                                                bagID = bagID, slotIndex = slotIndex,
                                                targetBagID = targetBagID, targetslotIndex = targetslotIndex,
                                            })
                                        end
                                    end
                                end
                                if #itemList > 0 then
                                    local index = 1
                                    local function linshi()
                                        if index <= #itemList then
                                            C_Container.PickupContainerItem(itemList[index]["bagID"], itemList[index]["slotIndex"])
                                            C_Container.PickupContainerItem(itemList[index]["targetBagID"], itemList[index]["targetslotIndex"])
                                            index = index + 1
                                            C_Timer.After(1, linshi)
                                        end
                                    end
                                    linshi()
                                else
                                    print(Prefix("|cffff0000注意：流拍物品重拍，但没有合适的物品从流拍背包中取出！|r"))
                                end
                            end
                            ZL_CURRENT.auctionlist[index].tradeId = nil
                            ZL_CURRENT.auctionlist[index].startbidamount = startbidamount
                            ZL_CURRENT.auctionlist[index].bidIncrement = _bidIncrement
                            ZL_CURRENT.auctionlist[index].countdownremaining = ZL.opt.auctionTimer
                            ZL_CURRENT.auctionlist[index].auctionTimerRefresh = ZL.opt.auctionTimerRefresh
                            ZL_CURRENT.auctionlist[index].state = "auctioning"
                            ZL_CURRENT.auctionlist[index].isPaused = false
                            ZL_CURRENT.auctionlist[index].bidderlist = {}
                            table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                bidder = GetClassColorName(sender),
                                bidamount = newBid,
                                bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount,
                                time = GetTime()*1000,
                            })
                            local data = {
                                type = "开始拍卖",
                                isRestart = "开始",
                                data2 = ZL_CURRENT.auctionlist[index],
                            }
                            MyAddon:TransmitAddonInfo("AUTOAUC SYNC1", data)
                        end
                    end
                    if ZL_CURRENT.auctionlist[index].countdownremaining > 0 then
                        ZL_CURRENT.auctionlist[index].countdownremaining = fdata.auctionTimerRefresh or 1800--有新的出价，重新更新倒计时
                        Frame1:SetValues(index)
                        if ZL.opt.IsVoiceReminder and ((not ZL.jiayou) or ((ZL.jiayou + 60 -GetTime()) < 0))
                        and ((newBid-tarbidamount+bidIncrement) >= 2000 or (newBid >= 10000 )) then
                            PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\老公加油.mp3", "Master")
                            ZL.jiayou = GetTime()
                        end
                        local isSenderExist = false
                        for bindex, b in ipairs(bidderlist) do
                            if ParseClassColorName(b.bidder) == sender then
                                ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidamount = newBid
                                ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidCount = bidCount
                                ZL_CURRENT.auctionlist[index].bidderlist[bindex].time = GetTime()*1000
                                isSenderExist = true
                                break
                            end
                        end
                        if (not isSenderExist) then --如不存在，则直接插入
                            table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                bidder = GetClassColorName(sender),
                                bidamount = newBid,
                                bidCount = bidCount,
                                time = GetTime()*1000,
                            })
                        end
                        tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                        local totalBidCount = 0
                        for bidindex, bidData in ipairs(bidderlist) do
                            if totalBidCount < fdata.itemCount then
                                local count = bidData["bidCount"] or 1
                                local newTotalBidCount = totalBidCount + count
                                if newTotalBidCount > fdata.itemCount then
                                    count = fdata.itemCount - totalBidCount
                                    ZL_CURRENT.auctionlist[index].bidderlist[bidindex].bidCount = count
                                    if ParseClassColorName(bidData.bidder) == sender and PlayerIsML() then
                                        SendChatMessage("已自动将您当前出价入围数量调整为：" .. count, "WHISPER", nil ,sender)
                                    end
                                end
                                totalBidCount = newTotalBidCount
                            else
                                break
                            end
                        end
                        Frame1:SetValues(index)
                        if (oldBid == 1 or oldBid == 11 or oldBid == 99) and PlayerIsML() then
                            msgStr = "插件已记录你的竞拍价:" .. newBid .. "g，如需撤销，请【私聊】我回复：撤销"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            return
                        end
                    else
                        if PlayerIsML() and ZL.opt.remindInvalidBid then
                            msgStr = fdata.itemlink .. "拍卖已结束！"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            return
                        end
                    end
                else
                    if PlayerIsML() then -- and ZL.opt.remindInvalidBid
                        msgStr = ("%s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(fdata.itemlink, tarbidamount)
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        msgStr = ("%s %s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(sender, fdata.itemlink, tarbidamount)
                        SendChatMessage(msgStr, "RAID")
                        return
                    end
                end
            else
                if PlayerIsML() then -- and ZL.opt.remindInvalidBid
                    msgStr = ">>>" .. sender .."<<<出价无效，请按加价幅度(" .. bidIncrement .. ")的整数倍出价"
                    SendChatMessage(msgStr, "RAID")
                    msgStr = "如需竞拍，请按加价幅度(" .. bidIncrement .. ")的整数倍出价，如不需要竞拍忽略这条信息"
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                    return
                end
            end
        end
    end
    if (event == "CHAT_MSG_WHISPER") and PlayerIsML() then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        local __name = GetClassColorName(sender)
        if msg == "邮寄" then
            if PlayerIsML(sender) then return end
            if (not ZL.mailRegOpen) then
                SendChatMessage("登记邮寄工资窗口已关闭，暂时不接受登记！", "WHISPER", nil, sender)
                return
            end
            if (not ZL_CURRENT["mailPlayers"]) then ZL_CURRENT["mailPlayers"] = {} end
            if (ZL_CURRENT["mailPlayers"][__name] == nil) then
                ZL_CURRENT["mailPlayers"][__name] = false
            end
            SendChatMessage("插件已登记邮寄工资，不可撤销！", "WHISPER", nil, sender)
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            local senderIndex = nil
            local subgroup = nil
            for i = 1, MAX_RAID_MEMBERS do
                local name, _, _subgroup = GetRaidRosterInfo(i)
                if name == sender then
                    senderIndex = i
                    subgroup = _subgroup
                    break
                end
            end
            if senderIndex and (not InCombatLockdown()) and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then
                local mailPlayerList = {__name}
                ZL.ChangePlayerGroup(mailPlayerList)
            end
        elseif msg == "撤销" then
            local num, index = GetAuctioningCount()
            if num == 1 then
                local itemId = ZL_CURRENT.auctionlist[index].itemId
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemId=itemId, itemindex=itemindex, playerName=__name})
            else
                if PlayerIsML() then
                    SendChatMessage("当前存在多个拍卖物品，无法撤销出价！", "WHISPER", nil, sender)
                end
            end
        end
    end
    local function Trade_UpdateMoney()
        if PlayerIsML() then
            ZL.tradeMoneyML = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyOther = GetTargetTradeMoney() / 10000
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradeMoneyOther = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyML = GetTargetTradeMoney() / 10000
        end
    end
    local function Trade_UpdateItemInfo(id)
        local itemLink
        if PlayerIsML() then
            itemLink = GetTradePlayerItemLink(id)
        elseif PlayerIsML(GetUnitName("npc", false)) then
            itemLink = GetTradeTargetItemLink(id)
        end
        if itemLink then
            -- local itemId = tonumber(string.match(itemLink, "|c........|Hitem:(%d+):"))
            ZL.MLTradeItems[id] = itemLink
        end
    end
    if (event == "TRADE_CLOSED") then
		ZL.isTrading = false
        ZL.AuctionRecordFrame:Hide()
        ZL.ShowAuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
	end
	if (event == "TRADE_SHOW") then
		ZL.isTrading = true
		ZL.tradeMoneyML = 0
		ZL.tradeMoneyOther = 0
        ZL.MLTradeItems = {}
        local function PickupContainerItemToTrade2(itemGUID)
            local bag, slot = ZL.FindItemInBag(itemGUID)
            if bag then
                local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                local isLocked = GetContainerItemInfo["isLocked"]
                local isBound = GetContainerItemInfo["isBound"]
                if (not isLocked) then
                    local isCanTrade = false
                    if isBound then
                        --如果已绑定，检测是否还有剩余交易时间
                        if (not ZL.ToolTip) then
                            ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                        end
                        ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                        ZL.ToolTip:ClearLines()
                        ZL.ToolTip:SetBagItem(bag, slot)
                        for i = 1, ZL.ToolTip:NumLines() do
                            local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                            if text then
                                local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                if timeRemaining then
                                    isCanTrade = true
                                    break
                                end
                            end
                        end
                    else
                        isCanTrade = true
                    end
                    if isCanTrade then
                        C_Container.PickupContainerItem(bag, slot)
                        for i = 1, 6 do
                            local name = GetTradePlayerItemInfo(i)
                            if (not name) then
                                ClickTradeButton(i)
                                break
                            end
                        end
                    end
                end
            end
        end
        local function PickupContainerItemToTrade(itemGUID, ibag, islot)
            C_Container.PickupContainerItem(ibag, islot)
            for i = 1, 6 do
                local name = GetTradePlayerItemInfo(i)
                if (not name) then
                    ClickTradeButton(i)
                    break
                end
            end
        end
        if PlayerIsML() then
            ZL.tradePartner = GetClassColorName((GetUnitName("npc", true)))
            local playerBuyList = ZL.GetPlayerBuyList()
            local tradeList = {}
            local splitList = {}
            if playerBuyList[ZL.tradePartner] then
                local balanceAmount = 0
                local playerPayToMLamount = 0
                if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                    playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                end
                balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                if balanceAmount < 0 then
                    SendChatMessage("总共请支付：".. -balanceAmount .. "g", "WHISPER", nil, ParseClassColorName(ZL.tradePartner))
                end
                if playerBuyList[ZL.tradePartner]["items"] and #playerBuyList[ZL.tradePartner]["items"] > 0 then
                    ClearCursor()
                    for _, data in ipairs(playerBuyList[ZL.tradePartner]["items"]) do
                        -- local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                        if (not data.isTraded) and data.itemGUID and #data.itemGUID > 0 then
                            local tradeCount = 0
                            for _, itemGUID in ipairs(data.itemGUID) do
                                if not tradeList[itemGUID] then
                                    local bag, slot = ZL.FindItemInBag(itemGUID)
                                    if bag then
                                        local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                                        local isLocked = GetContainerItemInfo["isLocked"]
                                        local isBound = GetContainerItemInfo["isBound"]
                                        local stackCount = GetContainerItemInfo["stackCount"]
                                        if not isLocked then
                                            local isCanTrade
                                            if isBound then
                                                --如果已绑定，检测是否还有剩余交易时间
                                                if (not ZL.ToolTip) then
                                                    ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                                                end
                                                ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                                                ZL.ToolTip:ClearLines()
                                                ZL.ToolTip:SetBagItem(bag, slot)
                                                for i = 1, ZL.ToolTip:NumLines() do
                                                    local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                                                    if text then
                                                        local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                                        if timeRemaining then
                                                            isCanTrade = true
                                                            break
                                                        end
                                                    end
                                                end
                                            else
                                                isCanTrade = true
                                            end
                                            if isCanTrade and tradeCount < data.itemCount then
                                                local splitCount = stackCount - (data.itemCount - tradeCount)
                                                tradeCount = tradeCount + stackCount
                                                tradeList[itemGUID] = {bag=bag, slot=slot}
                                                if splitCount > 0 then
                                                    splitList[itemGUID] = {
                                                        splitCount = splitCount,
                                                        bag = bag,
                                                        slot = slot,
                                                    }
                                                end
                                                if tradeCount >= data.itemCount then
                                                    break
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
                local function trade()
                    if next(tradeList, nil) then
                        local tempList = {}
                        for itemGUID, _ in pairs(tradeList) do
                            table.insert(tempList, itemGUID)
                        end
                        local index = 1
                        local function linshi()
                            if index <= #tempList then
                                local itemGUID = tempList[index]
                                PickupContainerItemToTrade(itemGUID, tradeList[itemGUID].bag, tradeList[itemGUID].slot)
                                index = index + 1
                                C_Timer.After(0.3, linshi)
                            end
                        end
                        linshi()
                    end
                end
                if next(splitList, nil) then
                    local tempList = {}
                    for itemGUID, data in pairs(splitList) do
                        table.insert(tempList, itemGUID)
                    end
                    local index = 1
                    local function split_linshi()
                        if index <= #tempList then
                            local itemGUID = tempList[index]
                            local isfull = true
                            for tarBagID = 0, NUM_BAG_SLOTS do
                                for tarSlotIndex = 1, C_Container.GetContainerNumSlots(tarBagID) do
                                    local currentInfo = C_Container.GetContainerItemInfo(tarBagID, tarSlotIndex)
                                    if not currentInfo then
                                        C_Container.SplitContainerItem(splitList[itemGUID].bag, splitList[itemGUID].slot, splitList[itemGUID].splitCount)
                                        C_Container.PickupContainerItem(tarBagID, tarSlotIndex)
                                        isfull = false
                                        break
                                    end
                                end
                            end
                            if isfull then
                                print(Prefix("注意！注意！背包已满，无法分成目标小堆数量！已移除交易清单"))
                                tradeList[itemGUID] = nil
                            end
                            if index == #tempList then
                                C_Timer.After(1, trade)
                            end
                            index = index + 1
                            C_Timer.After(1, split_linshi)
                        end
                    end
                    split_linshi()
                else
                    trade()
                end
            end
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradePartner = GetClassColorName((GetUnitName("player", true)))
        else
            ZL.tradePartner = nil
        end
        if PlayerIsML() then
            ZL.ShowAuctionRecordFrame:Show()
            ZL.ShowAuctionRecordFrame:ClearAllPoints()
            ZL.ShowAuctionRecordFrame:SetPoint("BOTTOMRIGHT", _G["TradeFrame"], "TOPRIGHT", 20, 0)
            if ZL.opt.ShowAuctionRecordFrameCheckButtonValue then
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["TradeFrame"], "TOPRIGHT")
            end
        end
	end
    if (event == "TRADE_ACCEPT_UPDATE") and ZL.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	end
    if (event == "TRADE_PLAYER_ITEM_CHANGED") then -- and ZL.tradePartner
        Trade_UpdateItemInfo(arg[1])
	end
    if (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	end
	if (event == "TRADE_MONEY_CHANGED") and ZL.tradePartner then
        Trade_UpdateMoney()
	end
    if (event == "UI_INFO_MESSAGE") and PlayerIsML() then
        if arg[2] == ERR_TRADE_COMPLETE and ZL.tradePartner and ZL_CURRENT["IncomeList"] then
            for _, itemlink in ipairs(ZL.MLTradeItems) do
                for index, data in ipairs(ZL_CURRENT["IncomeList"]) do
                    local isTrue
                    if data.itemList and next(data.itemList, nil) then
                        for _itemlink, _data in pairs(data.itemList) do
                            if (not _data.isTraded) and itemlink == _itemlink and data.player == ZL.tradePartner then
                                ZL_CURRENT["IncomeList"][index]["itemList"][itemlink]["isTraded"] = true
                                isTrue = true
                                break
                            end
                        end
                    end
                    if isTrue then break end
                end
            end
            --下面为新增数据库
            if ZL.tradeMoneyOther > 0 then
                if not ZL_CURRENT.playerPayToML then ZL_CURRENT.playerPayToML = {} end
                local oldPayToML = ZL_CURRENT.playerPayToML[ZL.tradePartner] and ZL_CURRENT.playerPayToML[ZL.tradePartner] or 0
                ZL_CURRENT.playerPayToML[ZL.tradePartner] = oldPayToML + ZL.tradeMoneyOther
                ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            end
            ZL.tradePartner = nil
        elseif arg[2] == ERR_MAIL_SENT and ZL.Recipient then --"邮件已发出。"
            ZL.ScrollingMessageFrame:AddMessage("【" .. ZL.Recipient .. "】邮件发送成功！", 1.0, 1.0, 1.0)
            ZL_CURRENT["mailPlayers"][ZL.Recipient] = true
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            ZL.Recipient = nil
		end
	end
    if (event == "UI_ERROR_MESSAGE") and PlayerIsML() then
        --"找不到收件人。" "收件人现在无法收到邮件。" "内部邮件数据库错误" 
        if arg[2] == ERR_MAIL_TARGET_NOT_FOUND or arg[2] == ERR_MAIL_RECEPIENT_CANT_RECEIVE_MAIL or arg[2] == ERR_MAIL_DATABASE_ERROR then
            ZL.Recipient = nil
        elseif arg[2] == ERR_MAIL_REACHED_CAP then --"你已经达到了收取邮件的数量上限"
            ZL.Recipient = nil
            ZL.ScrollingMessageFrame:AddMessage("你已经达到了发送邮件数量上限，已停止邮寄，请过一段时间后重试！", 1, 0, 0)
            ZL.StopSendMail = true
        end
    end
    if (event == "MAIL_CLOSED") and PlayerIsML() then
        ZL.Recipient = nil
    end
    if (event == "MAIL_SHOW") and PlayerIsML() and ZL.GetNeedMailNums() > 0  then
        ZL.Recipient = nil
        local function linshi()
            if (not _G["MailFrame"]) or (not _G["MailFrame"]:IsShown()) then
                C_Timer.After(0.3, linshi)
            else
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["MailFrame"], "TOPRIGHT")
            end
        end
        linshi()
    end
    -- if (event == "MAIL_INBOX_UPDATE") and PlayerIsML() and ZL.GetNeedMailNums() > 0 then

    -- end
    if (event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE") and (arg[1] == Enum.PlayerInteractionType.MailInfo) and PlayerIsML() then
        ZL.AuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
    end
    if (event == "PLAYER_ENTERING_WORLD") then
        -- ZL_CURRENT.MLname = ZL.GetMLname()
        --切换地图的时候才触发
        TransmitAddonInfo_Pro()
        if (not arg[1]) and (not arg[2]) then
            local inInstance, instanceType = IsInInstance()
            if inInstance and instanceType == "raid" then
                self:RegisterEvent("UPDATE_INSTANCE_INFO") --当RequestRaidInfo()请求可用时触发
                RequestRaidInfo()
            end
        end
        C_Timer.After(3, function ()
            -- local _, msgStr = CheckWaVersion("[AutoAuction]金团拍卖助手")
            -- if msgStr then
            --     print(ZL.Prefix(msgStr))
            --     ZL.ScrollingMessageFrame:AddMessage(msgStr)
            -- end
            --获取交易剩余时间定时器
            if not ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(2, function ()
                    ZL.GetRemainingTradeTime()
                end)
            end
            --刷新背包物品颜色
            -- if not ZL.UpdateBagHighLight then
            --     ZL.UpdateBagHighLight = C_Timer.NewTicker(2, function ()
            --         ZL.BagHighLight()
            --     end)
            -- end
            --获取ItemGUID定时器
            -- ZL.UpdateGetLootItemGUID =  C_Timer.NewTicker(2, function ()
            --     ZL.GetLootItemGUID()
            -- end)
            -- 加载窗口定时器
            if not ZL.UpdateReloadUI then
                ZL.UpdateReloadUI = C_Timer.NewTicker(1, function ()
                    if not PlayerIsML() then return end
                    ZL.reloadUITimerJump = (ZL.reloadUITimerJump or 0) + 1
                    if (not InCombatLockdown()) and ZL.opt.isReloadUI and IsInInstance() and (select(2, IsInInstance()) == "raid")
                    and (((ZL.opt.reloadUITimerJump or 600) - ZL.reloadUITimerJump) < 0) then
                        ZL.reloadUITimerJump = 0
                        if not ZL.ReloadUIFrame then ZL:CreateReloadUIFrame() end
                        ZL.ReloadUIFrame:Show()
                        if not ZL_CURRENT.ReloadUIFrame then ZL_CURRENT.ReloadUIFrame = {} end ---测试用
                        table.insert(ZL_CURRENT.ReloadUIFrame, date("%Y-%m-%d %H:%M:%S", time()))
                        PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\保存数据.mp3", "Master")
                        C_Timer.After(5, function ()
                            ZL.ReloadUIFrame:Hide()
                        end)
                        if ZL.opt.isSYNCAll and ZL.AuctionFrame2.MLFrame.syncAllBtn:IsEnabled() and GetAuctioningCount() == 0 then
                            ZL.AuctionFrame2.MLFrame.syncAllBtn:Click()
                        end
                    end
                end)
            end
        end)
        --请求同步数据
        if arg[1] or arg[2] then
            local delay = 3
            if arg[1] then
                delay = 6
            end
            C_Timer.After(delay, function ()
                if (not PlayerIsML()) and (UnitName("player") ~= ZL_CURRENT.MLname) and IsInRaid() then
                    local msgStr = "已发送同步拍卖数据请求，等待回应..."
                    print(Prefix(msgStr))
                    ZL.ScrollingMessageFrame:AddMessage(msgStr)
                    MyAddon:TransmitAddonInfo2("AUTOAUC REQ", "同步拍卖数据", "WHISPER", GetMLname())
                end
            end)
        end
    end
    if (event == "UPDATE_INSTANCE_INFO") then
        local instanceName, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
        local newCD = true
        for i = 1, GetNumSavedInstances() do
            local _, _, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
            if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                newCD = false
                break
            end
        end
        if newCD then --and ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) and (ZL_CURRENT.instanceID ~= instanceID) and (ZL_CURRENT.difficultyID ~= difficultyID) 
            local msgStr = "已进入一个全新副本【|cffffd100" .. instanceName .. "|r】，请确认是否重置当前拍卖数据？"
            StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
        else
            local todayDate = date("%Y-%m-%d", time())
            if ZL_CURRENT.auctiondate and (((ZL_CURRENT.auctiondate):match("^(.-)%s")) ~= todayDate) then
                local msgStr = "已进入【|cffffd100" .. instanceName .. "|r】副本，当前副本已存在|cffffd100" .. ZL_CURRENT.auctiondate .. "|r拍卖记录，请确认是否重置这个拍卖数据？"
                StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
            end
        end
        self:UnregisterEvent("UPDATE_INSTANCE_INFO")
    end
    if (event == "BAG_UPDATE_DELAYED") then
        if ZL.opt.waitingBagHighLight or ZL.opt.auctioningBagHighLight or ZL.opt.successBagHighLight
        or ZL.opt.failedBagHighLight or ZL.opt.lgnoreBagHighLight then
            ZL.BagHighLight()
        end
    end
    if (event == "BAG_OPEN") then
        ZL.BagHighLight()
    end
    if (event == "PLAYER_REGEN_ENABLED") then
        if ZL.opt.ZLAuctionFrameIsShown then
            ZL.AuctionFrame2:Show()
        end
        if ZL.opt.remainingTradeTimeBtnValue then
            ZL.ZLRemainingTradeTimeFrame:Show()
        end
        if ZL.opt.ItemSettingFrameIsShown then
            ZL.ItemSettingFrame:Show()
        end
        if ZL.opt.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Show()
        end
        if ZL.opt.SettingFrameIsShown then
            ZL.OpenAceConfigDialog("金团拍卖助手")
        end
    end
    if (event == "PLAYER_REGEN_DISABLED") then
        --进入战斗，隐藏窗口
        if ZL.opt.AuctionFrameHide then
            ZL.AuctionFrame2:Hide()
        end
        if ZL.opt.RemainingTradeTimeFrameHide then
            ZL.ZLRemainingTradeTimeFrame:Hide()
        end
        if ZL.opt.ItemSettingFrameHide then
            ZL.ItemSettingFrame:Hide()
        end
        if ZL.opt.AuctionRecordFrameHide then
            ZL.AuctionRecordFrame:Hide()
        end
        if ZL.opt.SettingFrameHide then
            if LibStub("AceConfigDialog-3.0").OpenFrames["金团拍卖助手"] then
                ZL.opt.SettingFrameIsShown = true
                LibStub("AceConfigDialog-3.0"):Close("金团拍卖助手")
            else
                ZL.opt.SettingFrameIsShown = false
            end
        end
    end
    if (event == "CHAT_MSG_ADDON") then
        if arg[1] == "WeakAuras" then
            local Compresser = LibStub:GetLibrary("LibCompress")
            local LibDeflate = LibStub:GetLibrary("LibDeflate")
            local Serializer = LibStub:GetLibrary("AceSerializer-3.0")
            local LibSerialize = LibStub("LibSerialize")
            local decodeB64Table = {}
            local string_char = string.char
            local bit_band, bit_lshift, bit_rshift = bit.band, bit.lshift, bit.rshift
            local B64tobyte = {
                a =  0,  b =  1,  c =  2,  d =  3,  e =  4,  f =  5,  g =  6,  h =  7,
                i =  8,  j =  9,  k = 10,  l = 11,  m = 12,  n = 13,  o = 14,  p = 15,
                q = 16,  r = 17,  s = 18,  t = 19,  u = 20,  v = 21,  w = 22,  x = 23,
                y = 24,  z = 25,  A = 26,  B = 27,  C = 28,  D = 29,  E = 30,  F = 31,
                G = 32,  H = 33,  I = 34,  J = 35,  K = 36,  L = 37,  M = 38,  N = 39,
                O = 40,  P = 41,  Q = 42,  R = 43,  S = 44,  T = 45,  U = 46,  V = 47,
                W = 48,  X = 49,  Y = 50,  Z = 51,["0"]=52,["1"]=53,["2"]=54,["3"]=55,
                ["4"]=56,["5"]=57,["6"]=58,["7"]=59,["8"]=60,["9"]=61,["("]=62,[")"]=63
            }
            local bytetoB64 = {
                [0]="a","b","c","d","e","f","g","h",
                "i","j","k","l","m","n","o","p",
                "q","r","s","t","u","v","w","x",
                "y","z","A","B","C","D","E","F",
                "G","H","I","J","K","L","M","N",
                "O","P","Q","R","S","T","U","V",
                "W","X","Y","Z","0","1","2","3",
                "4","5","6","7","8","9","(",")"
            }
            local function decodeB64(str)
                local bit8 = decodeB64Table;
                local decoded_size = 0;
                local ch;
                local i = 1;
                local bitfield_len = 0;
                local bitfield = 0;
                local l = #str;
                while true do
                  if bitfield_len >= 8 then
                    decoded_size = decoded_size + 1;
                    bit8[decoded_size] = string_char(bit_band(bitfield, 255));
                    bitfield = bit_rshift(bitfield, 8);
                    bitfield_len = bitfield_len - 8;
                  end
                  ch = B64tobyte[str:sub(i, i)];
                  bitfield = bitfield + bit_lshift(ch or 0, bitfield_len);
                  bitfield_len = bitfield_len + 6;
                  if i > l then
                    break;
                  end
                  i = i + 1;
                end
                return table.concat(bit8, "", 1, decoded_size)
            end
            local function StringToTable(inString, fromChat)
                local _, _, encodeVersion, encoded = inString:find("^(!WA:%d+!)(.+)$")
                if encodeVersion then
                  encodeVersion = tonumber(encodeVersion:match("%d+"))
                else
                  encoded, encodeVersion = inString:gsub("^%!", "")
                end

                local decoded
                if(fromChat) then
                  if encodeVersion > 0 then
                    decoded = LibDeflate:DecodeForPrint(encoded)
                  else
                    decoded = decodeB64(encoded)
                  end
                else
                  decoded = LibDeflate:DecodeForWoWAddonChannel(encoded)
                end
              
                if not decoded then
                  return "解码错误"
                end
              
                local decompressed
                if encodeVersion > 0 then
                  decompressed = LibDeflate:DecompressDeflate(decoded)
                  if not(decompressed) then
                    return "错误"
                  end
                else
                  -- We ignore the error message, since it's more likely not a weakaura.
                  decompressed = Compresser:Decompress(decoded)
                  if not(decompressed) then
                    return "错误"
                  end
                end
              
              
                local success, deserialized
                if encodeVersion < 2 then
                  success, deserialized = Serializer:Deserialize(decompressed)
                else
                  success, deserialized = LibSerialize:Deserialize(decompressed)
                end
                if not(success) then
                  return "错误"
                end
                return deserialized
            end
            local compressedTablesCache = {}
            local configForLS = {
                errorOnUnserializableType =  false
            }
            local configForDeflate = {level = 4} --压缩的级别，控制压缩的速度与压缩率之间的平衡。数值越高，压缩的效果越好，但速度可能较慢；数值越低，压缩速度更快，但压缩效果较差。如果不指定，库通常使用默认值（通常是 6）
            local function TableToString(inTable, forChat)
                local serialized = LibSerialize:SerializeEx(configForLS, inTable)
                local compressed
                -- get from / add to cache
                if compressedTablesCache[serialized] then
                    compressed = compressedTablesCache[serialized].compressed
                    compressedTablesCache[serialized].lastAccess = time()
                else
                    compressed = LibDeflate:CompressDeflate(serialized, configForDeflate)
                    compressedTablesCache[serialized] = {
                        compressed = compressed,
                        lastAccess = time(),
                    }
                end
                -- -- remove cache items after 5 minutes
                -- for k, v in pairs(compressedTablesCache) do
                --     if v.lastAccess < (time() - 300) then
                --         compressedTablesCache[k] = nil
                --     end
                -- end
                local encoded = "!WA:2!"
                if (forChat) then
                    encoded = encoded .. LibDeflate:EncodeForPrint(compressed)
                else
                    encoded = encoded .. LibDeflate:EncodeForWoWAddonChannel(compressed)
                end
                return encoded
            end
            local function stripNonTransmissableFields(datum, fieldMap)
                for k, v in pairs(fieldMap) do
                  if type(v) == "table" and type(datum[k]) == "table" then
                    stripNonTransmissableFields(datum[k], v)
                  elseif v == true then
                    datum[k] = nil
                  end
                end
            end
            local function CompressDisplay(data, version)
                -- 清理未使用的自定义触发器字段
                -- 这些字段可能包含大量不必要的数据。
                -- 我们还会对任何自定义代码发出警告，因此删除不必要的自定义代码可以防止不必要的警告。
                for triggernum, triggerData in ipairs(data.triggers) do
                    local trigger, untrigger = triggerData.trigger, triggerData.untrigger
              
                    if (trigger and trigger.type ~= "custom") then
                        trigger.custom = nil;
                        trigger.customDuration = nil;
                        trigger.customName = nil;
                        trigger.customIcon = nil;
                        trigger.customTexture = nil;
                        trigger.customStacks = nil;
                        if (untrigger) then
                            untrigger.custom = nil;
                        end
                    end
                end
                local copiedData = CopyTable(data)
                local non_transmissable_fields = {
                    controlledChildren = true,
                    parent = true,
                    authorMode = true,
                    skipWagoUpdate = true,
                    ignoreWagoUpdate = true,
                    preferToUpdate = true,
                    information = {
                        saved = true
                    }
                }
                stripNonTransmissableFields(copiedData, non_transmissable_fields)
                copiedData.tocversion = select(4, GetBuildInfo())
                return copiedData;
            end
            local received = StringToTable(arg[2])
            if(received and type(received) == "table" and received.m == "dR" and received.d ~= "") then
                local _, _, dataID, ver = (received.d):find("^(%[AutoAuction%]金团拍卖助手) V(%d+%.%d+%.%d+)")
                if (not dataID) or (not ver) then return end
                local data
                if _G["WeakAurasSaved"] then
                    data = _G["WeakAurasSaved"].displays["[AutoAuction]金团拍卖助手"]
                end
                if data then
                    local sender = pruneCrossRealm(arg[4])
                    if not ZL.WaLoadInfo then ZL.WaLoadInfo = {} end
                    if not ZL.WaLoadInfo[sender] then ZL.WaLoadInfo[sender] = {} ZL.WaLoadInfo[sender].loadCount = 0 end
                    if ZL.WaLoadInfo[sender].request then
                        local msgStr
                        if ZL.WaLoadInfo[sender].loadCount > 0 then
                            msgStr = "你已传输完成，如未及时导入，请回复：重置，可以申请重新传输！"
                        else
                            msgStr = "你已提交传输请求，请勿重复提交，不用管提示是否连接成功！"
                        end
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        return
                    end
                    local function GenerateUniqueID()
                        -- generates a unique random 11 digit number in base64
                        local s = {}
                        for i=1,11 do
                          tinsert(s, bytetoB64[math.random(0, 63)])
                        end
                        return table.concat(s)
                    end
                    local GetAddOnMetadata = C_AddOns and C_AddOns.GetAddOnMetadata or GetAddOnMetadata
                    local function DisplayToString(id, forChat)
                        data.uid = data.uid or GenerateUniqueID()
                        local version = 1421
                        local transmitData = CompressDisplay(data, version)
                        local transmit = {
                            m = "d",
                            d = transmitData,
                            v = version,
                            s = GetAddOnMetadata("WeakAuras", "Version")
                        }
                        return TableToString(transmit, forChat);
                    end
                    local function TransmitDisplay(id, characterName)
                        local Comm = LibStub:GetLibrary("AceComm-3.0")
                        local encoded = DisplayToString(id);
                        if(encoded ~= "") then
                            ZL.WaLoadInfo[sender].request = true
                            Comm:SendCommMessage("WeakAuras", encoded, "WHISPER", characterName, "BULK", function(displayName, done, total)
                                Comm:SendCommMessage("WeakAurasProg", done.." "..total.." "..displayName, "WHISPER", characterName, "ALERT");
                            end, id)
                        end
                    end
                    TransmitDisplay(received.d, arg[4])
                end
            end
        end
    end
    -- if (event == "ENCOUNTER_END") then
    --     print(arg[1], arg[2], arg[3], arg[4], arg[5])
    -- end
    -- if (event == "BOSS_KILL") then
    --     print(arg[1], arg[2])
    -- end
    arg:Release()
end

ZL:RegisterEvent("ADDON_LOADED")
ZL:RegisterEvent("PLAYER_LOGIN")
ZL:SetScript("OnEvent", mainInit)
--注册事件

fZL:RegisterEvent("PLAYER_ENTERING_WORLD")  --IsInInstance函数在 PLAYER_ENTERING_WORLD 后立即返回正确的结果
fZL:RegisterEvent("PLAYER_REGEN_ENABLED") --离开战斗
fZL:RegisterEvent("PLAYER_REGEN_DISABLED") -- 进入战斗
fZL:RegisterEvent("CHAT_MSG_RAID")
fZL:RegisterEvent("CHAT_MSG_RAID_LEADER")
fZL:RegisterEvent("CHAT_MSG_RAID_WARNING")
fZL:RegisterEvent("CHAT_MSG_WHISPER")
fZL:RegisterEvent("CHAT_MSG_ADDON")
fZL:RegisterEvent("LOOT_OPENED")
fZL:RegisterEvent("LOOT_CLOSED")
fZL:RegisterEvent("LOOT_READY")
fZL:RegisterEvent("GROUP_ROSTER_UPDATE")
fZL:RegisterEvent("PARTY_LEADER_CHANGED")
fZL:RegisterEvent("PARTY_LOOT_METHOD_CHANGED")
fZL:RegisterEvent("UNIT_NAME_UPDATE")
fZL:RegisterEvent("TRADE_MONEY_CHANGED")
fZL:RegisterEvent("UI_INFO_MESSAGE")
fZL:RegisterEvent("UI_ERROR_MESSAGE")
fZL:RegisterEvent("TRADE_CLOSED")
fZL:RegisterEvent("TRADE_SHOW")
fZL:RegisterEvent("TRADE_ACCEPT_UPDATE")
fZL:RegisterEvent("PLAYER_TRADE_MONEY")
fZL:RegisterEvent("MAIL_SHOW")
fZL:RegisterEvent("MAIL_CLOSED")
fZL:RegisterEvent("MAIL_INBOX_UPDATE")
fZL:RegisterEvent("PLAYER_INTERACTION_MANAGER_FRAME_HIDE") --关闭邮箱触发这个事件
fZL:RegisterEvent("BAG_UPDATE_DELAYED")
fZL:RegisterEvent("BAG_UPDATE")
fZL:RegisterEvent("BAG_OPEN")
fZL:RegisterEvent("CHAT_MSG_LOOT")
fZL:RegisterEvent("ENCOUNTER_START")
fZL:RegisterEvent("ENCOUNTER_END")
fZL:RegisterEvent("BOSS_KILL")

fZL:SetScript("OnEvent", mainInit)
