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 GetWeekDay = ZL.GetWeekDay
local InportToStatistics = ZL.InportToStatistics
local RGBAToHex = ZL.RGBAToHex
local GetDiffTime = ZL.GetDiffTime
local cGetItemInfo = C_Item and C_Item.GetItemInfo or GetItemInfo
local cGetItemIcon = C_Item and C_Item.GetItemIconByID or GetItemIcon
local GetLootMethod = C_PartyInfo and C_PartyInfo.GetLootMethod or GetLootMethod
local PickupContainerItem = C_Container and C_Container.PickupContainerItem or PickupContainerItem
local goldText = "|A:auctionhouse-icon-coin-gold:0:0|a"
local MyAddon = ZL.MyAddon

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 = 5,
		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 = false,
        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,
        autoClearHistoryDays = 1,
        autoClearHistoryIncomeDays = 3,
        showIncomeDays = 3,
        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,
        auctionStateTip = true,
        historyMaxAndMin = true,
        historyTrendChart = true,
        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,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        YYSound = false,
        ZLRolesOverViewFrameScale = 1,
        auctionMode = "团队",
        autoPackage = true,
        quickBidIncrement = 100,
        rollCountDown = 30,
        minIconReloadUI = true,
        popupPriceDelta = 500,
        popupPrice = 500,
        subsidyProfileSelect = 1,
        wagesSubsidyType = 2,
        autoShowAuctionFrame = false,
        autoNoticeFoodInRaid = true,
		ZLTaskFrameScale = 1,
		raidChannel = true,
		whisperChannel = true,
		taskSelectValue = 1,
        DROrderSelect = 1,
        msgChannelTeam = true,
        msgChannelWorld = true,
        whisperLastMinute = 5,
        whisperMessageNumbers = 20,
        taiTanSuiPianCurrency = true,
        AuctionSortLock = true,
  	},
    global = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 5,
		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 = false,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        ZLRolesOverViewFrameScale = 1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistoryDays = 1,
        autoClearHistoryIncomeDays = 3,
        showIncomeDays = 3,
        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,
        auctionStateTip = true,
        historyMaxAndMin = true,
        historyTrendChart = true,
        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,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        realmName = true,
        unitLevel = true,
        itemLevel = true,
        TOC25 = true,
        TOC10 = true,
        OL25 = true,
        OL10 = true,
        ULD25 = true,
        ULD10 = true,
        VOA25 = true,
        VOA10 = true,
        weekQuest = true,
        heroDayQuest = true,
        taiTanDayQuest = true,
        kaiXuanCurrency = true,
        yingXiongCurrency = true,
        rongYuCurrency = true,
        jinBiCurrency = true,
        RolesOverViewFrameHide = true,
        YYSound = false,
        rollCountDown = 30,
	},
}
function ZL:OnProfileEnable()
	ZL.opt = ZL.db.profile
    ZL.glb = ZL.db.global
    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]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:18563::::::::80:::::::::|h[逐风者禁锢徽记]|h|r",
        ["itemId"] = 18563,
    }, -- [5]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:18564::::::::80:::::::::|h[逐风者禁锢徽记]|h|r",
        ["itemId"] = 18564,
    }, -- [6]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffa335ee|Hitem:50231::::::::80:::::::::|h[腐面的酸性血液]|h|r",
        ["itemId"] = 50231,
    }, -- [7]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffa335ee|Hitem:50226::::::::80:::::::::|h[烂肠的酸性血液]|h|r",
        ["itemId"] = 50226,
    }, -- [8]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cff1eff00|Hitem:52019::::::::80:::::::::|h[小宝的丝带]|h|r",
        ["itemId"] = 52019,
    }, --[9]
}

local function filterFunc(self, event, text, player, l, cs, t, flag, channelId, channelIndex, channelBaseName, ...)
    if (not ZL.addonVersion) or flag == "GM" or flag == "DEV" then --or (event == "CHAT_MSG_CHANNEL" and type(channelId) == "number" and channelId > 0)
        return false, text, player, l, cs, t, flag, channelId, channelIndex, channelBaseName, ...
    end
    if text:find("^(安装AutoAuction插件后可查看账单总览和对账单)$") or text:find("^(安装AutoAuction插件后可查看账单总览)$") then
        text = format("|cffffff00|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "账单", "账单总览") .. format("|cffffff00|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "对账", "对账单")
    elseif text:find("%[.+%[AutoAuction%]金团拍卖助手 V(%d+%.%d+%.%d+)%]") then
        if not text:match("|cff00ff00你已安装插件，不需要加载|r") then
            text = "|cFF8800FF" .. text:gsub("|h", ""):gsub("|Hgarrmission:weakauras", ""):gsub("WeakAuras:", "") .. "|r |cff00ff00你已安装插件，不需要加载|r"
        end
    elseif text:find("(—感谢使用BiaoGe插件—)") or text:find("(RaidLedger: ...平均每人收入:)") then
        text = format(text .. "|cffffff00|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "对账", "对账单")
    else
        if event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" or event == "CHAT_MSG_RAID_WARNING" then
            local yyID
            yyID = text:match("[yY][yY][：:_/%-%s%·]*([%d%s]*%d+) %d+人")
            if not yyID then
                yyID = text:match("[yY][yY][：:_/%-%s%·]*([%d%s]*%d+)")
                if not yyID then
                    yyID = text:match("(%d+[%d%s]*)[：:_/%-%s%·]*[yY][yY]")
                    if not yyID then
                        yyID = text:match("([%d%s]*%d+)[%s]*G团")
                        if not yyID then
                            yyID = text:match("([%d%s]*%d+)[%s]*可待命")
                            if not yyID then
                                yyID = text:match("组人不易[%s]*([%d%s]*%d+)")

                            end
                        end
                    end
                end
            end
            if yyID and #yyID >= 5 then
                yyID = yyID:gsub("%s", "")
                local link = format("|cffffff00|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "YY号:" .. yyID, "复制YY")
                local text2 = text .. link
                if  #text2 <= 255 then
                    text = text2
                else
                    local isExist = false
                    if #channelBaseName == 0 then
                        isExist = true
                    else
                        for i = 1, NUM_CHAT_WINDOWS do
                            local DefaultChannels = {GetChatWindowChannels(_G["ChatFrame" .. i]:GetID())}
                            for j = 1, #DefaultChannels, 2 do
                                if channelBaseName == DefaultChannels[j] then
                                    isExist = true
                                    break
                                end
                            end
                        end
                    end
                    if isExist and not (ZL.lastFilterText and ZL.lastFilterTime and text == ZL.lastFilterText and (GetTime() - (ZL.lastFilterTime or 0) <= 0.1)) then
                        ZL.lastFilterText = text
                        ZL.lastFilterTime = GetTime()
                        SendSystemMessage(link)
                    end
                end
            end
        end
    end
    return false, text, player, l, cs, t, flag, channelId, channelIndex, channelBaseName, ...
end

ChatFrame_AddMessageEventFilter("CHAT_MSG_CHANNEL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_YELL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_GUILD", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_OFFICER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_WARNING", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_SAY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT_LEADER", filterFunc)

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
function ZL.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)
    else
      -- We ignore the error message, since it's more likely not a weakaura.
      decompressed = Compresser:Decompress(decoded)
    end
    if not(decompressed) then
        return "错误"
    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 = 9} --压缩的级别，控制压缩的速度与压缩率之间的平衡。数值越高，压缩的效果越好，但速度可能较慢；数值越低，压缩速度更快，但压缩效果较差。如果不指定，库通常使用默认值（通常是 6）
function ZL.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 = GetTime()
    else
        compressed = LibDeflate:CompressDeflate(serialized, configForDeflate)
        compressedTablesCache[serialized] = {
            compressed = compressed,
            lastAccess = GetTime(),
        }
    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 function getOwnAuctionItemsCount()
    if ((_G["AuctionFrame"] and _G["AuctionFrame"]:IsShown()) or (_G["AuctionHouseFrame"] and _G["AuctionHouseFrame"] :IsShown()))
    and (time() - (ZL.updateOwnAuctionItemsCountTime or 0)) > 0.5 then
        ZL.updateOwnAuctionItemsCountTime = time()
        ZL.opt.OwnAuctionItemsCount = {}
        if ZL.BUILD_DATA >= 5 then
            local ownedAuctions = C_AuctionHouse.GetOwnedAuctions()
            for _, data in ipairs(ownedAuctions) do
                if data.status == 0 then
                    ZL.opt.OwnAuctionItemsCount[data.itemKey.itemID] = (ZL.opt.OwnAuctionItemsCount[data.itemKey.itemID] or 0) + data.quantity
                end
            end
        else
            for index = 1, GetNumAuctionItems("owner") do
                local data = { GetAuctionItemInfo("owner", index) }
                --3:数量；16：1代表已售卖，0代表未售卖；17：物品ID
                if data[16] == 0 then
                    ZL.opt.OwnAuctionItemsCount[data[17]] = (ZL.opt.OwnAuctionItemsCount[data[17]] or 0) + data[3]
                end
            end
        end
    end
end
local function mainInit(self, event, ...)
    local arg = emptytable(...)
    local function formatTimestamp(text)
        if #text ~= 12 then
            return nil, "日期长度不是12位，格式不对！"
        end
        local year = "20" .. text:sub(1, 2)
        local month = text:sub(3, 4)
        local day = text:sub(5, 6)
        local hour = text:sub(7, 8)
        local minute = text:sub(9, 10)
        local second = text:sub(11, 12)
        return string.format("%s-%s-%s %s:%s:%s", year, month, day, hour, minute, second)
    end
    local function InportToStatisticsFromBiaoGe()
        local msgStr
        if _G["BiaoGe"] and _G["BiaoGe"]["History"] then
            local incomeCounts = 0
            for _, value1 in pairs(_G["BiaoGe"]["History"]) do
                for key2, value2 in pairs(value1) do
                    local auctiondate = formatTimestamp(tostring(key2))
                    if auctiondate then
                        local UnitGuid, RealmName, FactionGroup, listkey
                        local IncomeList = {}
                        if value2["raidRoster"] and value2["raidRoster"]["realm"] then
                            RealmName = value2["raidRoster"]["realm"]
                        end
                        if RealmName and value2["lockoutIDtbl"] and next(value2["lockoutIDtbl"], nil) then
                            local linshiList = {}
                            for _, lockoutValue in pairs(value2["lockoutIDtbl"]) do
                                tinsert(linshiList, lockoutValue["lockoutID"])
                            end
                            table.sort(linshiList)
                            UnitGuid = table.concat(linshiList)
                        end
                        if UnitGuid then
                            for key3, value3 in pairs(value2) do
                                local bossIndex = tonumber(key3:match("boss(%d+)"))
                                local isBreak
                                if bossIndex then
                                    for i = 1, 20 do
                                        if value3["maijia" .. i] and value3["zhuangbei" .. i] and value3["jine" .. i] and tonumber(value3["jine" .. i]) and tonumber(value3["jine" .. i]) > 0 then
                                            if (not FactionGroup) then
                                                if value3["factionGroup" .. i] == "Horde" then
                                                    FactionGroup = "部落"
                                                else
                                                    FactionGroup = "联盟"
                                                end
                                            end
                                            if not FactionGroup then
                                                isBreak = true
                                                break
                                            else
                                                if not listkey then
                                                    listkey = RealmName .. "|" .. FactionGroup .. "|" .. UnitGuid .. "|" .. auctiondate
                                                end
                                                if ZL_Statistics[listkey] then
                                                    isBreak = true
                                                    break
                                                else
                                                    local oldItemLink = value3["zhuangbei" .. i]
                                                    local itemlink, itemCount = oldItemLink:match("^(|c.-|Hitem:.+|r)H?x?(%d*)")
                                                    if itemlink then
                                                        --判断是否打包交易
                                                        local isZipTrade
                                                        if value2["tradeTbl"] and #value2["tradeTbl"] > 0 then
                                                            local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                                                            local isBreak2
                                                            for _, tradeTblValue1 in ipairs(value2["tradeTbl"]) do
                                                                for _, tradeTblValue2 in ipairs(tradeTblValue1) do
                                                                    if tradeTblValue2["i"] == i and tradeTblValue2["itemID"] == itemId and tradeTblValue2["b"] == bossIndex then
                                                                        isZipTrade = true
                                                                        isBreak2 = true
                                                                        break
                                                                    end
                                                                end
                                                                if isBreak2 then break end
                                                            end
                                                        end
                                                        if not isZipTrade then
                                                            local r, g, b = unpack(value3["color" .. i])
                                                            r = r*255
                                                            g = g*255
                                                            b = b*255
                                                            local player = RGBAToHex(r, g, b) .. value3["maijia" .. i] .. "|r"
                                                            itemCount = tonumber(itemCount) or 1
                                                            tinsert(IncomeList, {
                                                                ["player"] = player,
                                                                ["notes"] = itemlink,
                                                                ["itemCount"] = itemCount,
                                                                ["amount"] = tonumber(value3["jine" .. i])
                                                            })
                                                            incomeCounts = incomeCounts + 1
                                                        end
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                                if isBreak then break end
                            end
                        end
                        if #IncomeList > 0 then
                            ZL_Statistics[listkey] = {
                                ["IncomeList"] = IncomeList,
                                ["UnitGuid"] = UnitGuid,
                                ["FactionGroup"] = FactionGroup,
                                ["auctiondate"] = auctiondate:match("^(%d+-%d+-%d+)"),
                                ["RealmName"] = RealmName,
                            }
                            IncomeList = nil
                        end
                    end
                end
            end
            if incomeCounts > 0 then
                msgStr = "本次总共导入" .. incomeCounts .. "条成交数据！"
            else
                msgStr = "本次没有数据导入！"
            end
            ZL.Print(msgStr, true)
        else
            msgStr = "未检测到BiaoGe历史数据，请检查是否有开启插件并且存在历史数据！"
            ZL.Print(msgStr, true)
        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
            ZL.MLTradeItems[id] = itemLink
        end
    end
	local tradeFailed = {
		ERR_TRADE_BAG,--"你不能交易装有物品的包";
		ERR_TRADE_BAG_FULL,--"交易失败，你没有足够的物品栏空间。";
		ERR_TRADE_BLOCKED_S,--"%s要求进行交易，你拒绝了。";
		ERR_TRADE_BOUND_ITEM,--"你不能交易一件灵魂绑定物品";
		ERR_TRADE_CANCELLED,--"交易取消。";
		ERR_TRADE_EQUIPPED_BAG,--"你无法交易已经装备的包裹。";
		ERR_TRADE_FACTION_SPECIFIC,--"你无法与对立阵营交易阵营特色物品。";
		ERR_TRADE_GROUND_ITEM,--"你不能交易一件还放在地上的物品。";
		ERR_TRADE_MAX_COUNT_EXCEEDED,--"你拥有超过一件";
		ERR_TRADE_NOT_ON_TAPLIST,--"你只能将绑定物品交易给拥有该物品起始拾取资格的玩家。";
		ERR_TRADE_QUEST_ITEM,--"你不能交易一件任务物品";
		ERR_TRADE_REQUEST_S,--"%s想要和你进行交易。";
		ERR_TRADE_SELF,--"你不能与自己交易。";
		ERR_TRADE_TARGET_BAG_FULL,--"交易失败，交易目标没有足够的物品栏空间。";
		ERR_TRADE_TARGET_DEAD,--"你不能和已死亡的玩家交易";
		ERR_TRADE_TARGET_MAX_COUNT_EXCEEDED,--"交易对象已经拥有该类唯一物品。";
		ERR_TRADE_TARGET_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS,--"你的交易对象只能携带%d个%s";
		ERR_TRADE_TEMP_ENCHANT_BOUND,--"你不能交易带有临时附魔的物品。";
		ERR_TRADE_TOO_FAR,--"交易目标太远";
		ERR_TRADE_WRONG_REALM,--"你只能与来自其它服务器的玩家交易魔法制造的物品";
	}
	local function isTradeFailed(arg2)
		for _,v in pairs(tradeFailed) do
			if arg2 == v then
				return true
			end
		end
		return false
	end
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        local function OnHyperlinkEnter(self, link)
            local linkType, missionID, txt = strsplit(":", link)
            if linkType == "item" then
                -- 在这里可以显示自定义的悬浮提示框
                -- GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                -- GameTooltip:AddLine("玩家: " .. missionID)
                -- GameTooltip:Show()

            elseif linkType == "garrmission" then
                if missionID == "AutoAuction" then
                    if txt == "账单" then
                        GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                        GameTooltip:AddLine("查看账单总览")
                        GameTooltip:Show()
                    elseif txt == "对账" then
                        GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                        GameTooltip:AddLine("查看对账单")
                        GameTooltip:Show()
                    end
                end
            end
        end

        local function OnHyperlinkLeave()
            GameTooltip:Hide()
        end

        for i = 1, NUM_CHAT_WINDOWS do
            _G["ChatFrame"..i.."EditBox"]:SetAltArrowKeyMode(true)
            _G["ChatFrame" .. i]:HookScript("OnHyperlinkEnter", OnHyperlinkEnter)
            _G["ChatFrame" .. i]:HookScript("OnHyperlinkLeave", OnHyperlinkLeave)
        end

        SLASH_ZL_RELOAD1 = "/rl"
        SlashCmdList.ZL_RELOAD = ReloadUI
        SLASH_ZLAA1 ="/aa"
        SLASH_ZLAA2 ="/autoauction"
        SlashCmdList.ZLAA = ZL.OnChatCommand

        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_PLAYERLIST = ZL_PLAYERLIST or {}
        ZL_HISTORY = ZL_HISTORY or {}
        ZL_SETTING = ZL_SETTING or {itemLevelSetting=itemLevelSetting, itemIdSetting={}, filterItemId=filterItemId}
        ZL_Statistics = ZL_Statistics or {}
        RolesOverView = RolesOverView or {
            owner = {},
            sync = {},
            syncKey = {},
            BNChildNewName = {},
            syncKeyUnBind = {},
        }

        if ZL_Statistics["itemList"] then ZL_Statistics["itemList"] = nil end
        if ZL_Statistics["playerList"] then ZL_Statistics["playerList"] = nil end
        if ZL_Statistics["dateRange"] then ZL_Statistics["dateRange"] = nil end
        if ZL_Statistics["listKey"] then ZL_Statistics["listKey"] = nil end
        ZL.db = LibStub("AceDB-3.0"):New("ZL_Profile", defaults, true) --创建默认配置数据库
        local currentProfile = ZL.db:GetCurrentProfile()
        if currentProfile ~= "Default" and (not ZL.db.profile.askedAboutProfile) then
            local msgStr = "当前不是|cff00ff00默认配置(全角色共享)|r，是否切换为默认配置？"
            if  not ZL.db.global.copyToDefalutProfile then
                StaticPopup_Show("ZL_CHANGEANDCOPYTODEFAULTPROFILE", msgStr, nil, currentProfile)
            else
                StaticPopup_Show("ZL_CHANGEDEFAULTPROFILE", msgStr, nil, currentProfile)
            end
        end
        ZL.db.RegisterCallback(ZL, "OnProfileChanged", "OnProfileEnable")
		ZL.db.RegisterCallback(ZL, "OnProfileCopied", "OnProfileEnable")
		ZL.db.RegisterCallback(ZL, "OnProfileReset", "OnProfileEnable")
        
        ZL.opt = ZL.db.profile
        ZL.glb = ZL.db.global

        ZL.opt.playerInfo = ZL.opt.playerInfo or {}
        --删除3天前的玩家历史数据
        for name, data in ipairs(ZL.opt.playerInfo) do
            if time() - data.updateTimestamp > 259200 then
                ZL.opt.playerInfo[name] = nil
            end
        end

        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("金团拍卖助手", "|cffffffffAutoAuction|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" then
                    if IsShiftKeyDown() then
                        if ZL.opt.minIconReloadUI then
                            ReloadUI()
                        end
                    else
                        -- ZL.OpenAceConfigDialog("金团拍卖助手")
                        if ZL.AuctionFrame2:IsShown() then
                            ZL.AuctionFrame2:Hide()
                            ZL.opt.ZLAuctionFrameIsShown = false
                        else
                            ZL.AuctionFrame2:Show()
                            ZL.opt.ZLAuctionFrameIsShown = true
                        end
                    end
                elseif button == "RightButton" then
                    local function tempfunc()
                        return {
                            {text="AutoAuction", isTitle=1},
                            {
                                text = "固定信息总览",
                                func = function ()
                                    if not ZL.RolesOverViewFrame then return end
                                    ZL.RolesOverViewFrame.locked = true
                                    ZL.opt.ZLRolesOverViewFrameIsShown = true
                                    ZL.GetOwnRolesData()
                                    ZL.RolesOverViewFrame:Show()
                                end
                            },
                            {
                                text = ZL.opt.minIconTooltipHide and "打开按钮提示" or "隐藏按钮提示",
                                func = function ()
                                    if ZL.opt.minIconTooltipHide then
                                        ZL.opt.minIconTooltipHide = false
                                    else
                                        ZL.opt.minIconTooltipHide = true
                                        GameTooltip:Hide()
                                    end
                                end
                            },
                            {
                                text = "导入BiaoGe数据",
                                func = function ()
                                    InportToStatisticsFromBiaoGe()
                                end
                            },
                        }
                    end
                    if not ZL.opt.minIconTooltipHide then
                        ZL.GUI:ToggleMenu(self, tempfunc(), "BOTTOMLEFT", self, "TOPRIGHT", -6, -10)
                    else
                        ZL.GUI:ToggleMenu(self, tempfunc(), "TOPLEFT", self, "BOTTOMRIGHT", -6, 10)
                    end
                end
			end,
		})
        
        function ZL.LDB:OnTooltipShow()
            if not ZL.opt.minIconTooltipHide then
                self:AddLine("金团拍卖助手(|cffffffff" .. ZL.addonVersion .. "|r)")
                self:AddLine("自动化拍卖、出价、记账、工资分配、一键批量邮寄工资和补贴、离队计算工资等", 1, 1, 1, true)
                self:AddLine(" ")
                self:AddLine("左键|cffffffff: 打开/关闭拍卖清单窗口|r ")
                if ZL.opt.minIconReloadUI then
                    self:AddLine("Shift+左键：|cffffffff重新加载用户界面|r")
                end
                self:AddLine("右键|cffffffff: 更多功能|r ")
            end
            if ZL.RolesOverViewFrame and not ZL.RolesOverViewFrame.locked then
                ZL.GetOwnRolesData()
                local function IsFrameOverButton(frame, button)
                    if not frame:IsVisible() or not button:IsVisible() then
                        return false
                    end
                    local fX, fY, fWidth, fHeight = frame:GetRect()
                    local bX, bY, bWidth, bHeight = button:GetRect()
                    -- 判断矩形是否相交
                    return fX < bX + bWidth and
                           fX + fWidth > bX and
                           fY < bY + bHeight and
                           fY + fHeight > bY
                end
                local function MoveFrameAwayFromButton(frame, button)
                    if not IsFrameOverButton(frame, button) then return end
                    local bL, bB, bWidth, bHeight = button:GetRect()
                    local bR = GetScreenWidth() - (bL + bWidth)
                    local bT = GetScreenHeight() - (bB + bHeight)
                    frame:ClearAllPoints()
                    if bR > bL then
                        if bT > bB then
                            frame:SetPoint("BOTTOMLEFT", button, "TOPRIGHT", 0, 0)
                        else
                            frame:SetPoint("TOPLEFT", button, "BOTTOMRIGHT", 0, 0)
                        end
                    else
                        if bT > bB then
                            frame:SetPoint("BOTTOMRIGHT", button, "TOPLEFT", 0, 0)
                        else
                            frame:SetPoint("TOPRIGHT", button, "BOTTOMLEFT", 0, 0)
                        end
                    end
                end
                local RolesOverViewFrame = ZL.RolesOverViewFrame
                RolesOverViewFrame:Show()
                MoveFrameAwayFromButton(RolesOverViewFrame, ZL.minimapicon.objects["AUTOAUCTION"])
            end
        end
        function ZL.LDB:OnEnter()
            ZL.LDB.OnTooltipShow(GameTooltip)
            GameTooltip:Show()
        end
        function ZL.LDB:OnLeave()
            if ZL.RolesOverViewFrame and not ZL.RolesOverViewFrame.locked then
                ZL.RolesOverViewFrame:Hide()
            end
            GameTooltip:Hide()
        end

        ZL.minimapicon = LibStub("LibDBIcon-1.0")
		ZL.minimapicon:Register("AUTOAUCTION", ZL.LDB, ZL.db.global)

        local acutioningCountFontString = _G["LibDBIcon10_AUTOAUCTION"]:CreateFontString("ZLAucitoningCountFrame", "OVERLAY")
        acutioningCountFontString:SetPoint("CENTER", 0, -1)
        acutioningCountFontString:SetFont(GameFontNormal:GetFont(), 25, "THICKOUTLINE")

        _G["LibDBIcon10_AUTOAUCTION"].ag = _G["LibDBIcon10_AUTOAUCTION"]:CreateAnimationGroup()
        _G["LibDBIcon10_AUTOAUCTION"].anim = _G["LibDBIcon10_AUTOAUCTION"].ag:CreateAnimation("Alpha")
        local anim = _G["LibDBIcon10_AUTOAUCTION"].anim
        anim:SetOrder(1)
        anim:SetFromAlpha(0.1)
        anim:SetToAlpha(1)
        anim:SetDuration(1.2)
        _G["LibDBIcon10_AUTOAUCTION"].ag:SetToFinalAlpha(1)
        _G["LibDBIcon10_AUTOAUCTION"].ag:SetLooping("BOUNCE")
        
        ZL.opt.lgnoreBtnHide = true --忽略按钮已取消，强制隐藏，关联到其他功能，不可删除

        --强制设置功能按钮显示和隐藏
        do
            ZL.opt.bidEditBoxHide = nil
            ZL.opt.bidBtnHide = nil
            ZL.opt.bidCountsHide = nil
            ZL.opt.startBidHide = nil
            ZL.opt.inrementHide = nil
            ZL.opt.startBtnHide = nil
            ZL.opt.pauseBtnHide = true
            ZL.opt.countdownBtnHide = nil
            ZL.opt.packageBtnHide = true
            ZL.opt.reverseBidBtnHide = true
            ZL.opt.modifyBidBtnHide = true
            ZL.opt.syncBtnHide = nil
            ZL.opt.delAuctionBtnHide = true
        end

        local function historyData(self)
            local _, itemlink = self:GetItem()
            if not itemlink then return end
            local itemId
            if type(itemlink) == "string" then
                itemId = tonumber(itemlink:match("item:(%d+):"))
            elseif type(itemlink) == "number" then
                itemId = itemlink
            end
            if not itemId then return end
            GameTooltip:AddLine(" ")
            GameTooltip:AddLine("|T" .. "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga" .. ":10|t|cff3399ffAutoAuction|r")
            local inventoryCount, bagCount, itemBankCount, itemTotalCount = ZL.GetItemNumbers(itemId)
            local auctionCount = ZL.opt.OwnAuctionItemsCount and (ZL.opt.OwnAuctionItemsCount[itemId] or 0) or 0
            itemTotalCount = itemTotalCount + auctionCount
            GameTooltip:AddLine("装备: |cffffffff" .. inventoryCount .. "|r 背包: |cffffffff" .. bagCount .. "|r 银行: |cffffffff" .. itemBankCount .. "|r 拍卖: |cffffffff" .. auctionCount .. "|r |cff03CCFF合计: |r|cffffffff" .. itemTotalCount .. "|r")
            if not ZL.opt.historyMaxAndMin then return end
            local RealmName, FactionGroup = GetRealmName(), select(2, UnitFactionGroup("player"))
            do
                local smax_all, smin_all, save_all, smaxdate_all, smindate_all
                local smax_local, smin_local, save_local, smaxdate_local, smindate_local
                if ZL_Statistics and next(ZL_Statistics, nil) then
                    -- local RealmName, FactionGroup, sUnitName, auctiondate, listkey, weekday
                    local dataList_all = {}
                    local totalAmount_all = 0
                    local totalCount_all = 0
                    local linshiList_all = {}
                    local dataList_local = {}
                    local totalAmount_local = 0
                    local totalCount_local = 0
                    local linshiList_local = {}
                    for _, data in pairs(ZL_Statistics) do
                        if type(data) == "table" and data.IncomeList and #data.IncomeList > 0 then
                            for _, incomedata in ipairs(data.IncomeList) do
                                local _itemId = tonumber(incomedata.notes:match("|Hitem:(%d+):"))
                                if _itemId == itemId then
                                    local aveDayAmount = tostring(math.floor(incomedata.amount/incomedata.itemCount))
                                    tinsert(linshiList_all, tonumber(aveDayAmount))
                                    if not dataList_all[aveDayAmount] then dataList_all[aveDayAmount] = {} end
                                    tinsert(dataList_all[aveDayAmount], data.auctiondate)
                                    totalAmount_all = totalAmount_all + incomedata.amount
                                    totalCount_all = totalCount_all + incomedata.itemCount

                                    if data.RealmName == RealmName and data.FactionGroup == FactionGroup then
                                        tinsert(linshiList_local, tonumber(aveDayAmount))
                                        if not dataList_local[aveDayAmount] then dataList_local[aveDayAmount] = {} end
                                        tinsert(dataList_local[aveDayAmount], data.auctiondate)
                                        totalAmount_local = totalAmount_local + incomedata.amount
                                        totalCount_local = totalCount_local + incomedata.itemCount
                                    end
                                end
                            end
                        end
                    end
                    if #linshiList_local > 0 then
                        table.sort(linshiList_local)
                        smax_local = linshiList_local[#linshiList_local]
                        smin_local = linshiList_local[1]
                        save_local = math.floor(totalAmount_local/totalCount_local)
                        local smaxdatelist_local = dataList_local[tostring(smax_local)]
                        table.sort(smaxdatelist_local)
                        smaxdate_local = smaxdatelist_local[#smaxdatelist_local]
                        local smindatelist_local = dataList_local[tostring(smin_local)]
                        table.sort(smindatelist_local)
                        smindate_local = smindatelist_local[#smindatelist_local]
                    end
                    if #linshiList_all > 0 then
                        table.sort(linshiList_all)
                        smax_all = linshiList_all[#linshiList_all]
                        smin_all = linshiList_all[1]
                        save_all = math.floor(totalAmount_all/totalCount_all)
                        local smaxdatelist_all = dataList_all[tostring(smax_all)]
                        table.sort(smaxdatelist_all)
                        smaxdate_all = smaxdatelist_all[#smaxdatelist_all]
                        local smindatelist_all = dataList_all[tostring(smin_all)]
                        table.sort(smindatelist_all)
                        smindate_all = smindatelist_all[#smindatelist_all]
                    end
                    dataList_all = nil
                    linshiList_all = nil
                    dataList_local = nil
                    linshiList_local = nil
                end
                if smax_local then
                    GameTooltip:AddLine("本服本阵营成交(|cffff0000仅供参考|r)：")
                    GameTooltip:AddLine("最高：|cffff0000" .. smax_local .. "（" .. smaxdate_local .."）|r")
                    GameTooltip:AddLine("最低：|cff00ff00" .. smin_local .. "（" .. smindate_local .."）|r")
                    GameTooltip:AddLine("均价：|cffffffff" .. save_local .."|r")
                    if ZL.opt.historyTrendChart then
                        for i = 1, 7 do
                            self:AddLine("　　　　　　")
                        end
                    end
                elseif smax_all then
                    GameTooltip:AddLine("所有成交(|cffff0000仅供参考|r)：")
                    GameTooltip:AddLine("最高：|cffff0000" .. smax_all .. "（" .. smaxdate_all .."）|r")
                    GameTooltip:AddLine("最低：|cff00ff00" .. smin_all .. "（" .. smindate_all .."）|r")
                    GameTooltip:AddLine("均价：|cffffffff" .. save_all .."|r")
                    if ZL.opt.historyTrendChart then
                        for i = 1, 7 do
                            self:AddLine("　　　　　　")
                        end
                    end
                else
                    -- GameTooltip:AddLine("没有历史成交数据")
                end
            end
        end
        if WOW_PROJECT_ID ~= 1 then
            GameTooltip:HookScript("OnTooltipSetItem", historyData)
            ItemRefTooltip:HookScript("OnTooltipSetItem", historyData)
        end
        GameTooltip:HookScript("OnShow", function(self)
            if ZL.opt.historyTrendChart then
                C_Timer.After(0.1, function ()
                    local _, itemlink = self:GetItem()
                    if not itemlink then return end
                    local itemId
                    if type(itemlink) == "string" then
                        itemId = tonumber(itemlink:match("item:(%d+):"))
                    elseif type(itemlink) == "number" then
                        itemId = itemlink
                    end
                    if not itemId then return end
                    local RealmName, FactionGroup = GetRealmName(), select(2, UnitFactionGroup("player"))
                    local dateList_local = {}
                    local weekdayList_local = {
                        ["周一"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周二"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周三"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周四"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周五"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周六"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周日"]={totalAmount=0, totalCounts=0, aveAmount=0},
                    }
                    local dateList_all = {}
                    local weekdayList_all = {
                        ["周一"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周二"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周三"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周四"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周五"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周六"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周日"]={totalAmount=0, totalCounts=0, aveAmount=0},
                    }
                    if ZL_Statistics and next(ZL_Statistics, nil) then
                        -- local itemId = tonumber(itemlink:match("item:(%d+):"))
                        local weekday
                        for _, _data in pairs(ZL_Statistics) do
                            if type(_data) == "table" and _data.IncomeList and #_data.IncomeList > 0 then
                                for _, incomedata in ipairs(_data.IncomeList) do
                                    local _itemId = tonumber(incomedata.notes:match("|Hitem:(%d+):"))
                                    if _itemId == itemId then
                                        if not dateList_all[_data.auctiondate] then
                                            dateList_all[_data.auctiondate] = {totalAmount=0, totalCounts=0, aveAmount=0}
                                        end
                                        dateList_all[_data.auctiondate].totalAmount = dateList_all[_data.auctiondate].totalAmount + incomedata.amount
                                        dateList_all[_data.auctiondate].totalCounts = dateList_all[_data.auctiondate].totalCounts + incomedata.itemCount
                                        dateList_all[_data.auctiondate].aveAmount = math.floor(dateList_all[_data.auctiondate].totalAmount/dateList_all[_data.auctiondate].totalCounts)
                                        weekday = GetWeekDay(_data.auctiondate)
                                        weekdayList_all[weekday].totalAmount = weekdayList_all[weekday].totalAmount + incomedata.amount
                                        weekdayList_all[weekday].totalCounts = weekdayList_all[weekday].totalCounts + incomedata.itemCount
                                        weekdayList_all[weekday].aveAmount = math.floor(weekdayList_all[weekday].totalAmount/weekdayList_all[weekday].totalCounts)
    
                                        if _data.RealmName == RealmName and _data.FactionGroup == FactionGroup then
                                            if not dateList_local[_data.auctiondate] then
                                                dateList_local[_data.auctiondate] = {totalAmount=0, totalCounts=0, aveAmount=0}
                                            end
                                            dateList_local[_data.auctiondate].totalAmount = dateList_local[_data.auctiondate].totalAmount + incomedata.amount
                                            dateList_local[_data.auctiondate].totalCounts = dateList_local[_data.auctiondate].totalCounts + incomedata.itemCount
                                            dateList_local[_data.auctiondate].aveAmount = math.floor(dateList_local[_data.auctiondate].totalAmount/dateList_local[_data.auctiondate].totalCounts)
                                            weekdayList_local[weekday].totalAmount = weekdayList_local[weekday].totalAmount + incomedata.amount
                                            weekdayList_local[weekday].totalCounts = weekdayList_local[weekday].totalCounts + incomedata.itemCount
                                            weekdayList_local[weekday].aveAmount = math.floor(weekdayList_local[weekday].totalAmount/weekdayList_local[weekday].totalCounts)
                                        end
                                    end
                                end
                            end
                        end
                    end
                    local newDateList = {}
                    local aveAmountList = {}
                    local weekList = {
                        "周一", "周二", "周三", "周四", "周五", "周六", "周日",
                    }
                    local totalHeight = 0
                    local h2 = 0
                    -- 计算 GameTooltip 原有行高
                    local lineFont
                    for i = 1, GameTooltip:NumLines() do
                        local line = _G["GameTooltipTextLeft" .. i]
                        if line then --and line:IsVisible()
                            totalHeight = totalHeight + line:GetHeight()
                            if not lineFont and line:GetText() == "　　　　　　" then
                                h2 = line:GetHeight()
                                lineFont = line
                                break
                            end
                        end
                    end
                    totalHeight = totalHeight + 3*h2
                    if next(dateList_local, nil) then
                        for key, value in pairs(dateList_local) do
                            tinsert(newDateList, key)
                            tinsert(aveAmountList, value.aveAmount)
                        end
                        table.sort(newDateList)
                        local itemDateBar = ZL.ItemDateBar
                        -- itemDateBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemDateBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemDateBar:Show()
                        local maxValue = math.max(unpack(aveAmountList)) -- 最大值用于缩放
                        local pointSpacing = itemDateBar:GetWidth() / (#aveAmountList+1) -- 数据点之间的水平间距
                        local previousPoint
                        for _, f in ipairs(ZL.ItemDateBar.entries) do f:Hide() end
                        for i, date in ipairs(newDateList) do
                            -- 计算数据点的位置
                            local value = dateList_local[date]["aveAmount"]
                            local x = i * pointSpacing
                            local y = (value / maxValue) * (itemDateBar:GetHeight()-25)
                            local f = ZL.ItemDateBar.entries[i]
                            f:SetValues(x, y, previousPoint)
                            f:Show()
                            previousPoint = f.point
                        end
    
                        local itemWeekDayBar = ZL.ItemWeekDayBar
                        -- itemWeekDayBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemWeekDayBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemWeekDayBar:Show()
                        local aveWeekDayAmountList = {}
                        for i = 1, 7 do
                            tinsert(aveWeekDayAmountList, weekdayList_local[weekList[i]]["aveAmount"])
                        end
                        maxValue = math.max(unpack(aveWeekDayAmountList))
                        local barSpacing = (itemWeekDayBar:GetWidth()-20) / 7 -- 数据点之间的水平间距
                        local barWidth = barSpacing*0.9
                        local barHeight = itemWeekDayBar:GetHeight()
                        for i = 1, 7 do
                            local bar = itemWeekDayBar.entries[i]
                            bar:SetSize(barWidth, aveWeekDayAmountList[i]==0 and 0.001 or (aveWeekDayAmountList[i] / maxValue) * (barHeight-25))
                            if i == 1 then
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", 10, 0)
                            else
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", (i - 1) * barSpacing+10, 0)
                            end
                        end
                        itemDateBar:ClearAllPoints()
                        itemDateBar:SetPoint("TOPLEFT", lineFont, "BOTTOMLEFT", 0, h2/2)
                        itemDateBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                        itemWeekDayBar:ClearAllPoints()
                        itemWeekDayBar:SetPoint("TOP", itemDateBar, "BOTTOM")
                        itemWeekDayBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                    elseif next(dateList_all, nil) then
                        for key, value in pairs(dateList_all) do
                            tinsert(newDateList, key)
                            tinsert(aveAmountList, value.aveAmount)
                        end
                        table.sort(newDateList)
                        local itemDateBar = ZL.ItemDateBar
                        -- itemDateBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemDateBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemDateBar:Show()
                        local maxValue = math.max(unpack(aveAmountList)) -- 最大值用于缩放
                        local pointSpacing = itemDateBar:GetWidth() / (#aveAmountList+1) -- 数据点之间的水平间距
                        local previousPoint
                        for _, f in ipairs(ZL.ItemDateBar.entries) do f:Hide() end
                        for i, date in ipairs(newDateList) do
                            -- 计算数据点的位置
                            local value = dateList_all[date]["aveAmount"]
                            local x = i * pointSpacing
                            local y = (value / maxValue) * (itemDateBar:GetHeight()-30)
                            local f = ZL.ItemDateBar.entries[i]
                            f:SetValues(x, y, previousPoint)
                            f:Show()
                            previousPoint = f.point
                        end
    
                        local itemWeekDayBar = ZL.ItemWeekDayBar
                        -- itemWeekDayBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemWeekDayBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemWeekDayBar:Show()
                        local aveWeekDayAmountList = {}
                        for i = 1, 7 do
                            tinsert(aveWeekDayAmountList, weekdayList_all[weekList[i]]["aveAmount"])
                        end
                        maxValue = math.max(unpack(aveWeekDayAmountList))
                        local barSpacing = (itemWeekDayBar:GetWidth()-20) / 7 -- 数据点之间的水平间距
                        local barWidth = barSpacing*0.9
                        local barHeight = itemWeekDayBar:GetHeight()
                        -- local h = 0
                        for i = 1, 7 do
                            local bar = itemWeekDayBar.entries[i]
                            -- h = bar.label:GetHeight()
                            bar:SetSize(barWidth, aveWeekDayAmountList[i]==0 and 0.001 or (aveWeekDayAmountList[i] / maxValue) * (barHeight-30))
                            if i == 1 then
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", 10, 0)
                            else
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", (i - 1) * barSpacing+10, 0)
                            end
                        end
                        -- h = itemDateBar:GetHeight() + itemWeekDayBar:GetHeight() + h + 8
                        itemDateBar:ClearAllPoints()
                        itemDateBar:SetPoint("TOPLEFT", lineFont, "BOTTOMLEFT", 0, h2/2)
                        itemDateBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                        itemWeekDayBar:ClearAllPoints()
                        itemWeekDayBar:SetPoint("TOP", itemDateBar, "BOTTOM")
                        itemWeekDayBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                    end
                end)
            end
        end)
        GameTooltip:HookScript("OnHide", function (self)
            ZL.ItemDateBar:Hide()
            ZL.ItemWeekDayBar:Hide()
        end)
        _G["TradeFrame"]:HookScript("OnShow", function(self)
            if IsInRaid(1) then
                local ShowAuctionRecordFrame = ZL.ShowAuctionRecordFrame
                ShowAuctionRecordFrame:ClearAllPoints()
                ShowAuctionRecordFrame:SetPoint("BOTTOMRIGHT", _G["TradeFrame"], "TOPRIGHT", 20, 0)
                ShowAuctionRecordFrame:Show()
                -- if ZL_CURRENT.incomeConfirm then
                --     ShowAuctionRecordFrame.TradeGroupWagesBtn:Enable()
                -- else
                --     ShowAuctionRecordFrame.TradeGroupWagesBtn:Disable()
                -- end
            end
        end)
        _G["TradeFrame"]:HookScript("OnHide", function (self)
            ZL.ShowAuctionRecordFrame:Hide()
        end)

        ZL.opt.ZLAuctionRecordFrameIsShown = false
        ZL.SoundType = ZL.SoundTypeList[ZL.opt.VoiceReminderSoundType or 1] or "甜美女声"        --CTR+右键点击物品链接自动创建拍卖物品
        local function SetItemRefActivityMenu(itemLink)
            local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
            local _, _, _, _, _, _, _, stackCount = cGetItemInfo(itemLink)
            local menuList = {}
            local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
            selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
            if IsInRaid(1) then
                if PlayerIsML() then
                    local isExist
                    tinsert(menuList, {
                        text = "拍卖功能",
                        isTitle = true,
                    })
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for index, data in ipairs(ZL_CURRENT.auctionlist) do
                            if data.itemlink == itemLink then
                                local f = ZL.AuctionFrame2.entries[index]
                                local text
                                if (data.state == "failed" or data.state == "waiting") then
                                    text = "|T130866:18:18:2:0|t 开始"
                                elseif data.state == "auctioning" then
                                    text = "|T137048:18:18:2:0|t 取消"
                                elseif data.state == "success" then
                                    text = "|T130866:18:18:2:0|t 重拍"
                                end
                                if text then
                                    tinsert(menuList, {
                                        text = text,
                                        func = function ()
                                            f.MLframe.functionFrame.CancelBtn:Click()
                                        end
                                    })
                                end
                                if data.state == "auctioning" then
                                    tinsert(menuList, {
                                        text = "|TInterface\\AddOns\\AutoAuction\\Images\\5countdown_normal.png:18:18:2:2|t 5秒倒数",
                                        func = function ()
                                            f.MLframe.functionFrame.CountDownBtn:Click()
                                        end
                                    })
                                end
                                if (data.state == "failed" or data.state == "waiting") then
                                    tinsert(menuList, {
                                        text = "|T384756:18:18:2:0|t 快速拍卖",
                                        func = function ()
                                            local _data = {
                                                ["type"] = "指定人员",
                                                ["data"] = data,
                                                ["index"] = index,
                                            }
                                            -- data.index = index
                                            StaticPopup_Show("ZL_ADDINCOME", "收入", nil, _data, ZL.AddIncomeEditboxs)
                                        end
                                    })
                                end
                                isExist = true
                                break
                            end
                        end
                    end
                    if not isExist then
                        tinsert(menuList, {
                            text = "|TInterface\\AddOns\\" .. addonName .. "\\Images\\new.png:18:18:2:0|t " .. "创建拍卖",
                            func = function ()
                                if stackCount == 1 then
                                    ZL.ManualCreateAuctionItem(itemLink, 1)
                                else
                                    StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=nil}, ZL.AddAuctionEditboxs)
                                end
                            end
                        })
                    end
                    tinsert(menuList, {isSeparator = true})
                else
                    table.insert(menuList, {
                        text = "快速记账",
                        func = function ()
                            --快速记账
                            if not ZL.QuickRecordFrame then ZL:CreateQuickRecordFrame() end
                            local  isExist
                            if ZL_PLAYERLIST.lootList then
                                for _bossName, bossNameData in pairs(ZL_PLAYERLIST.lootList) do
                                    if type(bossNameData) == "table" then
                                        for _itemLink, itemLinkData in pairs(bossNameData) do
                                            if _itemLink == itemLink and itemLinkData["拾取1"]["counts"] > 0 then
                                                ZL.QuickRecordFrame.bossName = _bossName
                                                isExist = true
                                                break
                                            end
                                        end
                                        if isExist then break end
                                    end
                                end
                            end
                            if isExist then
                                ZL.QuickRecordFrame:Update(itemLink)
                                ZL.QuickRecordFrame:ClearAllPoints()
                                local uiScale, mX, mY = UIParent:GetEffectiveScale(), GetCursorPosition()
                                mX, mY = mX/uiScale, mY/uiScale
                                local screenWidth = GetScreenWidth() / 2
                                if mX < screenWidth then
                                    ZL.QuickRecordFrame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", mX+30, mY+30)
                                else
                                    ZL.QuickRecordFrame:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", mX-30, mY+30)
                                end
                                ZL.QuickRecordFrame:Show()
                            else
                                local msgStr = "拾取记录不存在或已记录！"
                                ZL.Print(msgStr, true, nil, 1, 0, 0)
                            end
                        end
                    })
                    tinsert(menuList, {isSeparator = true})
                end
            end
            
            if selectCharKey and (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
            (not ZL.opt.concernList[selectCharKey]["itemList"][itemId]) then
                tinsert(menuList, {
                    text = "|A:auctionhouse-icon-favorite:18:18:2:2|a " .. "关注",
                    func = function ()
                        ZL.addItem(itemId)
                    end,
                })
            else
                tinsert(menuList, {
                    text = "|A:auctionhouse-icon-favorite-off:18:18:2:2|a " .. "取消关注",
                    func = function ()
                        ZL.deleteItem(itemId)
                    end
                })
            end
            return menuList
        end
        --CTR+左键点击物品链接流拍物品自动开始拍卖
        hooksecurefunc("SetItemRef", function(link, _, button)
            local linkType, missionID, txt, arg4 = strsplit(":", link)
            if linkType == "garrmission" then
                if missionID == "AutoAuction" then
                    if txt == "账单" then
                        ZL.OverviewFrame:Update(ZL_CURRENT)
                        ZL.OverviewFrame:Show()
                        ZL.ReconciliationFrame:Hide()
                    elseif txt == "对账" then
                        if ZL.ReconciliationFrame:IsShown() then
                            ZL.ReconciliationFrame:Update()
                        else
                            ZL.ReconciliationFrame:Show()
                        end
                        ZL.OverviewFrame:Hide()
                    elseif txt == "YY号" and arg4 then
                        ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
                        ChatEdit_ChooseBoxForSend():SetText(arg4)
                        ChatEdit_ChooseBoxForSend():HighlightText()
                    elseif txt == "通报详细收支" then
                        ZL.reportIncomeConfirm()
                    elseif txt == "保存团员名单" then
                        ZL.saveGroupMembers()
                    elseif txt == "设置多拍" then
                        ZL.opt.allowMultipleAuctions = true
                        TransmitAddonInfo_Pro()
                        C_Timer.NewTicker(0.2, function (self)
                            if ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                self:Cancel()
                                local _link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "设置单拍", "改为单拍")
                                local msg = "已切换为|cffffffff多拍模式|r "
                                ZL.Print(msg .. _link, true)
                                ZL.SpeakText(msg)
                            end
                        end)
                    elseif txt == "设置单拍" then
                        ZL.opt.allowMultipleAuctions = false
                        TransmitAddonInfo_Pro()
                        C_Timer.NewTicker(0.2, function (self)
                            if not ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                self:Cancel()
                                local _link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "设置多拍", "设置多拍")
                                local msg = "已切换为|cffffffff单拍模式|r "
                                ZL.Print(msg .. _link, true)
                                ZL.SpeakText(msg)
                            end
                        end)
                    elseif txt == "历史记录" then
                        ZL.AuctionRecordFrame:Show()
                        _G["ZLAuctionRecordFrameTab1"]:Click()
                    elseif txt == "CLOSENOTICEFOOD" then
                        ZL.opt.autoNoticeFoodInRaid = false
                        local _link = format("已关闭食物、修理机器人团队通报|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "OPENNOTICEFOOD", "打开提醒")
                        ZL.Print(_link, true)
						if IsInRaid(1) then
							local data = {type="request", ver=ZL.addonVersion}
							MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "RAID", nil, "BULK")
						end
                    elseif txt == "OPENNOTICEFOOD" then
                        ZL.opt.autoNoticeFoodInRaid = true
                        local _link = format("已打开食物、修理机器人团队通报|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "CLOSENOTICEFOOD", "关闭提醒")
                        ZL.Print(_link, true)
						if IsInRaid(1) then
							local data = {type="request", ver=ZL.addonVersion}
							MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "RAID", nil, "BULK")
						end
                    end
                end
            elseif linkType == "item" then
                local _, itemLink = cGetItemInfo(link)
                if not itemLink then return end
                local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
                if button == "RightButton" then
                    if ItemRefTooltip:IsVisible() then
                        ItemRefTooltip:Hide()
                    end
                    if (not IsModifierKeyDown()) then
                        ZL.GUI:ToggleMenu(self, SetItemRefActivityMenu(itemLink), 'cursor2')
                    elseif (not IsShiftKeyDown()) and (not IsControlKeyDown()) and IsAltKeyDown() then
                        local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
                        selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
                        if selectCharKey and (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
                        (not ZL.opt.concernList[selectCharKey]["itemList"][itemId]) then
                            ZL.addItem(itemId)
                        else
                            ZL.deleteItem(itemId)
                        end
                    end
                elseif button == "LeftButton" then
                    if IsShiftKeyDown() and (not IsControlKeyDown()) and (not IsAltKeyDown()) and (not AuctionFrame or not AuctionFrame:IsShown()) then
                        local edite = GetCurrentKeyBoardFocus()
                        if edite then
                            if ZL.AddAuctionEditboxs and edite == ZL.AddAuctionEditboxs.editBox5 then
                                edite:SetText(itemId)
                            else
                                edite:SetText(itemLink)
                            end
                        end
                    end
                end
            end
        end)
        --CTR+右键点击背包物品自动创建拍卖物品
        local function hookContainerFrameItemButton_OnModifiedClick(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            local itemLink = containerInfo.hyperlink
            local itemId = containerInfo.itemID
            if PlayerIsML() and IsInRaid(1) 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 stackCount = select(8, cGetItemInfo(itemLink))
                    if stackCount == 1 then
                        ZL.ManualCreateAuctionItem(itemLink, 1)
                    else
                        StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=itemGuid}, ZL.AddAuctionEditboxs)
                    end
                else
                    ZL.Print("注意：" .. itemLink .. "已存在，请勿重复创建！", true)
                end
                itemLoc:Clear()
                return
            end
            if button == "LeftButton" and IsShiftKeyDown() and AuctionFrameBrowse and AuctionFrameBrowse:IsShown() then
                -- local itemLocation = ItemLocation:CreateFromBagAndSlot(self:GetParent():GetID(), self:GetID())
                local itemIsValidAuctionItem = true--(itemLocation:IsValid() and C_AuctionHouse.IsSellItemValid(itemLocation, --[[ displayError = ]] false))
                if itemIsValidAuctionItem then
                    ClearCursor()
                    ClickAuctionSellItemButton()
                    ClearCursor()
                    PickupContainerItem(self:GetParent():GetID(), self:GetID())
                    ClickAuctionSellItemButton()
                    ClearCursor()
                    -- print(GetAuctionSellItemInfo())
                    -- ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
                    -- ChatEdit_InsertLink(format('"%s"', containerInfo.itemName))
                    -- ChatEdit_ChooseBoxForSend():HighlightText()
                    return
                end
                -- itemLocation:Clear()
            end
            local edite = GetCurrentKeyBoardFocus()
            if edite and IsShiftKeyDown() and button == "LeftButton" and _G["AuctionFrame"] and _G["AuctionFrame"]:IsShown() then
                if ZL.AddAuctionEditboxs and edite == ZL.AddAuctionEditboxs.editBox5 then
                    edite:SetText(itemId)
                    if StackSplitFrame and StackSplitFrame:IsShown() then
                        StackSplitFrame:Hide()
                    end
                else
                    edite:SetText(itemLink)
                end
            end
        end
        if ZL.BUILD_DATA < 10 then
            hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", hookContainerFrameItemButton_OnModifiedClick)
        else
            hooksecurefunc(ContainerFrameItemButtonMixin, "OnModifiedClick", hookContainerFrameItemButton_OnModifiedClick)
        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.auctionStateTip then return end
            local itemLocation
            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["spawnUID"] and next(data["spawnUID"], nil) then
                            for _, _value in pairs(data["spawnUID"]) do
                                if _value["itemGUID"] and next(_value["itemGUID"], nil) then
                                    for key, value in pairs(_value["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("  " .. str)
                                                self:Show()
                                            end
                                            return
                                        end
                                    end
                                end
                            end

                        end
                    end
                end
            end
            itemLocation:Clear()
            itemLocation = nil
        end)
        --如果当前插件有激活输入框，则发送链接到输入框
        -- hooksecurefunc("HandleModifiedItemClick", function (itemlink)
            
        -- end)

        --人物右键菜单
        do
            local __poplib = __ala_meta__.__poplib
            local function addEntry(funcName)
                __poplib:AddEntry("SELF", funcName);
                __poplib:AddEntry("_BRFF_SELF", funcName);
                __poplib:AddEntry("PLAYER", funcName);
                __poplib:AddEntry("FRIEND", funcName);
                __poplib:AddEntry("FRIEND_OFFLINE", funcName);
                __poplib:AddEntry("PARTY", funcName);
                __poplib:AddEntry("_BRFF_PARTY", funcName);
                __poplib:AddEntry("RAID", funcName);
                __poplib:AddEntry("RAID_PLAYER", funcName);
                __poplib:AddEntry("_BRFF_RAID_PLAYER", funcName);
                __poplib:AddEntry("CHAT_ROSTER", funcName);
            end
            __poplib:AddMethod("ADD_FINE", {
                GetText = function() return "添加罚款"; end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if PlayerIsML() and IsInRaid(1) then
                        local playIsInRaid
                        for i = 1, MAX_RAID_MEMBERS do
                            local _name = GetRaidRosterInfo(i)
                            if _name and _name == context.name then
                                playIsInRaid = true
                                break
                            end
                        end
                        if playIsInRaid then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    local data = {
                        ["type"] = "罚款",
                        ["name"] = context.name,
                        ["title"] = "罚款",
                        ["amount"] = ZL.opt.popupPrice,
                    }
                    StaticPopup_Show("ZL_ADDINCOME", "收入", nil, data, ZL.AddIncomeEditboxs)
                end,
                category = "AutoAuction",
            });
            addEntry("ADD_FINE")

            __poplib:AddMethod("SENDWA", {
                GetText = function() return "发送拍卖WA"; end,
                IsShown = function(def, context)
                    if not context.name or context.name == UnitName("player") then return end
                    return true
                end,
                OnClick = function(def, which, context)
                    ZL.sendWAString(true)
                    ZL.sendStringFromWA({context.name}, "[AutoAuction]金团拍卖助手", true, "WHISPER")
                end,
                category = "AutoAuction",
            });
            addEntry("SENDWA")

            __poplib:AddMethod("SET_BOSS", {
                GetText = function(def, context)
                    if ZL_CURRENT.WagesBiLi and ZL_CURRENT.WagesBiLi[GetClassColorName(context.name)] and
                    ZL_CURRENT.WagesBiLi[GetClassColorName(context.name)]["biLi"] and ZL_CURRENT.WagesBiLi[GetClassColorName(context.name)]["biLi"] == 0 then
                        return "|T130751:18:18:0:0|t " .. "老板"  --是老板
                    else
                        return "|T130755:18:18:0:0|t " .. "老板"  --不是老板
                    end
                end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if PlayerIsML() and IsInRaid(1) then
                        local playIsInRaid
                        for i = 1, MAX_RAID_MEMBERS do
                            local _name = GetRaidRosterInfo(i)
                            if _name and _name == context.name then
                                playIsInRaid = true
                                break
                            end
                        end
                        if playIsInRaid then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    local colorName = GetClassColorName(context.name)
                    if not ZL_CURRENT.WagesBiLi then ZL_CURRENT.WagesBiLi = {} end
                    if ZL_CURRENT.WagesBiLi and ZL_CURRENT.WagesBiLi[colorName] and
                    ZL_CURRENT.WagesBiLi[colorName]["biLi"] and ZL_CURRENT.WagesBiLi[colorName]["biLi"] == 0 then
                        ZL_CURRENT.WagesBiLi[colorName]["biLi"] = 100
                        ZL.Print(colorName .. "已取消老板，将参与工资计算！", true)
                    else
                        if not ZL_CURRENT.WagesBiLi[colorName] then
                            ZL_CURRENT.WagesBiLi[colorName] = {}
                        end
                        ZL_CURRENT.WagesBiLi[colorName]["biLi"] = 0
                        ZL.Print(colorName .. "已设置为老板，不参与工资计算！", true)
                    end
                    if ZL.AuctionRecordFrame.playerBalanceFrame:IsShown() then
                        ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                    end
                end,
                category = "AutoAuction",
            });
            addEntry("SET_BOSS")

            __poplib:AddMethod("SET_APPOINTMLNAME", {
                GetText = function(def, context)
                    if ZL.opt.appointMLName and ZL.opt.appointMLName == context.name then
                        return "|T130751:18:18:0:0|t " .. "指定拍卖人"  --是
                    else
                        return "|T130755:18:18:0:0|t " .. "指定拍卖人"  --不是
                    end
                end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if IsInRaid(1) and UnitIsGroupLeader("player") and UnitInRaid(context.name) then
                        local lootMethod = GetLootMethod()
                        if (lootMethod == "group" or lootMethod == 3 or lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=context.name, notice=true})
                end,
                category = "AutoAuction",
            });
            addEntry("SET_APPOINTMLNAME")
            __poplib:AddMethod("SENDWHISPER", {
                GetText = function()
                    local activeTalent, _, avgItemLevel = ZL.getMsgContent()
                    return format("%s 装等%d", activeTalent, avgItemLevel);
                end,
                IsShown = function(def, context)
                    if not context.name or context.name == UnitName("player") then return end
                    return true
                end,
                OnClick = function(def, which, context)
                    local activeTalent, _, avgItemLevel = ZL.getMsgContent()
                    SendChatMessage(format("%s 装等%d", activeTalent, avgItemLevel), "WHISPER", nil, context.name)
                end,
                category = "AutoAuction",
            });
            addEntry("SENDWHISPER")
            __poplib:AddMethod("SENDWHISPER2", {
                GetText = function()
                    local activeTalent, _, _, unitLevel = ZL.getMsgContent()
                    return format("%s %d级", activeTalent, unitLevel);
                end,
                IsShown = function(def, context)
                    if not context.name or context.name == UnitName("player") then return end
                    return true
                end,
                OnClick = function(def, which, context)
                    local activeTalent, _, _, unitLevel = ZL.getMsgContent()
                    SendChatMessage(format("%s %d级", activeTalent, unitLevel), "WHISPER", nil, context.name)
                end,
                category = "AutoAuction",
            });
            addEntry("SENDWHISPER2")
            __poplib:AddMethod("SENDWHISPER3", {
                GetText = function()
                    local _, doubleTalent, avgItemLevel = ZL.getMsgContent()
                    return format("%s 装等%d", doubleTalent, avgItemLevel);
                end,
                IsShown = function(def, context)
                    local _, doubleTalent = ZL.getMsgContent()
                    if not doubleTalent or not context.name or context.name == UnitName("player") then return end
                    return true
                end,
                OnClick = function(def, which, context)
                    local _, doubleTalent, avgItemLevel = ZL.getMsgContent()
                    SendChatMessage(format("%s 装等%d", doubleTalent, avgItemLevel), "WHISPER", nil, context.name)
                end,
                category = "AutoAuction",
            });
            addEntry("SENDWHISPER3")
        end
    elseif event == "PLAYER_LOGIN" then
        ZL.Print("欢迎回来  >>>" .. GetClassColorName(UnitName("player")) .."<<<", true, true)
        if not ZL.AuctionFrame2 then ZL:CreateAuctionFrame2() end
        if not ZL.AuctionRecordFrame then ZL:CreateAuctionRecordFrame() end
        if not ZL.FloatAuctionFrame then ZL:CreateFloatAuctionFrame() 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

        if not ZL.ItemDateBar then ZL:CreateItemDateBar() end
        if not ZL.ItemWeekDayBar then ZL:CreateItemWeekDayBar() end
        if not ZL.GroupMembersDropdown then ZL.CreateGroupMembersDropdown() end
        if not ZL.AddIncomeEditboxs then ZL.CreateStaticPopupAddIncomeEditboxs() end
        if not ZL.AddAuctionEditboxs then ZL.CreateStaticPopupAddAuctionEditboxs() end
        if not ZL.QuickRecordFrame then ZL:CreateQuickRecordFrame() end
        if not ZL.BuyItemsFrame then ZL:CreateBuyItemsFrame() end
        if WOW_PROJECT_ID ~= 1 then
            if not ZL.RolesOverViewFrame then ZL:CreateRolesOverViewFrame() end
            if not ZL.LgnoreRolesFrame then ZL:CreateLgnoreRolesFrame() end
        end
        
        if not ZL.ConcernFrame then ZL:CreateConcernFrame() end
        if not ZL.SubsidyFrame then ZL:CreateSubsidyFrame() end
        if not ZL.TaskFrame then ZL:CreateTaskFrame() end
        if not ZL.RaidGroupsFrame then ZL:CreateRaidGroupsFrame() end

        local tabId = abs(ZL.opt.ZLAuctionFrameTabId)
        _G["ZL_NewAuctionFrameTab0"]:Click()
        local AuctionFrame = ZL.AuctionFrame2
        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 = GetTime()
        if PlayerIsML() then
            ZL.mailRegOpen = true
            ZL.AuctionRecordFrame.playerBalanceFrame.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
            --删除历史数据
            local autoClearHistoryDiff = ZL.historyDaysList[ZL.opt.autoClearHistoryDays] * 86400 -- 天数*1天的秒数
            for i = #ZL_HISTORY, 1, -1 do
                if GetDiffTime(ZL_HISTORY[i]["auctiondate"]) >= autoClearHistoryDiff then
                    table.remove(ZL_HISTORY, i)
                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")
        else
            SetCVar("profanityFilter", "1")
        end
        if ZL_HISTORY and #ZL_HISTORY > 0 and ZL_Statistics and (not ZL_Statistics.firstCheck) then
            ZL_Statistics.firstCheck = true
            for _, data in ipairs(ZL_HISTORY) do
                InportToStatistics(data)
            end
        end
        --删除历史成交记录
        if ZL_Statistics and next(ZL_Statistics, nil) then
            local autoClearHistoryDiff = ZL.historyDaysList[ZL.opt.autoClearHistoryIncomeDays] * 86400 -- 天数*1天的秒数
            for key, data in pairs(ZL_Statistics) do
                if type(data) == "table" then
                    if GetDiffTime(data["auctiondate"]) >= autoClearHistoryDiff then
                        ZL_Statistics[key] = nil
                    end
                end
            end
        end
    elseif event == "GROUP_ROSTER_UPDATE" then
        C_Timer.After(1, function ()
            -- 函数：获取当前团队成员列表
            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 (#ZL.opt.MessageString > 0) then
                                -- SendChatMessage(ZL.opt.MessageString, "WHISPER", nil, name)
                                SendChatMessage(ZL.opt.MessageString, "RAID")
                            end
                        end
                    end
                end
                -- 更新之前的团队成员列表
                previousRoster = {}
                for _, name in ipairs(currentRoster) do
                    previousRoster[name] = true
                end
            end
            if IsInRaid(1) then
                if PlayerIsML() then
                    CheckForNewMembers()
                end
                C_Timer.After(1, function ()
                    local MLname = GetMLname() or ZL_CURRENT.MLname
                    if MLname then
                        ZL_CURRENT.UnitGuid = UnitGUID(MLname)
                        ZL_CURRENT.FactionGroup = select(2, UnitFactionGroup(MLname))
                        ZL_CURRENT.MLname = MLname
                    end
                end)
                ZL.SaveDataRemind()
            else
                previousRoster = {}
            end
         end)
    elseif event == "PARTY_LOOT_METHOD_CHANGED" or event == "PARTY_LEADER_CHANGED" then
        -- 已包含在"GROUP_ROSTER_UPDATE"事件里
        local lootMethod = GetLootMethod()
        if (lootMethod == "group" or lootMethod == 3 or lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) and ZL.IsRaidLeader() then
            if (not ZL.opt.appointMLName) or (not UnitInRaid(ZL.opt.appointMLName)) then
                ZL.opt.appointMLName = UnitName("player")
            end
            MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.opt.appointMLName})
        end
        ZL.AuctionFrame2:Update()
    elseif event == "LOOT_OPENED" and IsInInstance() and (select(2, IsInInstance()) == "raid") then -- and IsInInstance() and (select(2, IsInInstance()) == "raid")
        --如果是ML打开掉落则开始创建待拍卖窗口
        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 = date("%Y-%m-%d %H:%M:%S", time())

        local npcID = select(6, strsplit("-", sourceGUID))
        if npcID and ZL.BossInfo[tonumber(npcID)] then
            npcID = ZL.BossInfo[tonumber(npcID)]
        else
            npcID = "其他"
        end
        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
        --先创建完所有的记录
        local lootMethod = GetLootMethod()
        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 > 2 then
                        lootList[itemlink] = (lootList[itemlink] or 0) + lootQuantity
                    end
                    if PlayerIsML() and (lootMethod == "master" or lootMethod == 2) then
                        --拍卖
                        if lootQuality >= minQuality and (not auctionFilter) then
                            --获取候选人
                            if (not isGetCandidates) then
                                candidates = GetMasterLootCandidates(numLoot) --获取候选人信息
                                isGetCandidates = true
                            end
                            --以下新增测试用
                            --增加自定义itemGUID规则：itemId+GetServerTime()+01
                            if not lootAuctionList[itemlink] then
                                lootAuctionList[itemlink] = {spawnUID={}, lootQuantity=0, increment=1}
                            end
                            local stackCount, _, _, _, _, _, bindType = select(8, cGetItemInfo(itemlink))
                            if stackCount == 1 then
                                local spawnUIDkey = itemId ..GetServerTime() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                if itemId == 47242 then --北伐奖章直接放到其他分类
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                else
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName=npcID, itemGUID={}}
                                end
                                lootAuctionList[itemlink].increment = lootAuctionList[itemlink].increment + 1
                                if bindType == 1 then
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey].candidates = candidates
                                end
                            else
                                if lootAuctionList[itemlink].increment == 1 then
                                    local spawnUIDkey = itemId ..GetServerTime() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                end
                            end
                            lootAuctionList[itemlink].lootQuantity = lootAuctionList[itemlink].lootQuantity + lootQuantity
                        end
                        --ML自动拾取
                        local _, _, _, _, _, _, _, itemStackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                        if lootQuality >= lootMinQuality and ZL.opt.awardToML and (not lootFilter) and (not (itemStackCount > 1 and bindType == 1))
                        and (not ZL.isbuyItems(numLoot , itemId)) then
                            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
        --拾取通报
        if next(lootList) then
            local reporter
            if ZL_PLAYERLIST.autoNotice and next(ZL_PLAYERLIST.autoNotice) then
                local tempList = {}
                for i = 1, MAX_RAID_MEMBERS do
                    local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
                    if name and online and ZL_PLAYERLIST.autoNotice[name] and ZL_PLAYERLIST.autoNotice[name].confirmLootAnnounce then
                        tinsert(tempList, name)
                    end
                end
                if #tempList > 1 then
                    table.sort(tempList, function (a, b)
                        local aIsML = PlayerIsML(a)
                        local bIsML = PlayerIsML(b)
                        if aIsML and not bIsML then
                            return true
                        elseif not aIsML and bIsML then
                            return false
                        end
                        local aIsLeader = UnitIsGroupLeader(a)
                        local bIsLeader = UnitIsGroupLeader(b)
                        if aIsLeader and not bIsLeader then
                            return true
                        elseif not aIsLeader and bIsLeader then
                            return false
                        end
                        return a < b
                    end)
                end
                reporter = tempList[1]
                tempList = nil
            end
            if reporter == UnitName("player") 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
        end
        if PlayerIsML() and (lootMethod == "master" or lootMethod == 2) then
            ZL_CURRENT.sourceGUID[sourceGUID].candidates = candidates
            --开始创建拍卖物品
            if next(lootAuctionList, nil) then
                local keyList = {}
                for key, _ in pairs(lootAuctionList) do
                    table.insert(keyList, key)
                end
                local sendData = {type="拾取创建", data={}, globalConfigData=ZL.globalConfigData()}
                for _, itemlink in ipairs(keyList) do
                    --bindType 1为拾取绑定
                    local _, _, _, itemLevel, _, _, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                    local lootQuantity = lootAuctionList[itemlink].lootQuantity
                    local spawnUID = lootAuctionList[itemlink].spawnUID
                    local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                    local indexList = {}
                    local itemindex = 1
                    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 = itemindex + 1
                                if not ZL.opt.notItemStack and data.state ~= "success" and data.state ~= "auctioning" then
                                    table.insert(indexList, num) --可能因交易名单不同存在多个拍卖记录
                                end
                            end
                        end
                    end
                    local data = {}
                    local index
                    if #indexList > 0 then
                        for _, _index in ipairs(indexList) do
                            index = _index  --相同物品都创建到一个拍卖物品上面，取消根据不同拾取权限重新创建
--[[                        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]["sourceGUID"], sourceGUID)
                        ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                        --堆叠数量为1，需要添加进去，大于1不需要
                        if fdata.stackCount == 1 then
                            for key, value in pairs(spawnUID) do
                                ZL_CURRENT.auctionlist[index]["spawnUID"][key] = value
                            end
                        end
                        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.syncAuction(__index)
                            end
                        end
                        fdata = ZL_CURRENT.auctionlist[index]
                        if fdata.state == "failed" then
                            --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                            C_Timer.After(20, function ()
                                ZL.reportFailedItem(true)
                            end)
                        end
                        data = {
                            type = "数量更新",
                            data2 = ZL_CURRENT.auctionlist[index],
                        }
                    else
                        if (not ZL_CURRENT.globalConfig) then
                            ZL_CURRENT.globalConfig = ZL.globalConfigData()
                        end
                        --不存在则创建
                        local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                        bidIncrement = ZL.GetDiffrentIncrementBid(startbidamount, bidIncrement)
                        --ML自己创建，不参与插件同步创建
                        local data2 = {
                            type = "自动创建",
                            itemId = itemId,
                            itemlink = itemlink,
                            itemindex = itemindex,
                            startbidamount = startbidamount,
                            bidIncrement = bidIncrement,
                            state = "waiting",
                            lgnore = false,
                            endTime = nil,
                            bidderlist = {},
                            itemCount = lootQuantity,
                            sourceGUID = {sourceGUID},
                            spawnUID = spawnUID,
                            stackCount = stackCount,
                            bindType = bindType,
                            itemLevel = itemLevel,
                            itemSubType = itemSubType,
                            createTime = date("%Y-%m-%d %H:%M:%S", GetServerTime()),
                        }
                        ZL_CURRENT.auctionlist = ZL_CURRENT.auctionlist or {}
                        table.insert(ZL_CURRENT.auctionlist, data2)
                        local index2 = #ZL_CURRENT.auctionlist
                        data = {
                            type = "创建拍卖",
                            data2 = ZL_CURRENT.auctionlist[index2],
                        }
                    end
                    table.insert(sendData.data, data)
                end
                ZL.AuctionListSort()
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC0", sendData)
            end
            --开始拾取包装备的
            local numLoot = 1
            local function tempfunc()
                if numLoot <= GetNumLootItems() then
                    local delay = 0
                    if LootSlotIsItem(numLoot ) then
                        local itemlink = GetLootSlotLink(numLoot )
                        local _, _, _, _, _, _, isQuestItem = GetLootSlotInfo(numLoot )
                        local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                        if (not isQuestItem) then
                            --自动分配给包装备的
                            if ZL.opt.autoMaster and ZL_CURRENT.buyerItemList and #ZL_CURRENT.buyerItemList > 0 then
                                for _, data in ipairs(ZL_CURRENT.buyerItemList) do
                                    local isBreak
                                    if data.itemId == itemId and data.hasLootCounts < data.itemCounts then
                                        local buyerName = ParseClassColorName(data.buyerName)
                                        local candidateIndex = 1
                                        local candidateName = GetMasterLootCandidate(numLoot , candidateIndex)
                                        while candidateName do
                                            if candidateName == buyerName then
                                                GiveMasterLoot(numLoot , candidateIndex)
                                                isBreak = true
                                                delay = 0.2
                                                break
                                            end
                                            candidateIndex = candidateIndex + 1
                                            candidateName = GetMasterLootCandidate(numLoot , candidateIndex)
                                        end
                                    end
                                    if isBreak then break end
                                end
                            end
                        end
                    else
                        delay = 0
                    end
                    numLoot = numLoot + 1
                    C_Timer.After(delay, tempfunc)
                end
            end
            C_Timer.After(0.3, function ()
                tempfunc()
            end)
        end
    elseif event == "LOOT_CLOSED" and PlayerIsML() then
        C_Timer.After(3, ZL.GetLootItemGUID)
    elseif (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 strfind(msg, "起手")) and not InCombatLockdown() and (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (not PlayerIsML(sender)) and (not UnitIsGroupLeader(sender)) and ZL.opt.welcomeMessageEnable and
        (sender ~= UnitName("player")) and ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0)  then
            SendChatMessage(ZL.opt.MessageString, "RAID")
        end
        do
            --检测biaoge拍卖成功物品
            local itemLink, buyerName, amount = msg:match("{rt6}拍卖成功{rt6} (.-) (.-) (.+)")
            if not (itemLink and buyerName and amount) then
                itemLink, buyerName, amount = msg:match("{rt6}拍賣成功{rt6} (.-) (.-) (.+)")
            end
            if (itemLink and buyerName and amount) then
                local isExist
                if ZL_PLAYERLIST.lootList then
                    for _bossName, bossNameData in pairs(ZL_PLAYERLIST.lootList) do
                        if type(bossNameData) == "table" then
                            for _itemLink, itemLinkData in pairs(bossNameData) do
                                if _itemLink == itemLink and itemLinkData["拾取1"]["counts"] > 0 then
                                    ZL.QuickRecordFrame.bossName = _bossName
                                    isExist = true
                                    break
                                end
                            end
                            if isExist then break end
                        end
                    end
                end
                if isExist then
                    buyerName = GetClassColorName(buyerName)
                    ZL.saveQuickRecordData(itemLink, buyerName, amount, 1)
                end
                if PlayerIsML() then
                    local auctionIndex
                    if ZL_CURRENT.auctionlist then
                        for index, data in ipairs(ZL_CURRENT.auctionlist) do
                            if data.itemlink == itemLink and (data.state == "waiting" or data.state == "failed") then
                                auctionIndex = index
                                break
                            end
                        end
                    end
                    if auctionIndex then
                        local ddate = ZL_CURRENT.auctionlist[auctionIndex]
                        ddate.bidderlist = {
                            {
                                bidder = buyerName,
                                bidamount = tonumber(amount),
                                bidCount = 1,
                                time = GetTime()*1000,
                            }
                        }
                        ZL.startOrCanelAuction(auctionIndex, true)
                    end
                end
            end
        end
        do
            if PlayerIsML() then
                --检测biaoge流拍物品
                local itemLink = msg:match("{rt7}流拍{rt7} (.+)")
                if itemLink then
                    local auctionIndex
                    if ZL_CURRENT.auctionlist then
                        for index, data in ipairs(ZL_CURRENT.auctionlist) do
                            if data.itemlink == itemLink and (data.state == "waiting" or data.state == "failed") then
                                auctionIndex = index
                                break
                            end
                        end
                    end
                    if auctionIndex then
                        ZL.startOrCanelAuction(auctionIndex, true)
                    end
                end
            end
        end
        do
            local itemLink, startAmount = msg:match("{rt1}拍卖开始{rt1} (.-) 起拍价：(.+)")
            if not (itemLink and startAmount) then
                itemLink, startAmount = msg:match("{rt1}拍卖开始{rt1} (.-) 起拍价：(.+)")
            end
            if itemLink and startAmount then
                local itemId = GetItemInfoFromHyperlink(itemLink)
                if itemId then
                    local selectCharKey = ZL.GetClassColorName(UnitName("player")) .. " - " .. GetRealmName()
                    if ZL.opt.concernList and ZL.opt.concernList[selectCharKey] and ZL.opt.concernList[selectCharKey]["itemList"][itemId]
                    and select(4, ZL.GetItemNumbers(itemId)) == 0 then
                        C_VoiceChat.StopSpeakingText()
                        PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\关注物品拍卖.mp3", "Master")
                        ZL.Print("注意！您关注的物品：" .. itemLink .. "开始拍卖，请及时出价！")
                    end
                end
            end
        end
        if ZL_CURRENT.globalConfig and ZL_CURRENT.globalConfig.auctionMode == "团队" then
            --监控全员信息出价
            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_CURRENT.globalConfig.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*)(|c.-|Hitem:.+|h%[.-%]|h|r)$") or cmsg:match("^(%d+%.?%d*)[gGkKwW]?(%[打包拍卖%])$") then
                local matchStr = ""
                if cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)(|c.-|Hitem:.+|h%[.-%]|h|r)$") then
                    matchStr = "(|c.-|Hitem:.+|r)"
                else
                    matchStr = "(%[打包拍卖%])"
                end
                local bidItemLink
                newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.?[0-9]*)[wW][%*%-xX×]?(%d*)" .. matchStr)
                if (not bidItemLink) then
                    newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.?[0-9]*)[kK][%*%-xX×]?(%d*)"  .. matchStr)
                    if (not bidItemLink) then
                        newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.[0-9]*)[%*%-xX×]?(%d*)" .. matchStr)
                        if (not bidItemLink) then
                            newBid, bidCount, bidItemLink = cmsg:match("(%d+)[gG]*[%*%-xX×]?(%d*)" .. matchStr)
                            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_CURRENT.globalConfig.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 then
                local itemCount = ZL_CURRENT.auctionlist[index].itemCount
                --拍卖物品大于1，则重新判断出价和数量
                if itemCount > 1 then
                    cmsg = fullwidthToHalfwidth(msg)
                    if cmsg:match("^%s*(|c.-|Hitem:.+|h%[.-%]|h|r)%s*(%d+%.?%d*)%s*([gGkKwW]?)%s*[%*%-xX× ]?(%d*)%s*$") or cmsg:match("^(%[打包拍卖%])(%d+%.?%d*)[gGkKwW]?$") then
                        local matchStr = ""
                        if cmsg:match("^%s*(|c.-|Hitem:.+|h%[.-%]|h|r)%s*(%d+%.?%d*)%s*([gGkKwW]?)[%*%-xX× ]?(%d*)%s*$") then
                            matchStr = "%s*(|c.-|Hitem:.+|r)%s*"
                        else
                            matchStr = "(%[打包拍卖%])"
                        end
                        local bidItemLink
                        bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)%s*[wW]%s*[%*%-xX× ]?(%d*)%s*")
                        if (not bidItemLink) then
                            bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)%s*[kK]%s*[%*%-xX× ]?(%d*)%s*")
                            if (not bidItemLink) then
                                bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.[0-9]*)%s*[%*%-xX×]?(%d*)%s*")
                                if (not bidItemLink) then
                                    bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "(%d+)%s*[gG]*%s*[%*%-xX×]?(%d*)%s*")
                                    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_CURRENT.globalConfig.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("^%s*(%d+%.?%d*)%s*[gGkKwW]?%s*[%*%-xX ]?(%d*)%s*$") then
                        if AuctioningCount == 1 then
                            index = _index
                            newBid, bidCount = cmsg:match("%s*([0-9]+%.?[0-9]*)%s*[wW]%s*[%*%-xX× ]?([0-9]*)%s*")  --万，检测1W，1.1w
                            if (not newBid) then
                                newBid, bidCount = cmsg:match("%s*([0-9]+%.?[0-9]*)%s*[kK]%s*[%*%-xX× ]?([0-9]*)%s*")  --千，检测1k,1.1K
                                if (not newBid) then
                                    newBid, bidCount = cmsg:match("%s*([0-9]+%.[0-9]*)%s*[%*%-xX× ]?([0-9]*)%s*") --检测1.1这种数字
                                    if (not newBid) then
                                        newBid, bidCount = cmsg:match("%s*(%d+)%s*[gG]*%s*[%*%-xX× ]?([0-9]*)%s*") --检测不带小数点的数字，可能带有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
                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")
                    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 AuctionFrame = ZL.AuctionFrame2
                local Frame1 = AuctionFrame.entries[index]
                local bidderlist = fdata.bidderlist
                local baseamount, bidIncrement, tarbidamount = ZL.GetNewBidAmount(index)
                newBid = padZeros(newBid, tarbidamount, bidIncrement, baseamount)
                if ((newBid - baseamount) % bidIncrement) == 0 or ((newBid - (baseamount - (baseamount % bidIncrement))) % bidIncrement) == 0 then --按照加价幅度整数倍出价
                    if newBid >= tarbidamount then
                        if isFailedAuction then
                            if PlayerIsML() then
                                --如果存在此流拍物品则先启动拍卖，然后将出价直接添加到数据库里
                                if (not ZL_CURRENT.globalConfig) then
                                    ZL_CURRENT.globalConfig = ZL.globalConfigData()
                                end
                                local curAuctionList = ZL_CURRENT.auctionlist[index]
                                if not ZL.IsCanAuction(curAuctionList) then
                                    msgStr = curAuctionList.itemlink .. "无法拍卖，原因可能是：已分解或已无法交易"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                                --如果是流拍的物品重新拍卖，检测流拍物品是否在流拍包里，如果在移动到其他包里
                                if curAuctionList.state == "failed" and ZL.opt.liupaiToggle and curAuctionList["spawnUID"] and next(curAuctionList["spawnUID"], nil) then
                                    local itemList = {}
                                    for _, value in pairs(curAuctionList["spawnUID"]) do
                                        if value["itemGUID"] and next(value["itemGUID"], nil) then
                                            for key, _ in pairs(value["itemGUID"]) do
                                                local bagID, slotIndex = ZL.FindItemInBag(key)
                                                if bagID and (bagID == ZL.opt.liupaiBagId or bagID == ZL.opt.liupaiBagId2) then
                                                    --从第一个背包开始查询空闲的格子，如果不是流拍背包，也不是自己拍到的背包，则放进去
                                                    local targetBagID, targetslotIndex
                                                    local currentInfo
                                                    for _bagID = 0, NUM_BAG_SLOTS do
                                                        if _bagID ~= ZL.opt.liupaiBagId and _bagID ~= ZL.opt.liupaiBagId2 and _bagID ~= ZL.opt.selfBagId then
                                                            for _slotIndex = 1, C_Container.GetContainerNumSlots(_bagID) do
                                                                currentInfo = C_Container.GetContainerItemInfo(_bagID, _slotIndex)
                                                                if not currentInfo then
                                                                    targetBagID = _bagID
                                                                    targetslotIndex = _slotIndex
                                                                    break
                                                                end
                                                            end
                                                        end
                                                    end
                                                    currentInfo = nil
                                                    if targetBagID then
                                                        table.insert(itemList, {
                                                            bagID = bagID, slotIndex = slotIndex,
                                                            targetBagID = targetBagID, targetslotIndex = targetslotIndex,
                                                        })
                                                    end
                                                end
                                            end
                                        end
                                    end
                                    if #itemList > 0 then
                                        local __index = 1
                                        local function linshi()
                                            if __index <= #itemList then
                                                if not (InCombatLockdown() or UnitIsDeadOrGhost("player")) 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)
                                                else
                                                    C_Timer.After(0.2, linshi)
                                                end
                                            end
                                        end
                                        linshi()
                                    end
                                end
                                bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount
                                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 = curAuctionList.state,
                                    data2 = ZL_CURRENT.auctionlist[index],
                                    syncIndex = index,
                                    globalConfigData = ZL.globalConfigData(),
                                }
                                MyAddon:TransmitAddonInfo("AUTOAUC SYNC1", data)
                                Frame1.sync = true
                                Frame1.MLframe.functionFrame.CancelBtn:Disable()
                                C_Timer.After(10, function ()
                                    Frame1.sync = nil
                                    Frame1.MLframe.functionFrame.CancelBtn:Enable()
                                end)
                                ZL.Print("开始拍卖发送数据中，请稍等...")
                            end
                        else
                            if (fdata.endTime or 0) - time() > 0 then
                                fdata.endTime = time() + ZL_CURRENT.globalConfig.auctionTimerRefresh
                                Frame1:SetValues(index)
                                if ZL.opt.IsVoiceReminder and (((not ZL_CURRENT.globalConfig) or (not ZL_CURRENT.globalConfig.YYSound)) or PlayerIsML()) and ((not ZL.jiayou) or ((ZL.jiayou + 30 -GetTime()) < 0))
                                and ((newBid-tarbidamount+bidIncrement) >= 2000 or (newBid >= 10000 )) then
                                    C_VoiceChat.StopSpeakingText()
                                    PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\老公加油.mp3", "Master")
                                    ZL.jiayou = GetTime()
                                    if not ZL.playerModel then
                                        ZL.playerModel = CreateFrame("PlayerModel", nil, UIParent)
                                        local playerModel = ZL.playerModel
                                        playerModel:SetPoint("CENTER")
                                        playerModel:SetSize(200, 200)
                                        -- playerModel:SetUnit("player")
                                        playerModel:SetCreature(25305)
                                        playerModel:SetFacing(-0.4)
                                        playerModel:SetAnimation(69)
                                        playerModel:SetAlpha(1)
                                    end
                                    ZL.playerModel:Show()
                                    C_Timer.After(5, function ()
                                        ZL.playerModel:Hide()
                                    end)
                                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 ZL.BidderListFrame:IsShown() and ZL.BidderListFrame.index then
                                    ZL.BidderListFrame:Update(ZL.BidderListFrame.index)
                                end
                                ZL.updateTargetAmount(index)
                                if (oldBid == 1 or oldBid == 11 or oldBid == 99) and PlayerIsML() then
                                    msgStr = "插件已记录你的竞拍价:" .. newBid .. "g，如需撤销，请【私聊】我回复：撤销"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                end
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = fdata.itemlink .. "拍卖已结束！"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                            end
                        end
                    else
                        local isExist
                        for _, bidData in ipairs(bidderlist) do
                            if bidData.bidder == GetClassColorName(sender) and newBid == bidData.bidAmount then
                                isExist = true
                                break
                            end
                        end
                        if (not isExist) and PlayerIsML() and ZL_CURRENT.globalConfig.auctionMode == "团队" then
                            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
    elseif (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 ZL_CURRENT.tradeGongZi and ZL_CURRENT.tradeGongZi[__name] then
                SendChatMessage("你的工资已交易过，无法登记邮寄！", "WHISPER", nil, sender)
                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 itemlink = ZL_CURRENT.auctionlist[index].itemlink
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemlink=itemlink, itemindex=itemindex, playerName=__name})
            else
                if PlayerIsML() then
                    SendChatMessage("当前存在多个拍卖物品，无法撤销出价！", "WHISPER", nil, sender)
                end
            end
        elseif msg == "重置" then
            if ZL.WaLoadInfo and ZL.WaLoadInfo[sender] then
                if ZL.WaLoadInfo[sender].requestState == "finished" then
                    ZL.WaLoadInfo[sender] = nil
                    ZL.sendStringFromWA({sender}, "[AutoAuction]金团拍卖助手", true, "WHISPER")
                    SendChatMessage("已重置传输次数，点击字符串可重新传输", "WHISPER", nil, sender)
                elseif ZL.WaLoadInfo[sender].requestState == "waiting" then
                    SendChatMessage("你已提交传输请求，不需要重置，请耐心等候", "WHISPER", nil, sender)
                elseif ZL.WaLoadInfo[sender].requestState == "transmitting" then
                    SendChatMessage("你正在传输中，无法重置，请耐心等候", "WHISPER", nil, sender)
                else
                    ZL.sendStringFromWA({sender}, "[AutoAuction]金团拍卖助手", true, "WHISPER")
                    SendChatMessage("不需要重置，点击字符串申请传输后，请耐心等候", "WHISPER", nil, sender)
                end
            else
                ZL.sendStringFromWA({sender}, "[AutoAuction]金团拍卖助手", true, "WHISPER")
                SendChatMessage("不需要重置，点击字符串申请传输后，请耐心等候", "WHISPER", nil, sender)
            end
        end
    elseif (event == "TRADE_CLOSED") then
		ZL.isTrading = nil
        if not ZL.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Hide()
            ZL.opt.ZLAuctionRecordFrameIsShown = false
        end
        if ZL.tradeUpdateTimer then
            if not ZL.tradeUpdateTimer:IsCancelled() then
                ZL.tradeUpdateTimer:Cancel()
            end
            ZL.tradeUpdateTimer = nil
        end
        ZL.ShowAuctionRecordFrame.PlayerTradeMoneyText:Hide()
	elseif (event == "TRADE_SHOW") then
		ZL.ZLAuctionRecordFrameIsShown = ZL.AuctionRecordFrame:IsShown() --如果一开始是打开状态，关闭交易的时候该窗口不关闭
        if (not BG) and (not ZL.tradeUpdateTimer) then
            ZL.tradeUpdateTimer = C_Timer.NewTicker(0.1, function ()
                ZL.ShowAuctionRecordFrame.PlayerTradeMoneyText:SetText("|cffffff00交易金额：|r" .. floor(GetPlayerTradeMoney()/10000) .. goldText)
                if ZL.tradeGongZi and ZL.tradeGongZi*10000 == GetPlayerTradeMoney() and _G["TradeFrameTradeButton"]:IsEnabled() then
                    AcceptTrade()
                end
            end)
        end

        ZL.isTrading = true
		ZL.tradeMoneyML = 0
		ZL.tradeMoneyOther = 0
        ZL.MLTradeItems = {}
        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 and ((not ZL_CURRENT.tradeGongZi) or (not ZL_CURRENT.tradeGongZi[ZL.tradePartner])) and ((not ZL_CURRENT["mailPlayers"]) or (not ZL_CURRENT["mailPlayers"][ZL.tradePartner] == true)) 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
                        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
                                local msgStr = "注意！注意！背包已满，无法分成目标小堆数量！已移除交易清单"
                                ZL.Print(msgStr)
                                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
            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
	elseif (event == "TRADE_ACCEPT_UPDATE") and ZL.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	elseif (event == "TRADE_PLAYER_ITEM_CHANGED") then -- and ZL.tradePartner
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_MONEY_CHANGED") and ZL.tradePartner then
        Trade_UpdateMoney()
	elseif (event == "UI_INFO_MESSAGE") then
        if arg[2] == ERR_TRADE_COMPLETE  then
            if ZL.tradePartner and ZL_CURRENT["IncomeList"] and PlayerIsML() 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
                    --判断是否有欠款
                    local playerBuyList = ZL.GetPlayerBuyList()
                    local balanceAmount = 0
                    local playerPayToMLamount = 0
                    if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                        playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                    end
                    if playerBuyList[ZL.tradePartner] and playerBuyList[ZL.tradePartner].totalAmount then
                        balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                    else
                        balanceAmount = playerPayToMLamount
                    end
                    if PlayerIsML(ZL.tradePartner) then
                        balanceAmount = 0
                    end
                    if balanceAmount < 0 then -- 有欠款则直接记录
                        if not ZL_CURRENT.playerPayToML then ZL_CURRENT.playerPayToML = {} end
                        ZL_CURRENT.playerPayToML[ZL.tradePartner] = (ZL_CURRENT.playerPayToML[ZL.tradePartner] or 0) + ZL.tradeMoneyOther
                        ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                    else --没有欠款，则弹出提示框选择是代交还是自己交或者只是普通的交易不记录
                        local data = {tradeMoneyOther = ZL.tradeMoneyOther, tradePartner = ZL.tradePartner}
                        StaticPopup_Show("ZL_CONFIRMTRADERNAME", ZL.tradePartner, nil, data, ZL.GroupMembersDropdown)
                    end
                end
                ZL.tradePartner = nil
                ZL.AuctionFrame2.Update()
            end
            if ZL.tradeGongZi and PlayerIsML() then
                if not ZL_CURRENT.tradeGongZi then ZL_CURRENT.tradeGongZi = {} end
                ZL_CURRENT.tradeGongZi[ZL.tradeName] = ZL.tradeGongZi
                --剔除邮寄名单
                if ZL_CURRENT["mailPlayers"] then
                    ZL_CURRENT["mailPlayers"][ZL.tradeName] = nil
                end
                ZL.tradeName = nil
                ZL.tradeGongZi = nil
                ZL.tradeGroupMsg = nil
            elseif ZL.tradeGroupGongZi and PlayerIsML() then
                local raidIndex = UnitInRaid(ZL.tradeName)
                if raidIndex then
                    MyAddon:TransmitAddonInfo2("AUTOAUC MY" .. raidIndex, {type="groupGongZi"}, "WHISPER", ZL.tradeName)
                end
                if not ZL_CURRENT.tradeGroupGongZi then ZL_CURRENT.tradeGroupGongZi = {} end
                ZL_CURRENT.tradeGroupGongZi[tostring(ZL.tradeGroup)] = ZL.tradeGroupGongZi
                if not ZL_CURRENT.tradeGongZi then ZL_CURRENT.tradeGongZi = {} end
                for name, gongzi in pairs(ZL.tradeGroupGongZi) do
                    ZL_CURRENT.tradeGongZi[name] = gongzi
                    --剔除邮寄名单
                    if ZL_CURRENT["mailPlayers"] then
                        ZL_CURRENT["mailPlayers"][name] = nil
                    end
                end
                SendChatMessage(ZL.tradeGroupMsg[1], "RAID")
                C_Timer.After(0.2, function ()
                    for i = 2, #ZL.tradeGroupMsg do
                        SendChatMessage(ZL.tradeGroupMsg[i], "RAID")
                    end
                    ZL.tradeGroupMsg = nil
                end)
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
                ZL.tradeName = nil
            elseif ZL.otherTradeGongZi and (not PlayerIsML()) then
                if not ZL_PLAYERLIST.otherTradeGongZi then ZL_PLAYERLIST.otherTradeGongZi = {} end
                ZL_PLAYERLIST.otherTradeGongZi[ZL.tradeName] = ZL.otherTradeGongZi
                ZL.tradeName = nil
                ZL.otherTradeGongZi = nil
                ZL.tradeGroupMsg = nil
            end
        elseif arg[2] == ERR_MAIL_SENT and ZL.Recipient and PlayerIsML() then --"邮件已发出。"
            ZL.ScrollingMessageFrame:AddMessage("【" .. ZL.Recipient .. "】邮件发送成功, 邮寄金额：|cff00ff00" .. ZL.moneyToMail .. "|r".. goldText, 1.0, 1.0, 1.0)
            ZL_CURRENT["mailPlayers"][ZL.Recipient] = true
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            ZL.Recipient = nil
            ZL.moneyToMail = nil
        else
            if isTradeFailed(arg[2]) then
                ZL.tradeGongZi = nil
                ZL.tradeName = nil
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
                ZL.otherTradeGongZi = nil
            end
		end
	elseif (event == "UI_ERROR_MESSAGE") then
        --"找不到收件人。" "收件人现在无法收到邮件。" "内部邮件数据库错误" 
        if 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
    elseif (event == "MAIL_CLOSED") and PlayerIsML() then
        ZL.Recipient = nil
    elseif (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()
    elseif (event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE") and (arg[1] == Enum.PlayerInteractionType.MailInfo) and PlayerIsML() then
        ZL.AuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
    elseif (event == "PLAYER_ENTERING_WORLD") then
        if not ZL.OverviewFrame then ZL:CreateOverviewFrame() end
        if not ZL.ReconciliationFrame then ZL:CreateReconciliationFrame() end
        C_FriendList.ShowFriends()
        C_WowTokenPublic.UpdateMarketPrice()
        if ZL.RolesOverViewFrame then
            ZL.RolesOverViewFrame.locked = false
            ZL.opt.ZLRolesOverViewFrameIsShown = false
        end
        ZL.sendWAString(true)
        --切换地图的时候才触发，比如进出副本
        if (not arg[1]) and (not arg[2]) then
            RequestRaidInfo()
            ZL.WaLoadError = true
            C_Timer.After(3, function ()
                ZL.WaLoadError = nil
            end)
        end
        C_Timer.After(3, function ()
            --获取交易剩余时间定时器
            if not ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(2, function ()
                    ZL.GetRemainingTradeTime()
                end)
            end

            -- 保存数据提醒
            ZL.SaveDataRemind()

            local function saveGroupMembersTip ()
                if ZL.opt.saveGroupMembersSound and IsInInstance() and (select(2, IsInInstance()) == "raid") and PlayerIsML()
                and (not ZL_CURRENT["GroupMembersList"] or #ZL_CURRENT["GroupMembersList"] == 0) then
                    local link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "保存团员名单", "保存团员名单")
                    local msgStr = "还未保存团队名单，注意及时保存哦！" .. link
                    ZL.Print(msgStr, true)
                    C_VoiceChat.StopSpeakingText()
                    PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\保存团队名单.mp3", "Master")
                end
            end
            -- 保存团队名单提醒
            if not ZL.saveGroupMembersTimer then
                ZL.saveGroupMembersTimer = C_Timer.NewTicker(300, function ()
                    saveGroupMembersTip ()
                end)
            end
        end)

        if arg[1] then
            C_Timer.After(10, function ()
                if IsInRaid(1) then
                    local lootMethod = GetLootMethod()
                    if (lootMethod == "group" or lootMethod == 3 or lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                        if ZL.IsRaidLeader() then
                            if (not ZL.opt.appointMLName) or (not UnitInRaid(ZL.opt.appointMLName)) then
                                ZL.opt.appointMLName = UnitName("player")
                            end
                            MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.opt.appointMLName})
                        else
                            MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="request"})
                        end
                    else
                        ZL.opt.appointMLName = nil
                    end
                else
                    ZL.opt.appointMLName = nil
                end
            end)
        end
        --请求同步数据,登录或每次/rl的时候触发
        if arg[1] or arg[2] then
            if ZL_CURRENT["auctionlist"] then
                if (not IsInRaid(1)) or (not PlayerIsML()) then
                    local isUpdate
                    for num, _data in ipairs(ZL_CURRENT["auctionlist"]) do
                        if _data.state == "auctioning" then
                            isUpdate = true
                            ZL_CURRENT.auctionlist[num].state = "waiting"
                            ZL_CURRENT.auctionlist[num].endTime = nil
                            ZL_CURRENT.auctionlist[num].isPaused = nil
                            ZL_CURRENT.auctionlist[num].bidderlist = {}
                        end
                    end
                    if isUpdate then
                        ZL.AuctionFrame2:Update()
                    end
                end
            end
            ZL.miniMapIconAnimation()
            C_Timer.After(5, function ()
                if IsInRaid(1) then
                    --同步ML拍卖数据
                    local MLname = GetMLname()
                    if MLname and (not PlayerIsML()) and (UnitName("player") ~= ZL_CURRENT.MLname) then
                        MyAddon:TransmitAddonInfo2("AUTOAUC REQ", "auctioning", "WHISPER", MLname)
                        -- local msgStr = "已发送同步拍卖中数据请求，等待回应..."
                        -- ZL.Print(msgStr, true)
                    end
                end
            end)
            C_Timer.After(10, function ()
                local chatType
                if IsInRaid(1) then
                    chatType = "RAID"
                elseif IsInGroup(1) then
                    chatType = "PARTY"
                elseif IsInGuild() then
                    chatType = "GUILD"
                else
                    if ZL.opt.auctionMode ~= "团队" then
                        ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
                    end
                end
                if chatType then
                    --获取版本号
                    local data = {type="request", ver=ZL.addonVersion}
                    MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, chatType, nil, "BULK")
                end

                if _G["AtlasLoot_Button_1"] then
                    local count = 1
                    while _G["AtlasLoot_Button_" .. count] do
                        _G["AtlasLoot_Button_" .. count]:HookScript("OnClick", function (self, button)
                            if button == "RightButton" and (not IsModifierKeyDown()) then
                                local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
                                selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
                                if not selectCharKey then return end
                                if (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
                                (not ZL.opt.concernList[selectCharKey]["itemList"][tonumber(self.ItemID)]) then
                                    ZL.addItem(self.ItemID)
                                else
                                    ZL.deleteItem(self.ItemID)
                                end
                            end
                        end)
                        count = count + 1
                    end
                end
            end)
            C_Timer.After(15, function ()
                if ZL.RolesOverViewFrame then
                    ZL.SyncRolesTimerStart()
                end
                if not ZL.SendStatisticsData then
                    local function SendStatisticsData()
                        if not ZL.opt.shareIncomeData then return end
                        local chatType
                        if IsInRaid(1) then
                            chatType = "RAID"
                        elseif IsInGroup(1) then
                            chatType = "PARTY"
                        elseif IsInGuild() then
                            chatType = "GUILD"
                        end
                        if chatType and ZL_Statistics and next(ZL_Statistics, nil) and (((not IsInInstance()) or (select(2, IsInInstance()) ~= "raid"))) then
                            local tempList = {}
                            local diff = 30*86400
                            for key, data in pairs(ZL_Statistics) do
                                if type(data) == "table" and GetDiffTime(data.auctiondate) <= diff then
                                    tempList[key] = data
                                end
                            end
                            if next(tempList, nil) then
                                local data = {
                                    ["type"] = "SendStatisticsData",
                                    ["data"] = tempList,
                                }
                                MyAddon:SYNCALL(data, chatType)
                                wipe(data)
                                data = nil
                            end
                            wipe(tempList)
                            tempList = nil
                        end
                    end
                    SendStatisticsData()
                    ZL.SendStatisticsData =  C_Timer.NewTicker(3600, SendStatisticsData)
                end

                local function ProcessingStatisticsData()
                    while ZL.ReceivedStatisticsData and #ZL.ReceivedStatisticsData > 0 do
                        local data = ZL.ReceivedStatisticsData[1]
                        if data and next(data, nil) then
                            for key, value in pairs(data) do
                                if (not ZL_Statistics[key]) and type(value) == "table" then
                                    ZL_Statistics[key] = value
                                end
                            end
                        end
                        tremove(ZL.ReceivedStatisticsData, 1)
                    end
                    -- 如果还有数据，继续处理，否则等待一段时间再检查
                    if ZL.ReceivedStatisticsData and #ZL.ReceivedStatisticsData > 0 then
                        ProcessingStatisticsData()
                    else
                        C_Timer.After(60, ProcessingStatisticsData)
                    end
                end
                ProcessingStatisticsData()
            end)
        end
    elseif (event == "UPDATE_INSTANCE_INFO") then
        if WOW_PROJECT_ID ~= 1 then
            ZL.GetSavedInstanceInfo()
            ZL.SyncRolesTimerStart()
        end
    elseif (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
    elseif (event == "BAG_OPEN") then
        ZL.BagHighLight()
    elseif (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
        if ZL.opt.ZLRolesOverViewFrameIsShown then
            ZL.RolesOverViewFrame:Show()
        end
    elseif (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
        if ZL.opt.RolesOverViewFrameHide then
            ZL.RolesOverViewFrame:Hide()
        end
    elseif (event == "CHAT_MSG_ADDON") then
        if arg[1] == "WeakAuras" then
            if (not arg[2]:find("^!WA:%d+!.+$")) and (not arg[2]:find("^!.+$")) then
                return
            end
            local received = ZL.StringToTable(arg[2])
            if(received and type(received) == "table" and received.m) then
                if received.m == "dR" then
                    local _, _, dataID, ver = (received.d):find("^(%[AutoAuction%]金团拍卖助手) V(%d+%.%d+%.%d+)")
                    if (not dataID) or (not ver) then return end
                    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].requestState then
                        local msgStr
                        if ZL.WaLoadInfo[sender].requestState == "finished" then
                            msgStr = "你已传输完成，如需重新传输，请回复：重置"
                        elseif ZL.WaLoadInfo[sender].requestState == "waiting" then
                            local ranking = 0
                            local selfIndex = ZL.WaLoadInfo[sender].index
                            for _, data in pairs(ZL.WaLoadInfo) do
                                if data.index < selfIndex and data.requestState ~= "finished" then
                                    ranking = ranking + 1
                                end
                            end
                            msgStr = "你已提交传输请求，前面还有" .. ranking .. "人，请勿重复提交"
                        elseif ZL.WaLoadInfo[sender].requestState == "transmitting" then
                            local perText = 254
                            local hasCounts = ceil(ZL.WaLoadInfo[sender].loaded / perText)
                            local hasTime = ZL.WaLoadInfo[sender].lastTime - ZL.WaLoadInfo[sender].firstTime
                            local speed = hasTime / hasCounts
                            speed = speed <= 1.5 and 1.5 or speed
                            local remainingText = ZL.WaLoadInfo[sender].total - ZL.WaLoadInfo[sender].loaded
                            local remainingTime = ceil(remainingText * speed / perText)
                            msgStr = "你正在传输中，预计剩余时间：" .. remainingTime .. "秒，请耐心等候"
                        end
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        return
                    end
                    local data
                    if _G["WeakAurasSaved"] then
                        data = _G["WeakAurasSaved"].displays["[AutoAuction]金团拍卖助手"]
                    end
                    if data then
                        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 ZL.TableToString(transmit, forChat);
                        end
                        local function TransmitDisplay(id, characterName)
                            ZL.WaLoadError = nil
                            local Comm = LibStub:GetLibrary("AceComm-3.0")
                            local encoded = DisplayToString(id);
                            if(encoded ~= "") then
                                ZL.WaLoadInfo[sender].requestState = "waiting"
                                if not ZL.WaLoadStateFrame then ZL:CreateWaLoadStateFrame() end
                                if not ZL.WaLoadInfo then ZL.WaLoadInfo = {requestList = {}} end
                                if not ZL.WaLoadInfo[sender] then ZL.WaLoadInfo[sender] = {} end
                                if not ZL.WaLoadInfo[sender].index then
                                    ZL.WaLoadInfo[sender].loadCount = 0
                                    for num, f in ipairs(ZL.WaLoadStateFrame.entries) do
                                        local playerName = f.sb.playerName:GetText()
                                        if (not playerName) or playerName == "" or playerName == sender then
                                            ZL.WaLoadInfo[sender].index = num
                                            break
                                        end
                                    end
                                    if not ZL.WaLoadInfo[sender].index then
                                        ZL.WaLoadInfo[sender].index = #ZL.WaLoadStateFrame.entries+1
                                    end
                                end
                                local f = ZL.WaLoadStateFrame.entries[ZL.WaLoadInfo[sender].index]
                                f.btn:SetEnabled(false)
                                local r, g, b = 1, 0.82, 0
                                local classFilename = UnitClassBase(sender)
                                if classFilename then
                                    r, g, b = GetClassColor(classFilename)
                                end
                                f:SetValues(0, 0, r, g, b, sender, "等待传输")
                                Comm:SendCommMessage("WeakAuras", encoded, "WHISPER", characterName, "BULK", function(displayName, loaded, total)
                                    local loadState
                                    local perText = 254
                                    local hasCounts = ceil(loaded / perText)
                                    local hasTime = time() - (ZL.WaLoadInfo[sender].firstTime or time())
                                    local speed = hasTime / hasCounts
                                    speed = speed <= 0.35 and 0.35 or speed
                                    local remainingText = total - loaded
                                    local remainingTime = ceil(remainingText * speed / perText)
                                    if loaded == total then
                                        C_Timer.After(2, function ()
                                            if not ZL.WaLoadError then
                                                ZL.WaLoadInfo[sender].requestState = "finished"
                                                loadState = math.floor(loaded*100/total) .. "%(传输完成,用时：" .. hasTime .. "秒)"
                                                ZL.WaLoadInfo[sender].loadCount = ZL.WaLoadInfo[sender].loadCount + 1
                                                C_Timer.NewTicker(0.2, function (self2)
                                                    if not UnitAffectingCombat(sender) then
                                                        SendChatMessage("传输完成，请选择【导入】或【更新光环-更新】后点【加载UI】生效！", "WHISPER", nil ,sender)
                                                        self2:Cancel()
                                                    end
                                                end)
                                            else
                                                ZL.WaLoadInfo[sender] = nil
                                                loadState = "传输失败"
                                                SendChatMessage("传输失败，请重新点击字符串传输", "WHISPER", nil ,sender)
                                            end
                                            f:SetValues(total, loaded, r, g, b, sender, loadState)
                                            f.btn:SetEnabled(true)
                                        end)
                                    else
                                        ZL.WaLoadInfo[sender].requestState = "transmitting"
                                        loadState = math.floor(loaded*100/total) .. "%(传输中，剩余：" .. remainingTime .. "秒)"
                                        f:SetValues(total, loaded, r, g, b, sender, loadState)
                                    end
                                    ZL.WaLoadInfo[sender].loaded = loaded
                                    ZL.WaLoadInfo[sender].total = ZL.WaLoadInfo[sender].total or total
                                    ZL.WaLoadInfo[sender].firstTime = ZL.WaLoadInfo[sender].firstTime or time()
                                    ZL.WaLoadInfo[sender].lastTime = time()
                                end, id)
                            end
                        end
                        TransmitDisplay(received.d, arg[4])
                    end
                end
            end
        end
    elseif event == "CHAT_MSG_SYSTEM" then
        if arg[1] == ERR_FRIEND_NOT_FOUND then
            if ZL.threadId["coroutineIsOnline"] then
                ZL.PlayerIsOnline = select(2, coroutine.resume(ZL.threadId["coroutineIsOnline"]))
                ZL.IsOnlinePlayer = nil
            end
        elseif arg[1] == ERR_PARTY_CONVERTED_TO_RAID then --"小队转化为团队"
            if IsInRaid(1) and ZL.IsRaidLeader() then
                local lootMethod = GetLootMethod()
                if (lootMethod == "group" or lootMethod == 3 or lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                    if (not ZL.opt.appointMLName) or (not UnitInRaid(ZL.opt.appointMLName)) then
                        ZL.opt.appointMLName = UnitName("player")
                    end
                    MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.opt.appointMLName})
                end
            end
        elseif ZL.IsOnlinePlayer and format(ERR_FRIEND_ADDED_S, ZL.IsOnlinePlayer) == arg[1] then
            ZL.PlayerIsOnline = select(2, coroutine.resume(ZL.threadId["coroutineIsOnline"]))
            ZL.IsOnlinePlayer = nil
        elseif arg[1] == INSTANCE_SAVED then
            RequestRaidInfo()
            C_Timer.After(2, function ()
                local _, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
                for i = 1, GetNumSavedInstances() do
                    local _, lockoutId, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
                    if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                        ZL_CURRENT.lockoutId = lockoutId
                        break
                    end
                end
            end)
        elseif arg[1] == ERR_GROUP_DISBANDED or arg[1] == ERR_LEFT_GROUP_YOU then
            previousRoster = {}
            ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
        elseif ZL.rollTimer and (not ZL.rollTimer:IsCancelled()) and arg[1]:match("(.+)掷出(%d+)（1%-100）") then
            if not ZL.rollList then ZL.rollList = {} end
            local playerName, rollNumber = arg[1]:match("(.+)掷出(%d+)（1%-100）")
            playerName = ZL.GetClassColorName(playerName)
            rollNumber = tonumber(rollNumber)
            if not ZL.rollList[playerName] then
                ZL.rollList[playerName] = {rollNumber, GetTime()*1000}
                ZL.updateRollGameToolTip(ZL.AuctionFrame2.rollBtn)
            end
        elseif strmatch(arg[1], ERR_RAID_MEMBER_REMOVED_S:gsub("%%s", "(.+)")) then
            -- local playerName = strmatch(arg[1], ERR_RAID_MEMBER_REMOVED_S:gsub("%%s", "(.+)"))
            -- if ZL_PLAYERLIST.GroupMembersVersion then
            --     ZL_PLAYERLIST.GroupMembersVersion[playerName] = nil
            -- end
        elseif (strmatch(arg[1], ERR_RAID_MEMBER_ADDED_S:gsub("%%s", "(.+)")) or arg[1] == ERR_PARTY_CONVERTED_TO_RAID
        or arg[1] == "^你加入了一个团队。$" or strmatch(arg[1], ERR_NEW_LOOT_MASTER_S:gsub("%%s", "(.+)"))) and IsInRaid(1) then
            --发送自己的版本号
            if PlayerIsML() then
                ZL.quickMasterButton:Show()
                MyAddon:TransmitAddonInfo("AUTOAUC PRO", ZL.globalConfigData())
            else
                ZL.quickMasterButton:Hide()
            end
            ZL.AuctionFrame2:Update()
        -- elseif arg[1] == ERR_AUCTION_STARTED or arg[1] == ERR_AUCTION_REMOVED or strmatch(arg[1], ERR_AUCTION_SOLD_S:gsub("%%s", "(.+)"))
        -- or strmatch(arg[1], ERR_AUCTION_EXPIRED_S:gsub("%%s", "(.+)")) then
            -- getOwnAuctionItemsCount()
        end
    elseif event == "GROUP_FORMED" or event == "GROUP_JOINED" and GetNumGroupMembers() > 1 then
        if event == "GROUP_JOINED" and IsInRaid(1) and not ZL.IsRaidLeader() then
            local lootMethod = GetLootMethod()
            if (lootMethod == "group" or lootMethod == 3 or lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="request"})
            end
        end
        local chatType
        if IsInRaid(1) then
            chatType = "RAID"
        elseif IsInGroup(1) then
            chatType = "PARTY"
        end
        if chatType then
            local data = {type="request", ver=ZL.addonVersion}
            MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, chatType, nil, "BULK")
        end
    elseif event == "GROUP_LEFT" then
        ZL.opt.appointMLName = nil
        local data = {type="request", ver=ZL.addonVersion}
        MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "GUILD", nil, "BULK")
        if ZL_CURRENT["auctionlist"] then
            local isUpdate
            for num, _data in ipairs(ZL_CURRENT["auctionlist"]) do
                if _data.state == "auctioning" then
                    isUpdate = true
                    ZL_CURRENT.auctionlist[num].state = "waiting"
                    ZL_CURRENT.auctionlist[num].endTime = nil
                    ZL_CURRENT.auctionlist[num].isPaused = nil
                    ZL_CURRENT.auctionlist[num].bidderlist = {}
                end
            end
            if isUpdate then
                ZL.AuctionFrame2:Update()
                ZL.miniMapIconAnimation()
            end
        end
    elseif event == "CHAT_MSG_TRADESKILLS" then
        local _msg = TRADESKILL_LOG_FIRSTPERSON:gsub("%%s", "(.+)")
        if strfind(arg[1], _msg) then
            ZL.SyncRolesTimerStart()
        end
    elseif event == "QUEST_TURNED_IN" or event == "CURRENCY_DISPLAY_UPDATE" or event == "PLAYER_MONEY" then
        if WOW_PROJECT_ID ~= 1 then
            ZL.SyncRolesTimerStart()
        end
    elseif event == "QUEST_LOG_UPDATE" then
        if WOW_PROJECT_ID ~= 1 then
            ZL.SyncRolesTimerStart()
        end
    elseif (event == "ENCOUNTER_END") then
        if arg[5] == 1 then
            RequestRaidInfo()
        end
    elseif (event == "TOKEN_MARKET_PRICE_UPDATED") then
        local price = C_WowTokenPublic.GetCurrentMarketPrice()
        if price and ZL.RolesOverViewFrame then
            local WowTokenBtn = ZL.RolesOverViewFrame.WowTokenBtn
            WowTokenBtn:SetText("|T1120721:13:13:2:0|t " .. GetMoneyString(price))
            WowTokenBtn:SetWidth(WowTokenBtn:GetFontString():GetWidth() + 5)
            WowTokenBtn.price = price
        end
    elseif event == "RAID_INSTANCE_WELCOME" then
        if not IsInRaid(1) then return end
        local instanceName = arg[1]
        C_Timer.After(1, function ()
            local name, _, _, difficultyName, maxPlayers, _, _, instanceID = GetInstanceInfo()
            if instanceID == ZL_CURRENT.instanceID and maxPlayers == ZL_CURRENT.maxPlayers then
                local todayDate = date("%Y-%m-%d", GetServerTime())
                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, nil, {type="更新日期"})
                end
            else
                ZL_CURRENT.bossName = nil
                difficultyName = difficultyName:gsub("人", ""):gsub("（", ""):gsub("）", "")
                difficultyName = difficultyName ~= "" and name .. "(" .. difficultyName .. ")" or name
                local msgStr = "已进入新副本|cffffd100" .. instanceName .. "|r，是否重置当前拍卖数据？"
                StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr, nil, {type="更新副本", instanceID=instanceID, maxPlayers=maxPlayers, name=difficultyName})
            end
        end)
    elseif event == "START_LOOT_ROLL" then
        local inInstance, instanceType = IsInInstance()
        if not (IsInRaid(1) and inInstance and instanceType == "raid") then return end
        local rollID = arg[1]
        local itemlink = GetLootRollItemLink(rollID)
        if not itemlink then return end
        local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
        local _, auctionFilter = isFilterItem(itemId)
        if not auctionFilter then
            local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality)
            local _, _, itemQuality, itemLevel, _, itemType, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
            if itemQuality >= minQuality then
                local lootQuantity = select(3, GetLootRollItemInfo(rollID))
                local index
                local itemindex = 1
                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 = itemindex + 1
                            if not ZL.opt.notItemStack and data.state ~= "success" and data.state ~= "auctioning" then
                                index = num
                            end
                        end
                    end
                end
                local spawnUID = {}
                local bossName = ZL_CURRENT.bossName or "其他"
                if itemId == 47242 then --北伐奖章直接放到其他分类
                    bossName = "其他"
                end
                local spawnUIDkey = itemId .. rollID .. GetServerTime()
                spawnUID[spawnUIDkey] = {bossName=bossName, itemGUID={}}
                if index then
                    local fdata = ZL_CURRENT.auctionlist[index]
                    ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                    if fdata.stackCount == 1 then
                        ZL_CURRENT.auctionlist[index]["spawnUID"][spawnUIDkey] = {bossName=bossName, itemGUID={}}
                    end
                    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
                        end
                    end
                    fdata = ZL_CURRENT.auctionlist[index]
                    if fdata.state == "failed" then
                        --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                        C_Timer.After(20, function ()
                            ZL.reportFailedItem(true)
                        end)
                    end
                else
                    if (not ZL_CURRENT.globalConfig) then
                        ZL_CURRENT.globalConfig = ZL.globalConfigData()
                    end
                    local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                    bidIncrement = ZL.GetDiffrentIncrementBid(startbidamount, bidIncrement)
                    local data2 = {
                        type = "自动创建",
                        itemId = itemId,
                        itemlink = itemlink,
                        itemindex = itemindex,
                        startbidamount = startbidamount,
                        bidIncrement = bidIncrement,
                        state = "waiting",
                        lgnore = false,
                        endTime = nil,
                        bidderlist = {},
                        itemCount = lootQuantity,
                        sourceGUID = {},
                        spawnUID = spawnUID,
                        stackCount = stackCount,
                        bindType = bindType,
                        itemLevel = itemLevel,
                        itemSubType = itemSubType,
                        createTime = date("%Y-%m-%d %H:%M:%S", GetServerTime()),
                    }
                    ZL_CURRENT.auctionlist = ZL_CURRENT.auctionlist or {}
                    table.insert(ZL_CURRENT.auctionlist, data2)
                    if ZL.opt.autoPackage and bindType ~= 1 and PlayerIsML() then
                        ZL.packageAuction(#ZL_CURRENT.auctionlist)
                    end
                end
                ZL.AuctionListSort()
            end
        end
    elseif event == "OWNED_AUCTIONS_UPDATED" or event == "AUCTION_CANCELED"
    or event == "AUCTION_HOUSE_AUCTION_CREATED"or event == "AUCTION_HOUSE_AUCTIONS_EXPIRED"
    or event == "AUCTION_OWNED_LIST_UPDATE" then
        getOwnAuctionItemsCount()
    end
    arg:Release()
end

ZL:RegisterEvent("ADDON_LOADED")
ZL:RegisterEvent("PLAYER_LOGIN")
ZL:SetScript("OnEvent", mainInit)
--注册事件
local eventList = {
    "PLAYER_ENTERING_WORLD", "PLAYER_REGEN_ENABLED", "PLAYER_REGEN_DISABLED", "CHAT_MSG_RAID",
    "CHAT_MSG_RAID_LEADER", "CHAT_MSG_RAID_WARNING", "CHAT_MSG_WHISPER", "CHAT_MSG_ADDON",
    "LOOT_OPENED", "LOOT_CLOSED", "LOOT_READY", "GROUP_ROSTER_UPDATE", "PARTY_LEADER_CHANGED",
    "PARTY_LOOT_METHOD_CHANGED", "UNIT_NAME_UPDATE", "TRADE_MONEY_CHANGED", "UI_INFO_MESSAGE",
    "UI_ERROR_MESSAGE", "TRADE_CLOSED", "TRADE_SHOW", "TRADE_ACCEPT_UPDATE", "PLAYER_TRADE_MONEY",
    "MAIL_SHOW", "MAIL_CLOSED", "MAIL_INBOX_UPDATE", "PLAYER_INTERACTION_MANAGER_FRAME_HIDE",
    "BAG_UPDATE_DELAYED", "BAG_UPDATE", "BAG_OPEN", "CHAT_MSG_LOOT", "ENCOUNTER_END",
    "UPDATE_INSTANCE_INFO", "CHAT_MSG_SYSTEM", "PLAYER_MONEY",
    "CHAT_MSG_TRADESKILLS", "CURRENCY_DISPLAY_UPDATE", "QUEST_TURNED_IN", "QUEST_WATCH_UPDATE",
    "QUEST_LOG_UPDATE", "TOKEN_MARKET_PRICE_UPDATED", "RAID_INSTANCE_WELCOME",
    "GROUP_FORMED", "GROUP_JOINED", "GROUP_LEFT", "START_LOOT_ROLL", "AUCTION_CANCELED",
    "OWNED_AUCTIONS_UPDATED", "AUCTION_HOUSE_AUCTION_CREATED", "AUCTION_HOUSE_AUCTIONS_EXPIRED",
    "AUCTION_OWNED_LIST_UPDATE"
}
for _, eventName in ipairs(eventList) do
    pcall(function ()
        fZL:RegisterEvent(eventName)
    end)
end
fZL:SetScript("OnEvent", mainInit)
