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 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 = true,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        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,
  	},
    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 = true,
        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,
	},
}
function ZL:OnProfileEnable()
	ZL.opt = ZL.db.profile
    TransmitAddonInfo_Pro()
end

local fZL = CreateFrame("Frame")

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

local function filterFunc(self, event, text, player, l, cs, t, flag, channelId, ...)
    local _msg = ERR_FRIEND_ADDED_S:gsub("%%s", "(.+)")
    if (not ZL.addonVersion) or flag == "GM" or flag == "DEV" or (event == "CHAT_MSG_CHANNEL" and type(channelId) == "number" and channelId > 0) then
        return false, text, player, l, cs, t, flag, channelId, ...
    end
    if text:find("^(安装AutoAuction插件后可查看账单总览)$") then
        text = 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
    end
    return false, text, player, l, cs, t, flag, channelId, ...
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_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 function mainInit(self, event, ...)
    local arg = emptytable(...)
    local AuctionFrame = ZL.AuctionFrame2
    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
                                                        -- else
                                                        --     print("打包交易，不导入！")
                                                        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
            print(Prefix(msgStr))
            ZL.ScrollingMessageFrame:AddMessage(msgStr)
        else
            msgStr = "未检测到BiaoGe历史数据，请检查是否有开启插件并且存在历史数据！"
            print(Prefix(msgStr))
            ZL.ScrollingMessageFrame:AddMessage(msgStr)
        end
    end
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        local function OnHyperlinkEnter(self, linkData)
            local linkType, playerName = strsplit(":", linkData)
            if linkType == "player" then
                -- 在这里可以显示自定义的悬浮提示框
                GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                GameTooltip:SetText("玩家: " .. playerName)
                GameTooltip:Show()
            end
        end

        local function OnHyperlinkLeave()
            GameTooltip:Hide()
        end

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

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

        local itemLevelSetting = {
            {
                ["minLevel"] = 225,
                ["sanJianStartBid"] = 300,
                ["wuQiStartBid"] = 500,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 300,
                ["maxLevel"] = 225,
            }, -- [1]
            {
                ["minLevel"] = 232,
                ["sanJianStartBid"] = 500,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 1000,
                ["maxLevel"] = 232,
            }, -- [2]
            {
                ["minLevel"] = 238,
                ["maxLevel"] = 239,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 1000,
            }, -- [3]
            {
                ["minLevel"] = 245,
                ["maxLevel"] = 245,
                ["wuQiStartBid"] = 1000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 1000,
            }, -- [4]
            {
                ["minLevel"] = 252,
                ["maxLevel"] = 252,
                ["wuQiStartBid"] = 3000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 3000,
            }, -- [5]
            {
                ["minLevel"] = 258,
                ["maxLevel"] = 258,
                ["wuQiStartBid"] = 5000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 3000,
                ["sanJianStartBid"] = 3000,
            }, -- [6]
            {
                ["minLevel"] = 272,
                ["maxLevel"] = 272,
                ["wuQiStartBid"] = 10000,
                ["increment"] = 100,
                ["taoZhuangStartBid"] = 0,
                ["sanJianStartBid"] = 10000,
            }, -- [7]
        }
        ZL_CURRENT = ZL_CURRENT or {}
        ZL_HISTORY = ZL_HISTORY or {}
        ZL_SETTING = ZL_SETTING or {itemLevelSetting=itemLevelSetting, itemIdSetting={}, filterItemId=filterItemId}
        ZL_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) --创建默认配置数据库
        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.options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(ZL.db)
		ZL.options.args.profiles.order = -1
		LibStub("AceConfig-3.0"):RegisterOptionsTable("金团拍卖助手", ZL.options)
        LibStub("AceConfigDialog-3.0"):SetDefaultSize("金团拍卖助手", 700, 500)
        --将选项表添加到暴雪的内置“界面”选项面板中
        if WOW_PROJECT_ID ~= 2 then
            LibStub("AceConfigDialog-3.0"):AddToBlizOptions("金团拍卖助手", "|cff0011ffAutoAuction|r")
        end
        --Minimap Icon Creation
		ZL.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga",
			OnClick = function(self, button)
                if button == "LeftButton" and IsShiftKeyDown() then
                    ReloadUI()
                elseif button == "RightButton" then
                    if IsShiftKeyDown() then
                        InportToStatisticsFromBiaoGe()
                    else
                        ZL.RolesOverViewFrame.locked = true
                        ZL.opt.ZLRolesOverViewFrameIsShown = true
                        ZL.GetOwnRolesData()
                        ZL.RolesOverViewFrame:Show()
                    end
                else
                    ZL.OpenAceConfigDialog("金团拍卖助手")
                end
			end,
			OnTooltipShow = function(tooltip)
				tooltip:AddLine("金团拍卖助手(|cffffffff" .. ZL.addonVersion .. "|r)")
				tooltip:AddLine("自动化拍卖、出价、记账、工资分配、一键批量邮寄工资和补贴、离队计算工资等", 1, 1, 1, true)
				tooltip:AddLine(" ")
				tooltip:AddLine("左键|cffffffff: 打开设置窗口|r ")
                tooltip:AddLine("右键|cffffffff: 固定打开角色信息总览窗口|r ")
                tooltip:AddLine("Shift+左键：|cffffffff重新加载用户界面|r")
                tooltip:AddLine("Shift+右键：|cffffffff从BiaoGe插件导入历史成交数据|r")
                if not ZL.RolesOverViewFrame.locked then
                    ZL.GetOwnRolesData()
                    ZL.RolesOverViewFrame:Show()
                end
			end
		})
        function ZL.LDB:OnLeave()
            if not ZL.RolesOverViewFrame.locked then
                ZL.RolesOverViewFrame:Hide()
            end
        end
        ZL.minimapicon = LibStub("LibDBIcon-1.0")
		ZL.minimapicon:Register("ZLAUTOLDB", ZL.LDB, ZL.db.global)
        ZL.opt.lgnoreBtnHide = true --忽略按钮已取消，强制隐藏

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

        if not ZL.ItemDateBar then ZL:CreateItemDateBar() end
        if not ZL.ItemWeekDayBar then ZL:CreateItemWeekDayBar() end
        if not ZL.OverviewFrame then ZL:CreateOverviewFrame() end
        if not ZL.RolesOverViewFrame then ZL:CreateRolesOverViewFrame() end
        if not ZL.LgnoreRolesFrame then ZL:CreateLgnoreRolesFrame() 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 = 0
            for slot = 1, 19 do -- 遍历所有装备栏（1-19）
                local item = GetInventoryItemID("player", slot)
                if item == itemId then
                    inventoryCount = inventoryCount + 1
                end
            end
            local itemBagCount = GetItemCount(itemlink) --获取背包+角色装备物品数量
            local bagCount = itemBagCount - inventoryCount --背包数量
            local itemTotalCount = GetItemCount(itemlink, true) --获取背包+角色装备+银行物品数量
            local itemBankCount = itemTotalCount - itemBagCount --银行物品数量
            GameTooltip:AddLine("装备：|cffffffff" .. inventoryCount .. "|r  背包：|cffffffff" .. bagCount .. "|r  银行：|cffffffff" .. itemBankCount .. "|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")
                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")
                else
                    GameTooltip:AddLine("没有历史成交数据")
                end
            end


        end
        GameTooltip:HookScript("OnTooltipSetItem", historyData)
        ItemRefTooltip:HookScript("OnTooltipSetItem", historyData)

        ZL.opt.ZLAuctionRecordFrameIsShown = false
        --CTR+右键点击物品链接自动创建拍卖物品
        --CTR+左键点击物品链接流拍物品自动开始拍卖
        hooksecurefunc("SetItemRef", function(link, text, button)
            local linkType, missionID, txt = strsplit(":", link)
            -- print(linkType, missionID, txt)
            if linkType == "garrmission" then
                if missionID == "AutoAuction" then
                    if txt == "账单" then
                        ZL.OverviewFrame:Show()
                        ZL.OverviewFrame:Update(ZL_CURRENT)
                    end
                end
            elseif linkType == "item" then
                local _, itemLink, _, _, _, _, _, stackCount = cGetItemInfo(link)
                if itemLink and PlayerIsML() and IsInRaid() and IsControlKeyDown() then
                    if button == "RightButton" then
                        if stackCount == 1 then
                            ZL.ManualCreateAuctionItem(itemLink, 1)
                            print(Prefix("警告！非背包物品创建，可能存在部分功能无法实现！已创建拍卖物品：" .. itemLink))
                        else
                            local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
                            StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=nil})
                        end
                    elseif button == "LeftButton" then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for index, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.state == "failed" or data.state == "waiting") and data.itemlink == itemLink then
                                    local f = ZL.AuctionFrame2.entries[index]
                                    f.MLframe.functionFrame.CancelBtn:Click()
                                    break
                                end
                            end
                        end
                    end
                elseif button == "LeftButton" and IsShiftKeyDown then
                    ZL.ChatEditInsertLink(itemLink)
                end
            end
        end)
        --CTR+右键点击背包物品自动创建拍卖物品
        hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", function(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            local itemLink = containerInfo.hyperlink
            if PlayerIsML() and IsInRaid() and button == "RightButton" and IsControlKeyDown() then
                local itemLoc = ItemLocation:CreateFromBagAndSlot(self:GetParent():GetID(), self:GetID())
                local itemGuid = C_Item.GetItemGUID(itemLoc)
                if (not ZL_CURRENT["itemGUIDUsed"]) or (not ZL_CURRENT["itemGUIDUsed"][itemGuid]) then
                    if not ZL_CURRENT["itemGUIDUsed"] then ZL_CURRENT["itemGUIDUsed"] = {} end
                    local itemId = containerInfo.itemID
                    local stackCount = select(8, cGetItemInfo(itemLink))
                    if stackCount == 1 then
                        ZL.ManualCreateAuctionItem(itemLink, 1, itemGuid)
                        -- ZL_CURRENT["itemGUIDUsed"][itemGuid] = "其他"
                        print(Prefix("已创建拍卖物品：" .. itemLink))
                    else
                        StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=itemGuid})
                    end
                else
                    print(Prefix("注意：" .. itemLink .. "已存在，请勿重复创建！"))
                end
                itemLoc:Clear()
            elseif button == "LeftButton" and IsShiftKeyDown() then
                ZL.ChatEditInsertLink(itemLink)
            end
        end)

        hooksecurefunc("ContainerFrameItemButton_OnEnter", function(self, button)
            -- local link = C_Container.GetContainerItemLink(self:GetParent():GetID(), self:GetID())
            -- GameTooltip:AddLine(link)
            -- GameTooltip:AddLine(link)
            -- GameTooltip:AddLine(link)
        end)
        --增加鼠标提示信息
        hooksecurefunc(GameTooltip, "SetBagItem", function(self, bag, slot)
            if not ZL.opt.auctionStateTip then return end
            local itemLocation
            itemLocation = ItemLocation:CreateFromBagAndSlot(bag, slot)
            if C_Item.DoesItemExist(itemLocation) then
                local itemGuid = C_Item.GetItemGUID(itemLocation)
                -- local itemlink = C_Item.GetItemLink(itemLocation)
                -- historyData(itemlink)
                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)
            -- local edit = GetCurrentKeyBoardFocus()
            -- if edit then
            --     edit:Insert(itemlink)
            -- end
            -- if ZL.focusEditBox then
            --     ZL.focusEditBox:Insert(itemlink)
            -- end
        end)
        --监控WA发送状态
        hooksecurefunc(C_ChatInfo, "SendAddonMessage", function(prefix, message, chatType, target)
            local loaded, total, waName = strsplit(" ", message)
            if not (prefix == "WeakAurasProg" and waName:find("%[AutoAuction%]金团拍卖助手")) then return end
            local dashIndex = target:find("-")
            if dashIndex then
                target = target:sub(1, dashIndex - 1)
            end
            if not ZL.WaLoadStateFrame then ZL:CreateWaLoadStateFrame() end
            if not ZL.WaLoadInfo then ZL.WaLoadInfo = {} end
            if not ZL.WaLoadInfo[target] then ZL.WaLoadInfo[target] = {} end
            if not ZL.WaLoadInfo[target].index then
                ZL.WaLoadInfo[target].loadCount = 0
                for num, f in ipairs(ZL.WaLoadStateFrame.entries) do
                    if (not f.sb.playerName:GetText()) or f.sb.playerName:GetText() == "" then
                        ZL.WaLoadInfo[target].index = num
                        break
                    end
                end
                if not ZL.WaLoadInfo[target].index then
                    ZL.WaLoadInfo[target].index = #ZL.WaLoadStateFrame.entries+1
                end
            end
            local f = ZL.WaLoadStateFrame.entries[ZL.WaLoadInfo[target].index]
            local loadState
            f.btn:SetEnabled(false)
            if loaded == total then
                loadState = math.floor(loaded*100/total) .. "%(传输完成)"
                ZL.WaLoadInfo[target].loadCount = ZL.WaLoadInfo[target].loadCount + 1
                SendChatMessage("您已传输完成，请选择【导入】或【更新光环-更新】后点【加载UI】生效！", "WHISPER", nil ,target)
                f.btn:SetEnabled(true)
            else
                loadState = math.floor(loaded*100/total) .. "%(传输中)"
            end
            local r, g, b = 1, 0.82, 0
            local classFilename = UnitClassBase(target)
            if classFilename then
                r, g, b = GetClassColor(classFilename)
            end
            f:SetValues(total, loaded, r, g, b, target, loadState)
        end)

        local __poplib = __ala_meta__.__poplib
        __poplib:AddMethod("QUERY_TALENT", {
            GetText = function() return "添加罚款"; end,
            IsShown = function() return true; end,
            OnClick = function(def, _, context)
                local msgStr
                if PlayerIsML() then
                    if not context.name then return end
                    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 not playIsInRaid then
                        msgStr = "非团队成员无法添加罚款！"
                        print(Prefix(msgStr))
                        ZL.ScrollingMessageFrame:AddMessage(msgStr)
                        return
                    end
                    local data = {
                        ["type"] = "罚款",
                        ["name"] = context.name,
                        ["title"] = "罚款",
                        ["amount"] = 500,
                    }
                    StaticPopup_Show("ZL_ADDINCOME", "收入", nil, data)
                else
                    msgStr = "你没有权限添加罚款！"
                    print(Prefix(msgStr))
                    ZL.ScrollingMessageFrame:AddMessage(msgStr)
                end
            end,
            category = "AutoAuction",
        });
        __poplib:AddEntry("SELF", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_SELF", "QUERY_TALENT");
        __poplib:AddEntry("PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("FRIEND", "QUERY_TALENT");
        __poplib:AddEntry("FRIEND_OFFLINE", "QUERY_TALENT");
        __poplib:AddEntry("PARTY", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_PARTY", "QUERY_TALENT");
        __poplib:AddEntry("RAID", "QUERY_TALENT");
        __poplib:AddEntry("RAID_PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_RAID_PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("CHAT_ROSTER", "QUERY_TALENT");

        DEFAULT_CHAT_FRAME:AddMessage(Prefix("欢迎回来  >>>" .. UnitName("player") .."<<<"))
    end
    if event == "PLAYER_LOGIN" then
        -- ZL:FrameUpdate()
        local tabId = ZL.opt.ZLAuctionFrameTabId
        _G["ZL_NewAuctionFrameTab0"]:Click()
        AuctionFrame:SetWidth(AuctionFrame:GetWidth()+0.5)
        C_Timer.After(0.5, function ()
            AuctionFrame:SetWidth(AuctionFrame:GetWidth()-0.5)
        end)
        _G["ZL_NewAuctionFrameTab" .. tabId]:Click()

        ZL.reloadUITime = GetServerTime()
        -- ZL.TradeRemainingReminderTime = GetServerTime() - ZL.opt.TradeRemainingReminderPinlv * 60 + 120
        if PlayerIsML() then
            ZL.mailRegOpen = true
            ZL.AuctionRecordFrame.currentIncomeFrame.mailConfirmBtn:SetText("|cff948cff邮寄登记中|r")
        end
        --检测V1.2.04之前版本物品过滤设置
        if ZL_CURRENT.filterItemId and #ZL_CURRENT.filterItemId > 0 then
            for _, data in ipairs(ZL_CURRENT.filterItemId) do
                if data["loot"] == nil then
                    data["loot"] = true
                end
                if data["auction"] == nil then
                    data["auction"] = true
                end
            end
        end
        --检测老板本数据库历史数据是否有缺少日期的，如果有缺少赋值为"1970-01-01 00:01"
        if ZL_HISTORY and #ZL_HISTORY > 0 then
            for i = #ZL_HISTORY, 1, -1 do
                if (not ZL_HISTORY[i]["auctiondate"]) then
                    ZL_HISTORY[i]["auctiondate"] = "1970-01-01 00:01"
                    -- table.remove(ZL_HISTORY, i)
                end
            end
            --删除历史数据
            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") end --关闭语言过滤器
        if ZL.opt.overrideArchive then SetCVar("overrideArchive", "0") end --反和谐
        ZL.SoundType = ZL.SoundTypeList[ZL.opt.VoiceReminderSoundType] or "甜美女声"

        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
        if not ZL.opt.tooltipFirstNotice then
            StaticPopup_Show("ZL_FIRSTNOTICE")
            ZL.opt.tooltipFirstNotice = true
        end

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

        local npcID = select(6, strsplit("-", sourceGUID))
        if npcID and ZL.BossInfo[npcID] then
            npcID = ZL.BossInfo[npcID]
        else
            npcID = "其他"
        end
        local msgStr = ""
        local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality) --GetLootThreshold()获取当前团队的战利品分配阈值
        local lootMinQuality = (ZL.opt.lootMinQuality == -1 and GetLootThreshold() or ZL.opt.lootMinQuality)
        local lootList = {}
        local lootAuctionList = {}
        local candidates = {}
        local isGetCandidates = false
        --先创建完所有的记录
        for numLoot = 1, NumLootItems do
            if LootSlotIsItem(numLoot) then
                local itemlink = GetLootSlotLink(numLoot)
                local _, _, lootQuantity, _, lootQuality, _, isQuestItem = GetLootSlotInfo(numLoot)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                if (not isQuestItem) then
                    local _, auctionFilter, lootFilter = isFilterItem(itemId)
                    --蓝装以上拾取通报
                    if lootQuality > 2 then
                        lootList[itemlink] = (lootList[itemlink] or 0) + lootQuantity
                    end
                    if PlayerIsML() then
                        --拍卖
                        if lootQuality >= minQuality and (not auctionFilter) then
                            --获取候选人
                            if (not isGetCandidates) then
                                candidates = GetMasterLootCandidates(numLoot) --获取候选人信息
                                isGetCandidates = true
                            end
                            --以下新增测试用
                            --增加自定义itemGUID规则：itemId+time()+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 ..time() .. 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 ..time() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                end
                            end
                            lootAuctionList[itemlink].lootQuantity = lootAuctionList[itemlink].lootQuantity + lootQuantity
                        end
                        --自动拾取
                        if lootQuality >= lootMinQuality then
                            if ZL.opt.awardToML and (not lootFilter) then --掉落不是拾取过滤物品自动分配给ML
                                local candidateIndex = 1
                                local candidateName = GetMasterLootCandidate(numLoot, candidateIndex) --用于获取在团队副本中分配战利品时的候选者信息
                                while candidateName do
                                    if PlayerIsML(candidateName) then --当候选人是ML时
                                        GiveMasterLoot(numLoot, candidateIndex)
                                        break
                                    end
                                    candidateIndex = candidateIndex + 1
                                    candidateName = GetMasterLootCandidate(numLoot, candidateIndex)
                                end
                            end
                        end
                    end
                end
            end
        end

        if ZL.opt.confirmLootAnnounce and next(lootList, nil) then  --拾取通报
            SendChatMessage("[AutoAuction]拾取通报：", "RAID")
            C_Timer.After(0.3, function ()
                for link, num in pairs(lootList) do
                    if num > 1 then
                        SendChatMessage(link .. "x" .. num, "RAID")
                    else
                        SendChatMessage(link, "RAID")
                    end
                end
            end)
        end
        if PlayerIsML() then
            ZL_CURRENT.sourceGUID[sourceGUID].candidates = candidates
            -- ZL_CURRENT.sourceGUID[sourceGUID].lootAuctionList = lootAuctionList
            --开始创建拍卖物品
            if next(lootAuctionList, nil) then
                local keyList = {}
                for key, _ in pairs(lootAuctionList) do
                    table.insert(keyList, key)
                end
                local sendData = {type="拾取创建", data={}}
                for _, itemlink in ipairs(keyList) do
                    --bindType 1为拾取绑定
                    local _, _, _, itemLevel, _, _, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                    local lootQuantity = lootAuctionList[itemlink].lootQuantity
                    local spawnUID = lootAuctionList[itemlink].spawnUID
                    local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                    local indexList = {}
                    local itemindex = nil
                    if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == itemlink) then
                                itemindex = data.itemindex
                                if (data.state ~= "success") then
                                    table.insert(indexList, num) --可能因交易名单不同存在多个拍卖记录
                                end
                            end
                        end
                    end
                    if (not itemindex )then
                        itemindex = 1
                    else
                        itemindex = itemindex + 1
                    end
                    local data = {}
                    local index
                    if #indexList > 0 then
                        for _, _index in ipairs(indexList) do
                            local fdata = ZL_CURRENT.auctionlist[_index]
                            if fdata.bindType ~= 1 then --不是拾取绑定的物品，不是拍卖成功的都可以创建到一个拍卖记录上面
                                index = _index
                                break
                            else --拾取绑定的物品
                                --如果是通过自动创建的，有sourceGUID的则判断与第一个sourceGUID交易名单差异
                                if fdata.type == "自动创建" and fdata.sourceGUID and #fdata.sourceGUID > 0 then
                                    local _sourceGUID = fdata.sourceGUID[1]
                                    local _candidates = ZL_CURRENT.sourceGUID[_sourceGUID].candidates
                                    --判断当前的交易名单跟前面的名单对比，有几个不在前面的名单内
                                    local curChaYi = 0
                                    for name, _ in pairs(candidates) do
                                        --不在前面交易名单内
                                        if (not _candidates[name]) then
                                            curChaYi = curChaYi + 1
                                        end
                                    end
                                    --判断前面的交易名单跟现在的对比，有几个不在当前名单内并且还在团队内
                                    local hisChaYi = 0
                                    for name, _ in pairs(_candidates) do
                                        if (not candidates[name]) and UnitInRaid(ParseClassColorName(name)) then
                                            hisChaYi = hisChaYi + 1
                                        end
                                    end
                                    --如果当前的差异不大于拾取数量并且历史差异不大于历史物品数量，则合并拍卖
                                    if curChaYi <= lootQuantity and hisChaYi <= fdata.itemCount then
                                        index = _index
                                        break
                                    end
                                end
                            end
                        end
                    end
                    if index then
                        local fdata = ZL_CURRENT.auctionlist[index]
                        -- table.insert(ZL_CURRENT.auctionlist[index]["candidates"], candidates)  --暂时不能删除
                        table.insert(ZL_CURRENT.auctionlist[index]["sourceGUID"], sourceGUID)
                        ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                        --新增测试内容↓↓↓↓↓↓
                        --堆叠数量为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.AuctionFrame2.entries[__index].MLframe.functionFrame.syncBtn:Click()
                            end
                        end
                        fdata = ZL_CURRENT.auctionlist[index]
                        if fdata.state == "auctioning" then --如果是正在拍卖中的物品，则发送消息全员更新，否则不发送消息，只更新RL的数量
                            local _, _, tarbidamount, bidCount = ZL.GetNewBidAmount(index)
                            local bidderlist = fdata.bidderlist
                            tableSort(bidderlist)
                            local hasbidamount = ""
                            local totalBidCount = 0
                            for _, bidData in ipairs(bidderlist) do
                                if totalBidCount < fdata.itemCount then
                                    local count = bidData["bidCount"] or 1
                                    local newTotalBidCount = totalBidCount + count
                                    if newTotalBidCount > fdata.itemCount then
                                        count = fdata.itemCount - totalBidCount
                                    end
                                    if count  > 1 then
                                        hasbidamount = hasbidamount .. ParseClassColorName(bidData.bidder) .. "(" .. bidData.bidamount .. "x" .. count .. ")，"
                                    else
                                        hasbidamount = hasbidamount .. ParseClassColorName(bidData.bidder) .. "(" .. bidData.bidamount .. ")，"
                                    end
                                    totalBidCount = newTotalBidCount
                                else
                                    break
                                end
                            end
                            if hasbidamount == "" then
                                msgStr = ("注意：%s拍卖数量更新为：%d，当前无人出价，下次最低出价：%d，对应最大数量%d"):format(
                                    fdata.itemlink, fdata.itemCount, tarbidamount, bidCount
                                )
                            else
                                msgStr = ("注意：%s拍卖数量更新为：%d，当前出价：%s下次最低出价：%d，对应最大数量%d"):format(
                                    fdata.itemlink, fdata.itemCount, hasbidamount, tarbidamount, bidCount
                                )
                            end
                            SendChatMessage(msgStr, ZL.MsgChannel())
                        elseif fdata.state == "failed" then
                            --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                            C_Timer.After(20, function ()
                                local curAuctionList = ZL_CURRENT.auctionlist[index]
                                local itemGUIDList = {}
                                if curAuctionList["spawnUID"] and next(curAuctionList["spawnUID"], nil) then
                                    for _, value in pairs(curAuctionList["spawnUID"]) do
                                        if value["itemGUID"] and next(value["itemGUID"], nil) then
                                            for itemGUID, _ in pairs(value["itemGUID"]) do
                                                table.insert(itemGUIDList, itemGUID)
                                            end
                                        end
                                    end
                                end
                                local _index = 1
                                local function changeBag()
                                    if _index <= #itemGUIDList then
                                        local itemGUID = itemGUIDList[_index]
                                        ZL.PutAuctionItemInBag(itemGUID, ZL.opt.liupaiBagId, ZL.opt.liupaiDirection)
                                        _index = _index + 1
                                        C_Timer.After(1, changeBag)
                                    end
                                end
                                changeBag()
                            end)
                        end
                        -- local f = AuctionFrame.entries[index]
                        -- f:SetValues(index)
                        data = {
                            type = "数量更新",
                            data2 = ZL_CURRENT.auctionlist[index],
                        }
                    else
                        local function linshi()
                            if (not ZL_CURRENT.globalConfig) or (ZL_CURRENT.globalConfig.intervalBidIncrement == nil) then
                                TransmitAddonInfo_Pro()
                                C_Timer.After(1, linshi)
                            else
                                --不存在则创建
                                local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                                if ZL_CURRENT.globalConfig.intervalBidIncrement then
                                    if startbidamount < ZL_CURRENT.globalConfig.baseAmount1 then
                                        bidIncrement = bidIncrement
                                    elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount2 then
                                        bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement1, bidIncrement)
                                    elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount3 then
                                        bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement2, bidIncrement)
                                    else
                                        bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement3, bidIncrement)
                                    end
                                end
                                --ML自己创建，不参与插件同步创建
                                local data2 = {
                                    type = "自动创建",
                                    itemId = itemId,
                                    itemlink = itemlink,
                                    itemindex = itemindex,
                                    startbidamount = startbidamount,
                                    bidIncrement = bidIncrement,
                                    state = "waiting",
                                    lgnore = false,
                                    countdownremaining = 0,
                                    auctionTimerRefresh = ZL.opt.auctionTimerRefresh,
                                    isPaused = false,
                                    bidderlist = {},
                                    itemCount = lootQuantity,
                                    sourceGUID = {sourceGUID},
                                    spawnUID = spawnUID,
                                    stackCount = stackCount,
                                    bindType = bindType,
                                    itemLevel = itemLevel,
                                    itemSubType = itemSubType,
                                    createTime = date("%Y-%m-%d %H:%M:%S", time()),
                                }
                                ZL.CreateAuctionList()
                                table.insert(ZL_CURRENT.auctionlist, data2)
                                local index2 = #ZL_CURRENT.auctionlist
                                data = {
                                    type = "创建拍卖",
                                    data2 = ZL_CURRENT.auctionlist[index2],
                                }
                            end
                        end
                        linshi()
                    end
                    table.insert(sendData.data, data)
                end
                ZL.AuctionListSort(true)
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC0", sendData)
            end
        end
    end
    if event == "LOOT_CLOSED" and PlayerIsML() then
        C_Timer.After(3, ZL.GetLootItemGUID)
    end
    if (event == "CHAT_MSG_RAID") or (event == "CHAT_MSG_RAID_LEADER") or (event == "CHAT_MSG_RAID_WARNING") then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        if (strfind(msg, "YY") or strfind(msg, "yy") or strfind(msg, "歪歪")) and (not strfind(msg, "待命") and not strfind(msg, "声") and not strfind(msg, "说") and not strfind(msg, "在") and not strfind(msg, "YY:"))
        and not strfind(msg, "开") and (not strfind(msg, "起手")) and not InCombatLockdown() and (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (sender~= UnitName("player")) and ZL.opt.welcomeMessageEnable and
        ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0)  then
            SendChatMessage(ZL.opt.MessageString, "RAID")
        end
        --监控全员信息出价
        local AuctioningCount, _index = GetAuctioningCount()
        local isFailedAuction --流拍物品重启拍卖
        local msgStr = ""
        local newBid, index
        local bidCount
        local cmsg = fullwidthToHalfwidth(msg)
        --首先全部剔除空格判断是否存在对应的拍卖物品
        cmsg = msg_gsub(cmsg)
        if cmsg:match("^(|c........|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") or cmsg:match("^(%[打包拍卖%])(%d+%.?%d*)[gGkKwW]?$") then
            local matchStr = ""
            if cmsg:match("^(|c........|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") then
                matchStr = "(|c........|Hitem:.+|r)"
            else
                matchStr = "(%[打包拍卖%])"
            end
            local bidItemLink
            bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[wW][%*%-xX×]?(%d*)")
            if (not bidItemLink) then
                bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[kK][%*%-xX×]?(%d*)")
                if (not bidItemLink) then
                    bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.[0-9]*)[%*%-xX×]?(%d*)")
                    if (not bidItemLink) then
                        bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "(%d+)[gG]*[%*%-xX×]?(%d*)")
                        if (not bidItemLink) then
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = ("【%s】不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(sender, bidItemLink)
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                -- SendChatMessage(msgStr, "RAID")
                            end
                            newBid = nil
                        end
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 1000)
                end
            else
                newBid = math.floor(tonumber(newBid) * 10000)
            end
            if bidItemLink then
                if AuctioningCount > 0 then
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == bidItemLink) and (data.state == "auctioning") then
                                index = num
                                break
                            end
                        end
                    end
                end
                if not index then
                    if AuctioningCount > 0 then
                        --如果此物品没有正在拍卖，则判断是否为多拍模式，多拍模式下，如果是流拍物品，则启动拍卖
                        if ZL.opt.allowMultipleAuctions then
                            isFailedAuction = true
                        else
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                return
                            end
                        end
                    else
                        --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                        isFailedAuction = true
                    end
                end
                if isFailedAuction then
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                index = num
                                break
                            end
                        end
                    end
                    if not index then
                        if PlayerIsML() and ZL.opt.remindInvalidBid then
                            msgStr = bidItemLink .. "没有此流拍物品"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                        end
                    end
                end
            end
        elseif cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX]?(%d*)$") then
            if AuctioningCount == 1 then
                index = _index
                newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[wW][%*%-xX×]?([0-9]*)")  --万，检测1W，1.1w
                if (not newBid) then
                    newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[kK][%*%-xX×]?([0-9]*)")  --千，检测1k,1.1K
                    if (not newBid) then
                        newBid, bidCount = cmsg:match("([0-9]+%.[0-9]*)[%*%-xX×]?([0-9]*)") --检测1.1这种数字
                        if (not newBid) then
                            newBid, bidCount = cmsg:match("(%d+)[gG]*[%*%-xX×]?([0-9]*)") --检测不带小数点的数字，可能带有g或G
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 1000)
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 10000)
                end
            elseif AuctioningCount > 1 then
                if PlayerIsML() and ZL.opt.remindInvalidBid and ZL_CURRENT.auctionlist[_index].itemlink then
                    msgStr = "出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                    msgStr = ">>>" .. sender .. "<<<，出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                    SendChatMessage(msgStr, "RAID")
                end
                return
            else
                return
            end
        end
        --如果存在拍卖物品则判断这个拍卖物品的数量
        if index and newBid 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.opt.allowMultipleAuctions then
                                    isFailedAuction = true
                                else
                                    if PlayerIsML() and ZL.opt.remindInvalidBid then
                                        msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                                        return
                                    end
                                end
                            else
                                --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                                isFailedAuction = true
                            end
                        end
                        if isFailedAuction then
                            if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                                for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                    if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                        index = num
                                        break
                                    end
                                end
                            end
                            if not index then
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = bidItemLink .. "没有此流拍物品"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                end
                            end
                        end
                    end
                elseif cmsg:match("^%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")
                    return
                end
                return
            end
            if newBid == 666 then
                if PlayerIsML() then
                    msgStr = ("\"666\"为高频易混淆词，如需竞价请在后面添加一个0，如：%d0，如不竞价，忽略这条提醒"):format(newBid)
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                end
                return
            end
            local oldBid = newBid
            --将小数点替换掉
            newBid = string.gsub(tostring(newBid),"%.", "")
            newBid = tonumber(newBid)
            local Frame1 = ZL.AuctionFrame2.entries[index]
            local bidderlist = fdata.bidderlist
            local baseamount, bidIncrement, tarbidamount = ZL.GetNewBidAmount(index)
            newBid = padZeros(newBid, tarbidamount, bidIncrement, baseamount)
            if ((newBid - baseamount) % bidIncrement) == 0 or ((newBid - (baseamount - (baseamount % bidIncrement))) % bidIncrement) == 0 then --按照加价幅度整数倍出价
                if newBid >= tarbidamount then
                    if isFailedAuction then
                        if PlayerIsML() then
                            --如果存在此流拍物品则先启动拍卖，然后将出价直接添加到数据库里
                            TransmitAddonInfo_Pro()
                            local curAuctionList = ZL_CURRENT.auctionlist[index]
                            if not ZL.IsCanAuction(curAuctionList) then
                                msgStr = curAuctionList.itemlink .. "无法拍卖，原因可能是：已分解或已无法交易"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                return
                            end
                            if not ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                _G["ZL_NewAuctionFrameTab1"]:Click()
                            end
                            local f = AuctionFrame.entries[index]
                            local _bidIncrement = curAuctionList.bidIncrement
                            local startbidamount = curAuctionList.startbidamount
                            if ZL_CURRENT.globalConfig.intervalBidIncrement then
                                if startbidamount < ZL_CURRENT.globalConfig.baseAmount1 then
                                    _bidIncrement = _bidIncrement
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount2 then
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement1, _bidIncrement)
                                elseif startbidamount < ZL_CURRENT.globalConfig.baseAmount3 then
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement2, _bidIncrement)
                                else
                                    _bidIncrement = math.max(ZL_CURRENT.globalConfig.bidIncrement3, _bidIncrement)
                                end
                            end
                            bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount
                            local bindType = curAuctionList.bindType
                            if curAuctionList.itemCount == 1 then
                                if bindType == 2 then
                                    SendChatMessage(("装绑%s开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                else
                                    if curAuctionList.itemlink == "[打包拍卖]" then
                                        local itemList = curAuctionList["itemList"]
                                        if itemList and next(itemList, nil) then
                                            SendChatMessage("打包拍卖清单：", "RAID")
                                            C_Timer.After(0.3, function ()
                                                for _itemlink, data in pairs(itemList) do
                                                    msgStr = _itemlink .. "x" .. data.itemCount
                                                    SendChatMessage(msgStr, "RAID")
                                                end
                                                C_Timer.After(0.3, function ()
                                                    SendChatMessage(("以上%s，起拍价：%d，加价幅度：%d"):format(
                                                        curAuctionList.itemlink, startbidamount, _bidIncrement), ZL.MsgChannel()
                                                    )
                                                end)
                                            end)
                                        else
                                            print(Prefix("没有打包拍卖物品，请先添加！"))
                                            return
                                        end
                                    else
                                        SendChatMessage(("%s开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                            curAuctionList.itemlink, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                        )
                                    end
                                end
                            else
                                if bindType == 2 then
                                    SendChatMessage(("装绑%sx%d，开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, curAuctionList.itemCount, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                else
                                    SendChatMessage(("%sx%d，开始拍卖，当前出价：%s(%dx%d)，加价幅度：%d"):format(
                                        curAuctionList.itemlink, curAuctionList.itemCount, sender, newBid, bidCount, _bidIncrement), ZL.MsgChannel()
                                    )
                                end
                            end
                            --如果是流拍的物品重新拍卖，检测流拍物品是否在流拍包里，如果在移动到其他包里
                            if curAuctionList.state == "failed" and ZL.opt.liupaiToggle and curAuctionList["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 then
                                                --从第一个背包开始查询空闲的格子，如果不是流拍背包，也不是自己拍到的背包，则放进去
                                                local targetBagID, targetslotIndex
                                                for _bagID = 0, NUM_BAG_SLOTS do
                                                    if _bagID ~= ZL.opt.liupaiBagId and (ZL.opt.selfToggle and _bagID ~= ZL.opt.selfBagId) then
                                                        for _slotIndex = 1, C_Container.GetContainerNumSlots(_bagID) do
                                                            local currentInfo = C_Container.GetContainerItemInfo(_bagID, _slotIndex)
                                                            if not currentInfo then
                                                                targetBagID = _bagID
                                                                targetslotIndex = _slotIndex
                                                                break
                                                            end
                                                        end
                                                    end
                                                end
                                                if targetBagID then
                                                    table.insert(itemList, {
                                                        bagID = bagID, slotIndex = slotIndex,
                                                        targetBagID = targetBagID, targetslotIndex = targetslotIndex,
                                                    })
                                                end
                                            end
                                        end
                                    end
                                end

                                if #itemList > 0 then
                                    local __index = 1
                                    local function linshi()
                                        if __index <= #itemList then
                                            C_Container.PickupContainerItem(itemList[__index]["bagID"], itemList[__index]["slotIndex"])
                                            C_Container.PickupContainerItem(itemList[__index]["targetBagID"], itemList[__index]["targetslotIndex"])
                                            __index = __index + 1
                                            C_Timer.After(1, linshi)
                                        end
                                    end
                                    linshi()
                                else
                                    print(Prefix("|cffff0000注意：流拍物品重拍，但没有合适的物品从流拍背包中取出！|r"))
                                end
                            end
                            ZL_CURRENT.auctionlist[index].tradeId = nil
                            ZL_CURRENT.auctionlist[index].startbidamount = startbidamount
                            ZL_CURRENT.auctionlist[index].bidIncrement = _bidIncrement
                            ZL_CURRENT.auctionlist[index].countdownremaining = ZL.opt.auctionTimer
                            ZL_CURRENT.auctionlist[index].auctionTimerRefresh = ZL.opt.auctionTimerRefresh
                            ZL_CURRENT.auctionlist[index].state = "auctioning"
                            ZL_CURRENT.auctionlist[index].isPaused = false
                            ZL_CURRENT.auctionlist[index].bidderlist = {}
                            table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                bidder = GetClassColorName(sender),
                                bidamount = newBid,
                                bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount,
                                time = GetTime()*1000,
                            })
                            local data = {
                                type = "开始拍卖",
                                isRestart = "开始",
                                data2 = ZL_CURRENT.auctionlist[index],
                            }
                            MyAddon:TransmitAddonInfo("AUTOAUC SYNC1", data)
                        end
                    end
                    if ZL_CURRENT.auctionlist[index].countdownremaining > 0 then
                        ZL_CURRENT.auctionlist[index].countdownremaining = fdata.auctionTimerRefresh or 1800--有新的出价，重新更新倒计时
                        Frame1:SetValues(index)
                        if ZL.opt.IsVoiceReminder and (((not ZL_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
                            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 (oldBid == 1 or oldBid == 11 or oldBid == 99) and PlayerIsML() then
                            msgStr = "插件已记录你的竞拍价:" .. newBid .. "g，如需撤销，请【私聊】我回复：撤销"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            return
                        end
                    else
                        if PlayerIsML() and ZL.opt.remindInvalidBid then
                            msgStr = fdata.itemlink .. "拍卖已结束！"
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            return
                        end
                    end
                else
                    if PlayerIsML() then -- and ZL.opt.remindInvalidBid
                        msgStr = ("%s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(fdata.itemlink, tarbidamount)
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        msgStr = ("%s %s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(sender, fdata.itemlink, tarbidamount)
                        SendChatMessage(msgStr, "RAID")
                        return
                    end
                end
            else
                if PlayerIsML() then -- and ZL.opt.remindInvalidBid
                    msgStr = ">>>" .. sender .."<<<出价无效，请按加价幅度(" .. bidIncrement .. ")的整数倍出价"
                    SendChatMessage(msgStr, "RAID")
                    msgStr = "如需竞拍，请按加价幅度(" .. bidIncrement .. ")的整数倍出价，如不需要竞拍忽略这条信息"
                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                    return
                end
            end
        end
    end
    if (event == "CHAT_MSG_WHISPER") and PlayerIsML() then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        local __name = GetClassColorName(sender)
        if msg == "邮寄" then
            if PlayerIsML(sender) then return end
            if (not ZL.mailRegOpen) then
                SendChatMessage("登记邮寄工资窗口已关闭，暂时不接受登记！", "WHISPER", nil, sender)
                return
            end
            if (not ZL_CURRENT["mailPlayers"]) then ZL_CURRENT["mailPlayers"] = {} end
            if (ZL_CURRENT["mailPlayers"][__name] == nil) then
                ZL_CURRENT["mailPlayers"][__name] = false
            end
            SendChatMessage("插件已登记邮寄工资，不可撤销！", "WHISPER", nil, sender)
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            local senderIndex = nil
            local subgroup = nil
            for i = 1, MAX_RAID_MEMBERS do
                local name, _, _subgroup = GetRaidRosterInfo(i)
                if name == sender then
                    senderIndex = i
                    subgroup = _subgroup
                    break
                end
            end
            if senderIndex and (not InCombatLockdown()) and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then
                local mailPlayerList = {__name}
                ZL.ChangePlayerGroup(mailPlayerList)
            end
        elseif msg == "撤销" then
            local num, index = GetAuctioningCount()
            if num == 1 then
                local itemId = ZL_CURRENT.auctionlist[index].itemId
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemId=itemId, itemindex=itemindex, playerName=__name})
            else
                if PlayerIsML() then
                    SendChatMessage("当前存在多个拍卖物品，无法撤销出价！", "WHISPER", nil, sender)
                end
            end
        end
    end
    local function Trade_UpdateMoney()
        if PlayerIsML() then
            ZL.tradeMoneyML = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyOther = GetTargetTradeMoney() / 10000
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradeMoneyOther = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyML = GetTargetTradeMoney() / 10000
        end
    end
    local function Trade_UpdateItemInfo(id)
        local itemLink
        if PlayerIsML() then
            itemLink = GetTradePlayerItemLink(id)
        elseif PlayerIsML(GetUnitName("npc", false)) then
            itemLink = GetTradeTargetItemLink(id)
        end
        if itemLink then
            -- local itemId = tonumber(string.match(itemLink, "|c........|Hitem:(%d+):"))
            ZL.MLTradeItems[id] = itemLink
        end
    end
    if (event == "TRADE_CLOSED") then
		ZL.isTrading = false
        ZL.AuctionRecordFrame:Hide()
        ZL.ShowAuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
	end
	if (event == "TRADE_SHOW") then
		ZL.isTrading = true
		ZL.tradeMoneyML = 0
		ZL.tradeMoneyOther = 0
        ZL.MLTradeItems = {}
        local function PickupContainerItemToTrade(itemGUID, ibag, islot)
            C_Container.PickupContainerItem(ibag, islot)
            for i = 1, 6 do
                local name = GetTradePlayerItemInfo(i)
                if (not name) then
                    ClickTradeButton(i)
                    break
                end
            end
        end
        if PlayerIsML() then
            ZL.tradePartner = GetClassColorName((GetUnitName("npc", true)))
            local playerBuyList = ZL.GetPlayerBuyList()
            local tradeList = {}
            local splitList = {}
            if playerBuyList[ZL.tradePartner] then
                local balanceAmount = 0
                local playerPayToMLamount = 0
                if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                    playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                end
                balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                if balanceAmount < 0 then
                    SendChatMessage("总共请支付：".. -balanceAmount .. "g", "WHISPER", nil, ParseClassColorName(ZL.tradePartner))
                end
                if playerBuyList[ZL.tradePartner]["items"] and #playerBuyList[ZL.tradePartner]["items"] > 0 then
                    ClearCursor()
                    for _, data in ipairs(playerBuyList[ZL.tradePartner]["items"]) do
                        -- local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                        if (not data.isTraded) and data.itemGUID and #data.itemGUID > 0 then
                            local tradeCount = 0
                            for _, itemGUID in ipairs(data.itemGUID) do
                                if not tradeList[itemGUID] then
                                    local bag, slot = ZL.FindItemInBag(itemGUID)
                                    if bag then
                                        local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                                        local isLocked = GetContainerItemInfo["isLocked"]
                                        local isBound = GetContainerItemInfo["isBound"]
                                        local stackCount = GetContainerItemInfo["stackCount"]
                                        if not isLocked then
                                            local isCanTrade
                                            if isBound then
                                                --如果已绑定，检测是否还有剩余交易时间
                                                if (not ZL.ToolTip) then
                                                    ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                                                end
                                                ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                                                ZL.ToolTip:ClearLines()
                                                ZL.ToolTip:SetBagItem(bag, slot)
                                                for i = 1, ZL.ToolTip:NumLines() do
                                                    local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                                                    if text then
                                                        local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                                        if timeRemaining then
                                                            isCanTrade = true
                                                            break
                                                        end
                                                    end
                                                end
                                            else
                                                isCanTrade = true
                                            end
                                            if isCanTrade and tradeCount < data.itemCount then
                                                local splitCount = stackCount - (data.itemCount - tradeCount)
                                                tradeCount = tradeCount + stackCount
                                                tradeList[itemGUID] = {bag=bag, slot=slot}
                                                if splitCount > 0 then
                                                    splitList[itemGUID] = {
                                                        splitCount = splitCount,
                                                        bag = bag,
                                                        slot = slot,
                                                    }
                                                end
                                                if tradeCount >= data.itemCount then
                                                    break
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
                local function trade()
                    if next(tradeList, nil) then
                        local tempList = {}
                        for itemGUID, _ in pairs(tradeList) do
                            table.insert(tempList, itemGUID)
                        end
                        local index = 1
                        local function linshi()
                            if index <= #tempList then
                                local itemGUID = tempList[index]
                                PickupContainerItemToTrade(itemGUID, tradeList[itemGUID].bag, tradeList[itemGUID].slot)
                                index = index + 1
                                C_Timer.After(0.3, linshi)
                            end
                        end
                        linshi()
                    end
                end
                if next(splitList, nil) then
                    local tempList = {}
                    for itemGUID, data in pairs(splitList) do
                        table.insert(tempList, itemGUID)
                    end
                    local index = 1
                    local function split_linshi()
                        if index <= #tempList then
                            local itemGUID = tempList[index]
                            local isfull = true
                            for tarBagID = 0, NUM_BAG_SLOTS do
                                for tarSlotIndex = 1, C_Container.GetContainerNumSlots(tarBagID) do
                                    local currentInfo = C_Container.GetContainerItemInfo(tarBagID, tarSlotIndex)
                                    if not currentInfo then
                                        C_Container.SplitContainerItem(splitList[itemGUID].bag, splitList[itemGUID].slot, splitList[itemGUID].splitCount)
                                        C_Container.PickupContainerItem(tarBagID, tarSlotIndex)
                                        isfull = false
                                        break
                                    end
                                end
                            end
                            if isfull then
                                print(Prefix("注意！注意！背包已满，无法分成目标小堆数量！已移除交易清单"))
                                tradeList[itemGUID] = nil
                            end
                            if index == #tempList then
                                C_Timer.After(1, trade)
                            end
                            index = index + 1
                            C_Timer.After(1, split_linshi)
                        end
                    end
                    split_linshi()
                else
                    trade()
                end
            end
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradePartner = GetClassColorName((GetUnitName("player", true)))
        else
            ZL.tradePartner = nil
        end
        if PlayerIsML() then
            ZL.ShowAuctionRecordFrame:Show()
            ZL.ShowAuctionRecordFrame:ClearAllPoints()
            ZL.ShowAuctionRecordFrame:SetPoint("BOTTOMRIGHT", _G["TradeFrame"], "TOPRIGHT", 20, 0)
            if ZL.opt.ShowAuctionRecordFrameCheckButtonValue then
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["TradeFrame"], "TOPRIGHT")
            end
        end
	end
    if (event == "TRADE_ACCEPT_UPDATE") and ZL.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	end
    if (event == "TRADE_PLAYER_ITEM_CHANGED") then -- and ZL.tradePartner
        Trade_UpdateItemInfo(arg[1])
	end
    if (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	end
	if (event == "TRADE_MONEY_CHANGED") and ZL.tradePartner then
        Trade_UpdateMoney()
	end
    if (event == "UI_INFO_MESSAGE") and PlayerIsML() then
        if arg[2] == ERR_TRADE_COMPLETE and ZL.tradePartner and ZL_CURRENT["IncomeList"] then
            for _, itemlink in ipairs(ZL.MLTradeItems) do
                for index, data in ipairs(ZL_CURRENT["IncomeList"]) do
                    local isTrue
                    if data.itemList and next(data.itemList, nil) then
                        for _itemlink, _data in pairs(data.itemList) do
                            if (not _data.isTraded) and itemlink == _itemlink and data.player == ZL.tradePartner then
                                ZL_CURRENT["IncomeList"][index]["itemList"][itemlink]["isTraded"] = true
                                isTrue = true
                                break
                            end
                        end
                    end
                    if isTrue then break end
                end
            end
            --下面为新增数据库
            if ZL.tradeMoneyOther > 0 then
                if not ZL_CURRENT.playerPayToML then ZL_CURRENT.playerPayToML = {} end
                local oldPayToML = ZL_CURRENT.playerPayToML[ZL.tradePartner] and ZL_CURRENT.playerPayToML[ZL.tradePartner] or 0
                ZL_CURRENT.playerPayToML[ZL.tradePartner] = oldPayToML + ZL.tradeMoneyOther
                ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            end
            ZL.tradePartner = nil
        elseif arg[2] == ERR_MAIL_SENT and ZL.Recipient then --"邮件已发出。"
            ZL.ScrollingMessageFrame:AddMessage("【" .. ZL.Recipient .. "】邮件发送成功！", 1.0, 1.0, 1.0)
            ZL_CURRENT["mailPlayers"][ZL.Recipient] = true
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            ZL.Recipient = nil
		end
	end
    if (event == "UI_ERROR_MESSAGE") and PlayerIsML() then
        --"找不到收件人。" "收件人现在无法收到邮件。" "内部邮件数据库错误" 
        if arg[2] == ERR_MAIL_TARGET_NOT_FOUND or arg[2] == ERR_MAIL_RECEPIENT_CANT_RECEIVE_MAIL or arg[2] == ERR_MAIL_DATABASE_ERROR then
            ZL.Recipient = nil
        elseif arg[2] == ERR_MAIL_REACHED_CAP then --"你已经达到了收取邮件的数量上限"
            ZL.Recipient = nil
            ZL.ScrollingMessageFrame:AddMessage("你已经达到了发送邮件数量上限，已停止邮寄，请过一段时间后重试！", 1, 0, 0)
            ZL.StopSendMail = true
        end
    end
    if (event == "MAIL_CLOSED") and PlayerIsML() then
        ZL.Recipient = nil
    end
    if (event == "MAIL_SHOW") and PlayerIsML() and ZL.GetNeedMailNums() > 0  then
        ZL.Recipient = nil
        local function linshi()
            if (not _G["MailFrame"]) or (not _G["MailFrame"]:IsShown()) then
                C_Timer.After(0.3, linshi)
            else
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["MailFrame"], "TOPRIGHT")
            end
        end
        linshi()
    end
    -- if (event == "MAIL_INBOX_UPDATE") and PlayerIsML() and ZL.GetNeedMailNums() > 0 then

    -- end
    if (event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE") and (arg[1] == Enum.PlayerInteractionType.MailInfo) and PlayerIsML() then
        ZL.AuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
    end
    if (event == "PLAYER_ENTERING_WORLD") then
        TransmitAddonInfo_Pro()
        --切换地图的时候才触发
        if (not arg[1]) and (not arg[2]) then
            local inInstance, instanceType = IsInInstance()
            if inInstance and instanceType == "raid" then
                self:RegisterEvent("UPDATE_INSTANCE_INFO") --当RequestRaidInfo()请求可用时触发
                RequestRaidInfo()
            end
        end
        C_Timer.After(3, function ()
            -- local _, msgStr = CheckWaVersion("[AutoAuction]金团拍卖助手")
            -- if msgStr then
            --     print(ZL.Prefix(msgStr))
            --     ZL.ScrollingMessageFrame:AddMessage(msgStr)
            -- end
            --获取交易剩余时间定时器
            if not ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(2, function ()
                    ZL.GetRemainingTradeTime()
                end)
            end
            --刷新背包物品颜色
            -- if not ZL.UpdateBagHighLight then
            --     ZL.UpdateBagHighLight = C_Timer.NewTicker(2, function ()
            --         ZL.BagHighLight()
            --     end)
            -- end
            --获取ItemGUID定时器
            -- ZL.UpdateGetLootItemGUID =  C_Timer.NewTicker(2, function ()
            --     ZL.GetLootItemGUID()
            -- end)


            -- 保存数据提醒
            if not ZL.UpdateReloadUI then
                ZL.UpdateReloadUI = C_Timer.NewTicker(1, function ()
                    if not PlayerIsML() then return end
                    ZL.reloadUITimerJump = (ZL.reloadUITimerJump or 0) + 1
                    if (not InCombatLockdown()) and ZL.opt.isReloadUI and IsInInstance() and (select(2, IsInInstance()) == "raid")
                    and (((ZL.opt.reloadUITimerJump or 600) - ZL.reloadUITimerJump) < 0) then
                        ZL.reloadUITimerJump = 0
                        if not ZL.ReloadUIFrame then ZL:CreateReloadUIFrame() end
                        ZL.ReloadUIFrame:Show()
                        PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\保存数据.mp3", "Master")
                        C_Timer.After(5, function ()
                            ZL.ReloadUIFrame:Hide()
                        end)
                        if ZL.opt.isSYNCAll and ZL.AuctionFrame2.MLFrame.syncAllBtn:IsEnabled() and GetAuctioningCount() == 0 then
                            ZL.AuctionFrame2.MLFrame.syncAllBtn:Click()
                        end

                    end
                end)
            end

            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 msg = "还未保存团队名单，注意及时保存哦！"
                    ZL.ScrollingMessageFrame:AddMessage(msg)
                    PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\保存团队名单.mp3", "Master")
                end
            end
            -- 保存团队名单提醒
            if not ZL.saveGroupMembers then
                ZL.saveGroupMembers = C_Timer.NewTicker(600, function ()
                    saveGroupMembersTip ()
                end)
            end
        end)
        --请求同步数据
        if arg[1] or arg[2] then
            local delay = 3
            if arg[1] then
                delay = 6
            end
            C_Timer.After(delay, function ()
                if (not PlayerIsML()) and (UnitName("player") ~= ZL_CURRENT.MLname) and IsInRaid() then
                    local msgStr = "已发送同步拍卖数据请求，等待回应..."
                    print(Prefix(msgStr))
                    ZL.ScrollingMessageFrame:AddMessage(msgStr)
                    MyAddon:TransmitAddonInfo2("AUTOAUC REQ", "同步拍卖数据", "WHISPER", GetMLname())
                end
                ZL.GetOwnRolesData()
            end)
            
            C_Timer.After(15, function ()
                C_FriendList.ShowFriends()
                ZL.SyncRoles()
                
                if not ZL.SendStatisticsData then
                    local function SendStatisticsData()
                        local chatType
                        if IsInRaid() then
                            chatType = "RAID"
                        elseif IsInGroup() then
                            chatType = "PARTY"
                        elseif IsInGuild() then
                            chatType = "GUILD"
                        end
                        if chatType and ZL_Statistics and next(ZL_Statistics, nil) then
                            local tempLIst = {}
                            local diff = 30*86400
                            -- local counts = 0
                            for key, data in pairs(ZL_Statistics) do
                                if type(data) == "table" and GetDiffTime(data.auctiondate) <= diff then
                                    tempLIst[key] = data
                                    -- counts = counts + 1
                                end
                            end
                            if next(tempLIst, nil) then
                                -- print("发送了" .. counts .. "个副本记录")
                                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
    end
    if (event == "UPDATE_INSTANCE_INFO") then
        local instanceName, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
        local newCD = true
        for i = 1, GetNumSavedInstances() do
            local _, _, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
            if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                newCD = false
                break
            end
        end
        if newCD then --and ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) and (ZL_CURRENT.instanceID ~= instanceID) and (ZL_CURRENT.difficultyID ~= difficultyID) 
            local msgStr = "已进入一个全新副本【|cffffd100" .. instanceName .. "|r】，请确认是否重置当前拍卖数据？"
            StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
        else
            local todayDate = date("%Y-%m-%d", time())
            if ZL_CURRENT.auctiondate and (((ZL_CURRENT.auctiondate):match("^(.-)%s")) ~= todayDate) then
                local msgStr = "已进入【|cffffd100" .. instanceName .. "|r】副本，当前副本已存在|cffffd100" .. ZL_CURRENT.auctiondate .. "|r拍卖记录，请确认是否重置这个拍卖数据？"
                StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
            end
        end
        self:UnregisterEvent("UPDATE_INSTANCE_INFO")
    end
    if (event == "BAG_UPDATE_DELAYED") then
        if ZL.opt.waitingBagHighLight or ZL.opt.auctioningBagHighLight or ZL.opt.successBagHighLight
        or ZL.opt.failedBagHighLight or ZL.opt.lgnoreBagHighLight then
            ZL.BagHighLight()
        end
    end
    if (event == "BAG_OPEN") then
        ZL.BagHighLight()
    end
    if (event == "PLAYER_REGEN_ENABLED") then
        if ZL.opt.ZLAuctionFrameIsShown then
            ZL.AuctionFrame2:Show()
        end
        if ZL.opt.remainingTradeTimeBtnValue then
            ZL.ZLRemainingTradeTimeFrame:Show()
        end
        if ZL.opt.ItemSettingFrameIsShown then
            ZL.ItemSettingFrame:Show()
        end
        if ZL.opt.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Show()
        end
        if ZL.opt.SettingFrameIsShown then
            ZL.OpenAceConfigDialog("金团拍卖助手")
        end
        if ZL.opt.ZLRolesOverViewFrameIsShown then
            ZL.RolesOverViewFrame:Show()
        end
    end
    if (event == "PLAYER_REGEN_DISABLED") then
        --进入战斗，隐藏窗口
        if ZL.opt.AuctionFrameHide then
            ZL.AuctionFrame2:Hide()
        end
        if ZL.opt.RemainingTradeTimeFrameHide then
            ZL.ZLRemainingTradeTimeFrame:Hide()
        end
        if ZL.opt.ItemSettingFrameHide then
            ZL.ItemSettingFrame:Hide()
        end
        if ZL.opt.AuctionRecordFrameHide then
            ZL.AuctionRecordFrame:Hide()
        end
        if ZL.opt.SettingFrameHide then
            if LibStub("AceConfigDialog-3.0").OpenFrames["金团拍卖助手"] then
                ZL.opt.SettingFrameIsShown = true
                LibStub("AceConfigDialog-3.0"):Close("金团拍卖助手")
            else
                ZL.opt.SettingFrameIsShown = false
            end
        end
        if ZL.glb.RolesOverViewFrameHide then
            ZL.RolesOverViewFrame:Hide()
        end
    end
    if (event == "CHAT_MSG_ADDON") then
        if arg[1] == "WeakAuras" then
            local Compresser = LibStub:GetLibrary("LibCompress")
            local LibDeflate = LibStub:GetLibrary("LibDeflate")
            local Serializer = LibStub:GetLibrary("AceSerializer-3.0")
            local LibSerialize = LibStub("LibSerialize")
            local decodeB64Table = {}
            local string_char = string.char
            local bit_band, bit_lshift, bit_rshift = bit.band, bit.lshift, bit.rshift
            local B64tobyte = {
                a =  0,  b =  1,  c =  2,  d =  3,  e =  4,  f =  5,  g =  6,  h =  7,
                i =  8,  j =  9,  k = 10,  l = 11,  m = 12,  n = 13,  o = 14,  p = 15,
                q = 16,  r = 17,  s = 18,  t = 19,  u = 20,  v = 21,  w = 22,  x = 23,
                y = 24,  z = 25,  A = 26,  B = 27,  C = 28,  D = 29,  E = 30,  F = 31,
                G = 32,  H = 33,  I = 34,  J = 35,  K = 36,  L = 37,  M = 38,  N = 39,
                O = 40,  P = 41,  Q = 42,  R = 43,  S = 44,  T = 45,  U = 46,  V = 47,
                W = 48,  X = 49,  Y = 50,  Z = 51,["0"]=52,["1"]=53,["2"]=54,["3"]=55,
                ["4"]=56,["5"]=57,["6"]=58,["7"]=59,["8"]=60,["9"]=61,["("]=62,[")"]=63
            }
            local bytetoB64 = {
                [0]="a","b","c","d","e","f","g","h",
                "i","j","k","l","m","n","o","p",
                "q","r","s","t","u","v","w","x",
                "y","z","A","B","C","D","E","F",
                "G","H","I","J","K","L","M","N",
                "O","P","Q","R","S","T","U","V",
                "W","X","Y","Z","0","1","2","3",
                "4","5","6","7","8","9","(",")"
            }
            local function decodeB64(str)
                local bit8 = decodeB64Table;
                local decoded_size = 0;
                local ch;
                local i = 1;
                local bitfield_len = 0;
                local bitfield = 0;
                local l = #str;
                while true do
                  if bitfield_len >= 8 then
                    decoded_size = decoded_size + 1;
                    bit8[decoded_size] = string_char(bit_band(bitfield, 255));
                    bitfield = bit_rshift(bitfield, 8);
                    bitfield_len = bitfield_len - 8;
                  end
                  ch = B64tobyte[str:sub(i, i)];
                  bitfield = bitfield + bit_lshift(ch or 0, bitfield_len);
                  bitfield_len = bitfield_len + 6;
                  if i > l then
                    break;
                  end
                  i = i + 1;
                end
                return table.concat(bit8, "", 1, decoded_size)
            end
            local function StringToTable(inString, fromChat)
                local _, _, encodeVersion, encoded = inString:find("^(!WA:%d+!)(.+)$")
                if encodeVersion then
                  encodeVersion = tonumber(encodeVersion:match("%d+"))
                else
                  encoded, encodeVersion = inString:gsub("^%!", "")
                end

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

            for j = 1, wnumPlayers do
                local name, class, rollType, roll, isWinner, isMe = C_LootHistory.GetPlayerInfo(i, j)
                print(name, class, rollType, roll, isWinner, isMe)
            end
        end
    end

    if (event == "LOOT_HISTORY_ROLL_CHANGED") then
        local rollID, itemLink, numPlayers, isDone, winnerIdx, isMasterLoot  = C_LootHistory.GetItem(arg[1])
        print(arg[1], arg[2], rollID, itemLink, numPlayers, isDone, winnerIdx, isMasterLoot)
        if isDone then
            print(itemLink, numPlayers, isDone)
            for j = 1, numPlayers do
                local name, class, rollType, roll, isWinner, isMe = C_LootHistory.GetPlayerInfo(arg[1], j)
                print(name, class, rollType, roll, isWinner, isMe)
            end
        end
    end
]=]
    if event == "CHAT_MSG_SYSTEM" then
        if arg[1] == ERR_FRIEND_NOT_FOUND then
            if ZL.threadId["coroutineIsOnline"] then
                _, ZL.PlayerIsOnline = coroutine.resume(ZL.threadId["coroutineIsOnline"])
                ZL.IsOnlinePlayer = nil
            end
        elseif arg[1] == INSTANCE_SAVED then
            RequestRaidInfo()
            ZL.SyncRoles()
        else
            if ZL.IsOnlinePlayer then
                if format(ERR_FRIEND_ADDED_S, ZL.IsOnlinePlayer) == arg[1] then
                    _, ZL.PlayerIsOnline = coroutine.resume(ZL.threadId["coroutineIsOnline"])
                    -- print(arg[1] .. 11111)
                    ZL.IsOnlinePlayer = nil
                    
                end
            end
        end
    end
    if event == "CHAT_MSG_TRADESKILLS" then
        local _msg = TRADESKILL_LOG_FIRSTPERSON:gsub("%%s", "(.+)")
        if strfind(arg[1], _msg) then
            ZL.SyncRoles()
        end
    end
    if event == "QUEST_TURNED_IN" or event == "PLAYER_MONEY" then
        ZL.SyncRoles()
    end
    if event == "QUEST_WATCH_UPDATE" then
        if IsQuestComplete(arg[1]) then
            ZL.SyncRoles()
        end
    end
    arg:Release()
end

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

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

fZL:SetScript("OnEvent", mainInit)
