local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local pruneCrossRealm = ZL.pruneCrossRealm
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 GetMasterLootCandidates = ZL.GetMasterLootCandidates
local GetClassColorName = ZL.GetClassColorName
local ParseClassColorName = ZL.ParseClassColorName
local GetMLname = ZL.GetMLname
local GetWeekDay = ZL.GetWeekDay
local RGBAToHex = ZL.RGBAToHex
local GetDiffTime = ZL.GetDiffTime
local cGetItemInfo = C_Item and C_Item.GetItemInfo or GetItemInfo
local cGetItemIcon = C_Item and C_Item.GetItemIconByID or GetItemIcon
local GetLootMethod = C_PartyInfo and C_PartyInfo.GetLootMethod or GetLootMethod
local PickupContainerItem = C_Container and C_Container.PickupContainerItem or PickupContainerItem
local goldText = "|A:auctionhouse-icon-coin-gold:0:0|a"
local MyAddon = ZL.MyAddon
local interruptSound

local previousRoster = {} --初始化团队成员
-- 函数：获取当前团队成员列表
local function _GetCurrentRoster()
    local roster = {}
    for i = 1, MAX_RAID_MEMBERS do
        local name = GetRaidRosterInfo(i)
        if name then
            table.insert(roster, ZL.GetFullName(name))
        end
    end
    return roster
end
-- 函数：检测是否有新成员加入
local function CheckForNewMembers()
    local currentRoster = _GetCurrentRoster()
    if next(previousRoster) then
        for _, name in ipairs(currentRoster) do
            if (not previousRoster[name]) then
                -- 新成员加入，发送密语
                if (UnitIsGroupLeader("player") or PlayerIsML()) and (name ~= ZL.GetFullName()) and ZL.opt.welcomeMessageEnable and
                    ZL.opt.MessageString and (#ZL.opt.MessageString > 0) then
                    SendChatMessage(ZL.opt.MessageString, "RAID")
                end
            end
        end
    end
    -- 更新之前的团队成员列表
    previousRoster = {}
    for _, name in ipairs(currentRoster) do
        previousRoster[name] = true
    end
end

local defaults = {
	profile = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 180,
		auctionTimerRefresh = 60,
		manualCountdownTimer = 5,
		startBid = 10000,
		increment = 1000,
        baseAmount1 = 10000,
        baseAmount2 = 500000,
        baseAmount3 = 1000000,
        bidIncrement1 = 10000,
        bidIncrement2 = 50000,
        bidIncrement3 = 100000,
		minQuality = -1,
        lootMinQuality = -1,
		awardToML = false,
		buttonReenableDelay = 1,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = false,
        developerMode = false,
        announceRaidWarning = false,
        CountdownAnnounceRaidWarning = false,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistoryDays = 2,
        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,
        levelSort = false,
        timeSort = "up",
        autoAddStartBid = false,
        AuctionFrameHide = false,
        RemainingTradeTimeFrameHide = true,
        ItemSettingFrameHide = true,
        AuctionRecordFrameHide = true,
        SettingFrameHide = true,
        VoiceReminderSoundType = 1,
        startAuctionSound = true,
        intervalBidIncrement = false,
        maxFrameHide = false,
        bidColumnHide = false,
        startbidColumnHide = false,
        functionColumnHide = false,
        itemLevelHide = false,
        itemCountHide = false,
        itemIndexHide = false,
        itemNameHide = false,
        bidEditBoxHide = false,
        bidBtnHide = false,
        lgnoreBtnHide = true,
        bidCountsHide = false,
        startBidHide = false,
        inrementHide = false,
        startBtnHide = false,
        pauseBtnHide = false,
        countdownBtnHide = false,
        packageBtnHide = false,
        reverseBidBtnHide = false,
        syncBtnHide = false,
        delAuctionBtnHide = false,
        floatBidFrameHide = false,
        floatStartBidFrameHide = false,
        floatFunctionFrameHide = false,
        ShortcutTipHide = false,
        currentDetailToolTipHide = false,
        xiaoFeiToolTipHide = false,
        recordShortcutTipHide = false,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        YYSound = false,
        ZLRolesOverViewFrameScale = 1,
        auctionMode = "团队",
        autoPackage = true,
        quickBidIncrement = 100,
        rollCountDown = 30,
        minIconReloadUI = true,
        popupPriceDelta = 500,
        popupPrice = 500,
        subsidyProfileSelect = 1,
        wagesSubsidyType = 2,
        autoShowAuctionFrame = false,
        autoNoticeFoodInRaid = true,
		ZLTaskFrameScale = 1,
		raidChannel = true,
		whisperChannel = true,
		taskSelectValue = 1,
        DROrderSelect = 1,
        msgChannelTeam = true,
        msgChannelWorld = true,
        whisperLastMinute = 5,
        whisperMessageNumbers = 20,
        taiTanSuiPianCurrency = true,
        AuctionSortLock = true,
        AuctionStartPrice= 99,
        AucitonPriceDown = 1,
        DefaultStackCount = 1,
        defaultStackCountMax = false,
        DefaultNumStacks = 1,
        defaultNumStacksMax = false,
        defaultStackCountOrdefaultNumStacksFirst = 1,
        AuctionPriceSaveDays = 7,
        BuyItemsHistorySaveDays = 28,
        ShowBuyItemsHistorySaveDays = 1,
        AuctionDefaultTime = 1,
        AHPriceChartDays = 7,
        ComeOnVoiceReminderInterval = 60,
        ComeOnVoiceReminderBidAmount = 100000,
        ComeOnVoiceReminderBidIncrement = 50000,
        AutoUpdateWagesBiliByWCL = true,
        InstanceSelectJournalInstanceID = 1307,
        InstanceSelectInstanceID = 2912,
        InstanceSelectInstanceName = "虚影尖塔[英雄]",
        InstanceSelectDifficultyId = 15,
        SelectLootMethod = 1,
        MarsterLootQuality = 3,
        NoticeAveWages = true,
        NoticeTimerJump = 0.5
  	},
    global = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 5,
		startBid = 300,
		increment = 100,
        baseAmount1 = 5000,
        baseAmount2 = 10000,
        baseAmount3 = 50000,
        bidIncrement1 = 500,
        bidIncrement2 = 1000,
        bidIncrement3 = 1000,
		minQuality = -1,
        lootMinQuality = -1,
		awardToML = false,
		buttonReenableDelay = 1,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = false,
        developerMode = false,
        announceRaidWarning = false,
        CountdownAnnounceRaidWarning = false,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        ZLRolesOverViewFrameScale = 1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistoryDays = 1,
        autoClearHistoryIncomeDays = 3,
        showIncomeDays = 3,
        overrideArchive = true,
        profanityFilter = true,
        IsVoiceReminder = true,
        IsTradeRemainingVoiceReminder = true,
        TradeRemainingTimer = 30,
        TradeRemainingReminderPinlv = 5,
        RLBuTieType = 1,
        ZLAuctionFrameTabId = 1,
        showAllWages = false,
        wagesGroupMembers = 0,
        MLChangeGroup = false,
        liupaiToggle = false,
        liupaiBagId = 0,
        liupaiBagId2 = 1,
        liupaiDirection = false,
        selfToggle = false,
        selfBagId = 0,
        selfDirection = false,
        BOEToggle = false,
        BOEBagId = 0,
        BOEDirection = false,
        emptyOneSpace = true,
        isSYNCAll = false,
        waitingBagHighLight = false,
        auctioningBagHighLight = false,
        successBagHighLight = false,
        failedBagHighLight = false,
        lgnoreBagHighLight = false,
        auctionStateTip = true,
        historyMaxAndMin = true,
        levelSort = false,
        timeSort = "up",
        autoAddStartBid = false,
        AuctionFrameHide = false,
        RemainingTradeTimeFrameHide = true,
        ItemSettingFrameHide = true,
        AuctionRecordFrameHide = true,
        SettingFrameHide = true,
        VoiceReminderSoundType = 1,
        startAuctionSound = true,
        intervalBidIncrement = false,
        maxFrameHide = false,
        bidColumnHide = false,
        startbidColumnHide = false,
        functionColumnHide = false,
        itemLevelHide = false,
        itemCountHide = false,
        itemIndexHide = false,
        itemNameHide = false,
        bidEditBoxHide = false,
        bidBtnHide = false,
        lgnoreBtnHide = true,
        bidCountsHide = false,
        startBidHide = false,
        inrementHide = false,
        startBtnHide = false,
        pauseBtnHide = false,
        countdownBtnHide = false,
        packageBtnHide = false,
        reverseBidBtnHide = false,
        syncBtnHide = false,
        delAuctionBtnHide = false,
        floatBidFrameHide = false,
        floatStartBidFrameHide = false,
        floatFunctionFrameHide = false,
        ShortcutTipHide = false,
        currentDetailToolTipHide = false,
        xiaoFeiToolTipHide = false,
        recordShortcutTipHide = false,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        realmName = true,
        unitLevel = true,
        itemLevel = true,
        TOC25 = true,
        TOC10 = true,
        OL25 = true,
        OL10 = true,
        ULD25 = true,
        ULD10 = true,
        VOA25 = true,
        VOA10 = true,
        weekQuest = true,
        heroDayQuest = true,
        taiTanDayQuest = true,
        kaiXuanCurrency = true,
        yingXiongCurrency = true,
        rongYuCurrency = true,
        jinBiCurrency = true,
        RolesOverViewFrameHide = true,
        YYSound = false,
        rollCountDown = 30,
        showItemCounts = true,
        ComeOnVoiceReminderInterval = 60,
	},
}
function ZL:OnProfileEnable()
	ZL.opt = ZL.db.profile
    ZL.glb = ZL.db.global
    TransmitAddonInfo_Pro()
end

local fZL = CreateFrame("Frame")

local filterItemId = {
    {
        ["itemlink"] = "|cffff8000|Hitem:22726::::::::80:::::::::|h[埃提耶什的碎片]|h|r",
        ["auction"] = false,
        ["loot"] = true,
        ["itemId"] = 22726,
    }, -- [1]
    {
        ["itemlink"] = "|cffff8000|Hitem:45038::::::::80:::::::::|h[瓦兰奈尔的碎片]|h|r",
        ["itemId"] = 45038,
        ["auction"] = false,
        ["loot"] = true,
    }, -- [2]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cff0070dd|Hitem:46110::::::::80:::::::::|h[炼金师的宝箱]|h|r",
        ["itemId"] = 46110,
    }, -- [3]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:50274::::::::80:::::::::|h[影霜碎片]|h|r",
        ["itemId"] = 50274,
    }, -- [4]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:18563::::::::80:::::::::|h[逐风者禁锢徽记]|h|r",
        ["itemId"] = 18563,
    }, -- [5]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffff8000|Hitem:18564::::::::80:::::::::|h[逐风者禁锢徽记]|h|r",
        ["itemId"] = 18564,
    }, -- [6]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffa335ee|Hitem:50231::::::::80:::::::::|h[腐面的酸性血液]|h|r",
        ["itemId"] = 50231,
    }, -- [7]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cffa335ee|Hitem:50226::::::::80:::::::::|h[烂肠的酸性血液]|h|r",
        ["itemId"] = 50226,
    }, -- [8]
    {
        ["loot"] = true,
        ["auction"] = false,
        ["itemlink"] = "|cff1eff00|Hitem:52019::::::::80:::::::::|h[小宝的丝带]|h|r",
        ["itemId"] = 52019,
    }, --[9]
}

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

                            end
                        end
                    end
                end
            end
            if yyID and #yyID >= 5 then
                yyID = yyID:gsub("%s", "")
                local link = format("|cffffff00|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "YY号:" .. yyID, "复制YY")
                local text2 = text .. link
                if  #text2 <= 255 then
                    text = text2
                else
                    local isExist = false
                    if #channelBaseName == 0 then
                        isExist = true
                    else
                        for i = 1, NUM_CHAT_WINDOWS do
                            local DefaultChannels = {GetChatWindowChannels(_G["ChatFrame" .. i]:GetID())}
                            for j = 1, #DefaultChannels, 2 do
                                if channelBaseName == DefaultChannels[j] then
                                    isExist = true
                                    break
                                end
                            end
                        end
                    end
                    if isExist and not (ZL.lastFilterText and ZL.lastFilterTime and text == ZL.lastFilterText and (GetTime() - (ZL.lastFilterTime or 0) <= 0.1)) then
                        ZL.lastFilterText = text
                        ZL.lastFilterTime = GetTime()
                        SendSystemMessage(link)
                    end
                end
            end
        elseif event == "CHAT_MSG_WHISPER" then
            local balanceAmount = text:match("^§总共请支付：(%d+)g$")
            if balanceAmount then
                text = text:gsub("§", "") .. format("|cff87CEEB|Hgarrmission:%s:%s:%s:%s|h[%s]|h|r", "AutoAuction", "欠款", balanceAmount, player, "交易")
                ZL.Print(text, true)
                if TradeFrame.NeedTradeMoneyBtn and GetPlayerTradeMoney() ~= (tonumber(balanceAmount) or 0) * 10000 then
                    TradeFrame.NeedTradeMoneyBtn.balanceAmount = (tonumber(balanceAmount) or 0) * 10000
                    TradeFrame.NeedTradeMoneyBtn:SetText(format("请支付:|cffffffff%s|r", ZL.formatNumber((tonumber(balanceAmount) or 0)))) --GetMoneyString((tonumber(balanceAmount) or 0) * 10000)
                    TradeFrame.NeedTradeMoneyBtn:Show()
                end
            end
        end
    end
    return false, text, player, l, cs, t, flag, channelId, channelIndex, channelBaseName, ...
end

ChatFrame_AddMessageEventFilter("CHAT_MSG_CHANNEL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_YELL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_GUILD", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_OFFICER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_WARNING", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_SAY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_SYSTEM", function (self, event, text)
    if event == "CHAT_MSG_SYSTEM" and (text == ERR_CHAT_THROTTLED or text == ERR_NOT_IN_GROUP or strmatch(text, ERR_CHAT_PLAYER_NOT_FOUND_S:gsub("%%s", "(.+)"))) then -- or strmatch(text, ERR_CHAT_PLAYER_NOT_FOUND_S:gsub("%%s", "(.+)"))
        return true
    end
end)

local function getOwnAuctionItemsCount()
    if ((_G["AuctionFrame"] and _G["AuctionFrame"]:IsShown()) or (_G["AuctionHouseFrame"] and _G["AuctionHouseFrame"] :IsShown()))
    and (time() - (ZL.updateOwnAuctionItemsCountTime or 0)) > 0.5 then
        ZL.updateOwnAuctionItemsCountTime = time()
        ZL.opt.OwnAuctionItemsCount = {}
        if ZL.BUILD_DATA >= 5 then
            local ownedAuctions = C_AuctionHouse.GetOwnedAuctions()
            for _, data in ipairs(ownedAuctions) do
                if data.status == 0 then
                    ZL.opt.OwnAuctionItemsCount[data.itemKey.itemID] = (ZL.opt.OwnAuctionItemsCount[data.itemKey.itemID] or 0) + data.quantity
                end
            end
        else
            for index = 1, GetNumAuctionItems("owner") do
                local data = { GetAuctionItemInfo("owner", index) }
                --3:数量；16：1代表已售卖，0代表未售卖；17：物品ID
                if data[16] == 0 then
                    ZL.opt.OwnAuctionItemsCount[data[17]] = (ZL.opt.OwnAuctionItemsCount[data[17]] or 0) + data[3]
                end
            end
        end
    end
end
local function Trade_UpdateMoney()
    if PlayerIsML() then
        ZL.tradeMoneyML = GetPlayerTradeMoney() / 10000
        ZL.tradeMoneyOther = GetTargetTradeMoney() / 10000
    elseif PlayerIsML(GetUnitName("npc", true)) 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", true)) then
        itemLink = GetTradeTargetItemLink(id)
    end
    if itemLink then
        ZL.MLTradeItems[id] = itemLink
    end
end
local tradeFailed = {
    ERR_TRADE_BAG,--"你不能交易装有物品的包";
    ERR_TRADE_BAG_FULL,--"交易失败，你没有足够的物品栏空间。";
    ERR_TRADE_BLOCKED_S,--"%s要求进行交易，你拒绝了。";
    ERR_TRADE_BOUND_ITEM,--"你不能交易一件灵魂绑定物品";
    ERR_TRADE_CANCELLED,--"交易取消。";
    ERR_TRADE_EQUIPPED_BAG,--"你无法交易已经装备的包裹。";
    ERR_TRADE_FACTION_SPECIFIC,--"你无法与对立阵营交易阵营特色物品。";
    ERR_TRADE_GROUND_ITEM,--"你不能交易一件还放在地上的物品。";
    ERR_TRADE_MAX_COUNT_EXCEEDED,--"你拥有超过一件";
    ERR_TRADE_NOT_ON_TAPLIST,--"你只能将绑定物品交易给拥有该物品起始拾取资格的玩家。";
    ERR_TRADE_QUEST_ITEM,--"你不能交易一件任务物品";
    ERR_TRADE_REQUEST_S,--"%s想要和你进行交易。";
    ERR_TRADE_SELF,--"你不能与自己交易。";
    ERR_TRADE_TARGET_BAG_FULL,--"交易失败，交易目标没有足够的物品栏空间。";
    ERR_TRADE_TARGET_DEAD,--"你不能和已死亡的玩家交易";
    ERR_TRADE_TARGET_MAX_COUNT_EXCEEDED,--"交易对象已经拥有该类唯一物品。";
    ERR_TRADE_TARGET_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS,--"你的交易对象只能携带%d个%s";
    ERR_TRADE_TEMP_ENCHANT_BOUND,--"你不能交易带有临时附魔的物品。";
    ERR_TRADE_TOO_FAR,--"交易目标太远";
    ERR_TRADE_WRONG_REALM,--"你只能与来自其它服务器的玩家交易魔法制造的物品";
}
function ZL.isTradeFailed(arg2)
    for _,v in ipairs(tradeFailed) do
        if strmatch(arg2, v:gsub("%%s", "(.+)"):gsub("%%d", "(.+)")) then
            return true
        end
    end
    return false
end
local isTradeFailed = ZL.isTradeFailed

local function historyData(self)
    if not (self == GameTooltip or self == ItemRefTooltip) then
        return
    end
    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
    if ZL.opt.showItemCounts then
        local inventoryCount, bagCount, itemBankCount, itemTotalCount = ZL.GetItemNumbers(itemId)
        local auctionCount = ZL.opt.OwnAuctionItemsCount and (ZL.opt.OwnAuctionItemsCount[itemId] or 0) or 0
        itemTotalCount = itemTotalCount + auctionCount
        local txt = ""
        if inventoryCount > 0 then
            txt = "装备: |cffffffff" .. inventoryCount .. "|r "
        end
        if bagCount > 0 then
            txt = txt .. "背包: |cffffffff" .. bagCount .. "|r "
        end
        if itemBankCount > 0 then
            txt = txt .. "银行: |cffffffff" .. itemBankCount .. "|r "
        end
        if auctionCount > 0 then
            txt = txt .. "拍卖: |cffffffff" .. auctionCount .. "|r "
        end
        if itemTotalCount > 0 then
            txt = txt .. "|cff03CCFF合计: |r|cffffffff" .. itemTotalCount .. "|r"
            GameTooltip:AddLine(txt)
        end
    end
end
local function mainInit(self, event, ...)
    local arg = emptytable(...)
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        local function OnHyperlinkEnter(self, link)
            local linkType, missionID, txt = strsplit(":", link)
            if linkType == "item" then
                -- 在这里可以显示自定义的悬浮提示框
                -- GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                -- GameTooltip:AddLine("玩家: " .. missionID)
                -- GameTooltip:Show()

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

        local function OnHyperlinkLeave()
            GameTooltip:Hide()
        end

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

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

        ZL_CURRENT = ZL_CURRENT or {}
        ZL_PLAYERLIST = ZL_PLAYERLIST or {}
        ZL_HISTORY = ZL_HISTORY or {}
        RolesOverView = RolesOverView or {
            owner = {},
            sync = {},
            syncKey = {},
            BNChildNewName = {},
            syncKeyUnBind = {},
        }

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

        ZL.opt = ZL.db.profile
        ZL.glb = ZL.db.global
        ZL.opt.WCLSetting = ZL.opt.WCLSetting or {
            {
                sorceMin = 100,
                sorceMax = 200000,
                sorceText = "|cffFFD700s≥100|r",
                wagesBili = 200,
            },
            {
                sorceMin = 99,
                sorceMax = 100,
                -- sorceText = "|cffFF69B499|r",
                sorceText = "|cffFF69B499≤s<100|r",
                wagesBili = 200,
            },
            {
                sorceMin = 95,
                sorceMax = 99,
                -- sorceText = "|cffFF8C0095 - 98|r",
                sorceText = "|cffFF8C0095≤s<99|r",
                wagesBili = 200,
            },
            {
                sorceMin = 75,
                sorceMax = 95,
                -- sorceText = "|cff80008075 - 94|r",
                sorceText = "|cff80008075≤s<95|r",
                wagesBili = 150,
            },
            {
                sorceMin = 50,
                sorceMax = 75,
                -- sorceText = "|cff0096FF50 - 74|r",
                sorceText = "|cff0096FF50≤s<75|r",
                wagesBili = 100,
            },
            {
                sorceMin = 25,
                sorceMax = 50,
                -- sorceText = "|cff00960025 - 49|r",
                sorceText = "|cff00960025≤s<50|r",
                wagesBili = 50,
            },
            {
                sorceMin = -200000,
                sorceMax = 25,
                sorceText = "|cff808080s<25|r",
                wagesBili = 0,
            },
        }
        if ZL.opt.WCLSetting[2].sorceMax == 99 then
            ZL.opt.WCLSetting[1].sorceText = "|cffFFD700s≥100|r"
            ZL.opt.WCLSetting[2].sorceMax = 100
            ZL.opt.WCLSetting[2].sorceText = "|cffFF69B499≤s<100|r"
            ZL.opt.WCLSetting[3].sorceMax = 99
            ZL.opt.WCLSetting[3].sorceText = "|cffFF8C0095≤s<99|r"
            ZL.opt.WCLSetting[4].sorceMax = 95
            ZL.opt.WCLSetting[4].sorceText = "|cff80008075≤s<95|r"
            ZL.opt.WCLSetting[5].sorceMax = 75
            ZL.opt.WCLSetting[5].sorceText = "|cff0096FF50≤s<75|r"
            ZL.opt.WCLSetting[6].sorceMax = 50
            ZL.opt.WCLSetting[6].sorceText = "|cff00960025≤s<50|r"
            ZL.opt.WCLSetting[7].sorceMax = 25
            ZL.opt.WCLSetting[7].sorceText = "|cff808080s<25|r"
        end
        ZL.options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(ZL.db)
		ZL.options.args.profiles.order = -1
		LibStub("AceConfig-3.0"):RegisterOptionsTable("金团拍卖助手", ZL.options)
        LibStub("AceConfigDialog-3.0"):SetDefaultSize("金团拍卖助手", 700, 500)
        --将选项表添加到暴雪的内置“界面”选项面板中
        LibStub("AceConfigDialog-3.0"):AddToBlizOptions("金团拍卖助手", "|cffffffffAutoAuction|r")
        --Minimap Icon Creation
		ZL.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = ZL.LogoPath,
			OnClick = function(self, button)
                if button == "LeftButton" then
                    if IsShiftKeyDown() then
                        if ZL.opt.minIconReloadUI then
                            ReloadUI()
                        end
                    else
                        if ZL.AuctionFrame2:IsShown() then
                            ZL.AuctionFrame2:Hide()
                            ZL.opt.ZLAuctionFrameIsShown = false
                        else
                            ZL.AuctionFrame2:Show()
                            ZL.opt.ZLAuctionFrameIsShown = true
                        end
                    end
                elseif button == "RightButton" then
                    ZL.OpenAceConfigDialog("金团拍卖助手")
                end
			end,
		})
        
        function ZL.LDB:OnTooltipShow()
            if not ZL.opt.minIconTooltipHide then
                self:AddLine("AutoAuction[金团拍卖助手AA](|cffffffff" .. ZL.addonVersion .. "|r)")
                self:AddLine("支持金团自动化拍卖、出价、记账、工资分配、离队计算工资等", 1, 1, 1, true)
                self:AddLine(" ")
                self:AddLine("左键|cffffffff: 打开/关闭拍卖清单窗口|r ")
                if ZL.opt.minIconReloadUI then
                    self:AddLine("Shift+左键：|cffffffff重新加载用户界面|r")
                end
                self:AddLine("右键|cffffffff: 打开配置窗口|r ")
            end
        end
        function ZL.LDB:OnEnter()
            ZL.LDB.OnTooltipShow(GameTooltip)
            GameTooltip:Show()
        end
        function ZL.LDB:OnLeave()
            GameTooltip:Hide()
        end

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

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

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

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

        -- TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Item, historyData)

        _G["TradeFrame"]:HookScript("OnShow", function(self)
            if IsInRaid(1) then
                local ShowAuctionRecordFrame = ZL.ShowAuctionRecordFrame
                ShowAuctionRecordFrame:ClearAllPoints()
                ShowAuctionRecordFrame:SetPoint("BOTTOMRIGHT", _G["TradeFrame"], "TOPRIGHT", 20, 0)
                ShowAuctionRecordFrame:Show()
            end
        end)
        _G["TradeFrame"]:HookScript("OnHide", function (self)
            ZL.ShowAuctionRecordFrame:Hide()
        end)

        ZL.opt.ZLAuctionRecordFrameIsShown = false
        ZL.SoundType = ZL.SoundTypeList[ZL.opt.VoiceReminderSoundType or 1] or "甜美女声"        --CTR+右键点击物品链接自动创建拍卖物品
        local function SetItemRefActivityMenu(itemLink)
            local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
            local _, _, _, _, _, _, _, stackCount = cGetItemInfo(itemLink)
            local menuList = {}
            local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
            selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
            if IsInRaid(1) then
                if PlayerIsML() then
                    local isExist
                    tinsert(menuList, {
                        text = "拍卖功能",
                        isTitle = true,
                    })
                    if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                        for index, data in ipairs(ZL_CURRENT.auctionlist) do
                            if data.itemlink == itemLink then
                                local f = ZL.AuctionFrame2.entries[index]
                                local text
                                if (data.state == "failed" or data.state == "waiting") then
                                    text = "|T130866:18:18:2:0|t 开始"
                                elseif data.state == "auctioning" then
                                    text = "|T137048:18:18:2:0|t 取消"
                                elseif data.state == "success" then
                                    text = "|T130866:18:18:2:0|t 重拍"
                                end
                                if text then
                                    tinsert(menuList, {
                                        text = text,
                                        func = function ()
                                            f.MLframe.functionFrame.CancelBtn:Click()
                                        end
                                    })
                                end
                                if data.state == "auctioning" then
                                    tinsert(menuList, {
                                        text = "|TInterface\\AddOns\\AutoAuction\\Images\\5countdown_normal.png:18:18:2:2|t 5秒倒数",
                                        func = function ()
                                            f.MLframe.functionFrame.CountDownBtn:Click()
                                        end
                                    })
                                end
                                if (data.state == "failed" or data.state == "waiting") then
                                    tinsert(menuList, {
                                        text = "|T384756:18:18:2:0|t 快速拍卖",
                                        func = function ()
                                            local _data = {
                                                ["type"] = "指定人员",
                                                ["data"] = data,
                                                ["index"] = index,
                                            }
                                            StaticPopup_Show("ZL_ADDINCOME", "收入", nil, _data, ZL.AddIncomeEditboxs)
                                        end
                                    })
                                end
                                isExist = true
                                break
                            end
                        end
                    end
                    if not isExist then
                        tinsert(menuList, {
                            text = "|TInterface\\AddOns\\" .. addonName .. "\\Images\\new.png:18:18:2:0|t " .. "创建拍卖",
                            func = function ()
                                if stackCount == 1 then
                                    ZL.ManualCreateAuctionItem(itemLink, 1)
                                else
                                    StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=nil}, ZL.AddAuctionEditboxs)
                                end
                            end
                        })
                    end
                    tinsert(menuList, {isSeparator = true})
                else
                    table.insert(menuList, {
                        text = "快速记账",
                        func = function ()
                            --快速记账
                            if not ZL.QuickRecordFrame then ZL:CreateQuickRecordFrame() end
                            local  isExist
                            if ZL_PLAYERLIST.lootList then
                                for _bossName, bossNameData in pairs(ZL_PLAYERLIST.lootList) do
                                    if type(bossNameData) == "table" then
                                        for _itemLink, itemLinkData in pairs(bossNameData) do
                                            if _itemLink == itemLink and itemLinkData["拾取1"]["counts"] > 0 then
                                                ZL.QuickRecordFrame.bossName = _bossName
                                                isExist = true
                                                break
                                            end
                                        end
                                        if isExist then break end
                                    end
                                end
                            end
                            if isExist then
                                ZL.QuickRecordFrame:Update(itemLink)
                                ZL.QuickRecordFrame:ClearAllPoints()
                                local uiScale, mX, mY = UIParent:GetEffectiveScale(), GetCursorPosition()
                                mX, mY = mX/uiScale, mY/uiScale
                                local screenWidth = GetScreenWidth() / 2
                                if mX < screenWidth then
                                    ZL.QuickRecordFrame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", mX+30, mY+30)
                                else
                                    ZL.QuickRecordFrame:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", mX-30, mY+30)
                                end
                                ZL.QuickRecordFrame:Show()
                            else
                                local msgStr = "拾取记录不存在或已记录！"
                                ZL.Print(msgStr, true, nil, 1, 0, 0)
                            end
                        end
                    })
                    tinsert(menuList, {isSeparator = true})
                end
            end
            
            if selectCharKey and (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
            (not ZL.opt.concernList[selectCharKey]["itemList"][itemId]) then
                tinsert(menuList, {
                    text = "|A:auctionhouse-icon-favorite:18:18:2:2|a " .. "关注",
                    func = function ()
                        ZL.addItem(itemId)
                    end,
                })
            else
                tinsert(menuList, {
                    text = "|A:auctionhouse-icon-favorite-off:18:18:2:2|a " .. "取消关注",
                    func = function ()
                        ZL.deleteItem(itemId)
                    end
                })
            end
            return menuList
        end
        --CTR+左键点击物品链接流拍物品自动开始拍卖
        hooksecurefunc("SetItemRef", function(link, _, button)
            local linkType, missionID, txt, arg4, arg5 = strsplit(":", link)
            if linkType == "garrmission" then
                if missionID == "AutoAuction" then
                    if txt == "账单" then
                        ZL.BillOverviewFrame:Update()
                        ZL.BillOverviewFrame:Show()
                        ZL.ReconciliationFrame:Hide()
                    elseif txt == "对账" then
                        if ZL.ReconciliationFrame:IsShown() then
                            ZL.ReconciliationFrame:Update()
                        else
                            ZL.ReconciliationFrame:Show()
                        end
                        ZL.BillOverviewFrame:Hide()
                    elseif txt == "YY号" and arg4 then
                        ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
                        ChatEdit_ChooseBoxForSend():SetText(arg4)
                        ChatEdit_ChooseBoxForSend():HighlightText()
                    elseif txt == "通报详细收支" then
                        ZL.reportIncomeConfirm()
                    elseif txt == "保存团员名单" then
                        ZL.saveGroupMembers()
                    elseif txt == "设置多拍" then
                        ZL.opt.allowMultipleAuctions = true
                        TransmitAddonInfo_Pro()
                        C_Timer.NewTicker(0.2, function (self)
                            if ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                self:Cancel()
                                local _link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "设置单拍", "改为单拍")
                                local msg = "已切换为|cffffffff多拍模式|r "
                                ZL.Print(msg .. _link, true)
                                ZL.SpeakText(msg)
                            end
                        end)
                    elseif txt == "设置单拍" then
                        ZL.opt.allowMultipleAuctions = false
                        TransmitAddonInfo_Pro()
                        C_Timer.NewTicker(0.2, function (self)
                            if not ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                self:Cancel()
                                local _link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "设置多拍", "设置多拍")
                                local msg = "已切换为|cffffffff单拍模式|r "
                                ZL.Print(msg .. _link, true)
                                ZL.SpeakText(msg)
                            end
                        end)
                    elseif txt == "历史记录" then
                        ZL.AuctionRecordFrame:Show()
                        _G["ZLAuctionRecordFrameTab1"]:Click()
                    elseif txt == "欠款" then
                        if arg4 and arg5 then
                            if GetMoney() < (tonumber(arg4) or 0)*10000 then
                                ZL.Print("金币不足，无法支付！")
                                return
                            end
                            local hasOpenTrade, hasCloseTrade
                            local function startTrade()
                                if TradeFrame and TradeFrame:IsShown() then
                                    if not hasCloseTrade and not hasOpenTrade then
                                        TradeFrame:Hide()
                                        hasCloseTrade = true
                                        C_Timer.After(0.3, startTrade)
                                    end
                                    if hasOpenTrade then
                                        ClickTradeButton(1)
                                        C_Timer.After(0.3, function ()
                                            AcceptTrade()
                                        end)
                                    end
                                else
                                    if not hasOpenTrade then
                                        PickupPlayerMoney((tonumber(arg4) or 0)*10000)
                                        InitiateTrade(ZL.pruneCrossRealm(arg5))
                                        hasOpenTrade = true
                                    end
                                    C_Timer.After(0.1, startTrade)
                                end
                            end
                            startTrade()
                        end
                    elseif txt == "ads" then
                        ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
                        ChatEdit_InsertLink("https://dydy.site/")
                        ChatEdit_ChooseBoxForSend():HighlightText()
                    end
                end
            elseif linkType == "item" then
                local _, itemLink = cGetItemInfo(link)
                if not itemLink then return end
                local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
                if button == "RightButton" then
                    if ItemRefTooltip:IsVisible() then
                        ItemRefTooltip:Hide()
                    end
                    if (not IsModifierKeyDown()) then
                        ZL.GUI:ToggleMenu(self, SetItemRefActivityMenu(itemLink), 'cursor2')
                    elseif (not IsShiftKeyDown()) and (not IsControlKeyDown()) and IsAltKeyDown() then
                        local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
                        selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
                        if selectCharKey and (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
                        (not ZL.opt.concernList[selectCharKey]["itemList"][itemId]) then
                            ZL.addItem(itemId)
                        else
                            ZL.deleteItem(itemId)
                        end
                    end
                elseif button == "LeftButton" then
                    if IsShiftKeyDown() and (not IsControlKeyDown()) and (not IsAltKeyDown()) then
                        local edite = GetCurrentKeyBoardFocus()
                        if edite then
                            if ZL.AddAuctionEditboxs and edite == ZL.AddAuctionEditboxs.editBox5 then
                                edite:SetText(itemId)
                            else
                                edite:SetText(itemLink)
                            end
                        end
                    end
                end
            end
        end)
        --CTR+右键点击背包物品自动创建拍卖物品
        local function hookContainerFrameItemButton_OnModifiedClick(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            local itemLink = containerInfo.hyperlink
            local itemId = containerInfo.itemID
            if PlayerIsML() and IsInRaid(1) and button == "RightButton" and IsControlKeyDown() then
                local itemLoc = ItemLocation:CreateFromBagAndSlot(self:GetParent():GetID(), self:GetID())
                local itemGuid = C_Item.GetItemGUID(itemLoc)
                if (not ZL_CURRENT["itemGUIDUsed"]) or (not ZL_CURRENT["itemGUIDUsed"][itemGuid]) then
                    if not ZL_CURRENT["itemGUIDUsed"] then ZL_CURRENT["itemGUIDUsed"] = {} end
                    local stackCount = select(8, cGetItemInfo(itemLink))
                    if stackCount == 1 then
                        ZL.ManualCreateAuctionItem(itemLink, 1, itemGuid)
                    else
                        StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=itemGuid}, ZL.AddAuctionEditboxs)
                    end
                else
                    ZL.Print("注意：" .. itemLink .. "已存在，请勿重复创建！", true)
                end
                itemLoc:Clear()
                return
            end
            local edite = GetCurrentKeyBoardFocus()
            if edite and IsShiftKeyDown() and button == "LeftButton" and _G["AuctionFrame"] and _G["AuctionFrame"]:IsShown() then
                if ZL.AddAuctionEditboxs and edite == ZL.AddAuctionEditboxs.editBox5 then
                    edite:SetText(itemId)
                    if StackSplitFrame and StackSplitFrame:IsShown() then
                        StackSplitFrame:Hide()
                    end
                else
                    edite:SetText(itemLink)
                end
            end
        end
        if ZL.BUILD_DATA < 10 then
            hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", hookContainerFrameItemButton_OnModifiedClick)
        else
            hooksecurefunc(ContainerFrameItemButtonMixin, "OnModifiedClick", hookContainerFrameItemButton_OnModifiedClick)
        end

        --增加鼠标提示信息
        hooksecurefunc(GameTooltip, "SetBagItem", function(self, bag, slot)
            if not ZL.opt.auctionStateTip then return end
            local itemLocation
            itemLocation = ItemLocation:CreateFromBagAndSlot(bag, slot)
            if C_Item.DoesItemExist(itemLocation) then
                local itemGuid = C_Item.GetItemGUID(itemLocation)
                if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                    for _, data in ipairs(ZL_CURRENT.auctionlist) do
                        if data["spawnUID"] and next(data["spawnUID"], nil) then
                            for _, _value in pairs(data["spawnUID"]) do
                                if _value["itemGUID"] and next(_value["itemGUID"], nil) then
                                    for key, value in pairs(_value["itemGUID"]) do
                                        if key == itemGuid then
                                            local r, g, b, a = unpack(ZL.colorList[data.state])
                                            r, g, b = r*255, g*255, b*255
                                            local str
                                            if data.state == "waiting" then
                                                str = ZL.RGBAToHex(r, g, b, a) .. "待拍卖" .. "|r"
                                            elseif data.state == "auctioning" then
                                                str = ZL.RGBAToHex(r, g, b, a) .. "拍卖中" .. "|r"
                                            elseif data.state == "success" then
                                                if value.isUsed then
                                                    str = ZL.RGBAToHex(r, g, b, a) .. "拍卖成功" .. "|r，|cffffffff获胜者：|r" .. value.isUsed
                                                else
                                                    str = ZL.RGBAToHex(r, g, b, a) .. "拍卖成功"
                                                end
                                            elseif data.state == "failed" then
                                                str = ZL.RGBAToHex(r, g, b, a) .. "流拍" .. "|r"
                                            end
                                            if str then
                                                self:AddLine("|T" .. ZL.LogoPath .. ":12|t " .. str)
                                                self:Show()
                                            end
                                            return
                                        end
                                    end
                                end
                            end

                        end
                    end
                end
            end
            itemLocation:Clear()
            itemLocation = nil
        end)

        --人物右键菜单
        do
            local __poplib = __ala_meta__.__poplib
            local function addEntry(funcName)
                __poplib:AddEntry("SELF", funcName);
                __poplib:AddEntry("_BRFF_SELF", funcName);
                __poplib:AddEntry("PLAYER", funcName);
                __poplib:AddEntry("FRIEND", funcName);
                __poplib:AddEntry("FRIEND_OFFLINE", funcName);
                __poplib:AddEntry("PARTY", funcName);
                __poplib:AddEntry("_BRFF_PARTY", funcName);
                __poplib:AddEntry("RAID", funcName);
                __poplib:AddEntry("RAID_PLAYER", funcName);
                __poplib:AddEntry("_BRFF_RAID_PLAYER", funcName);
                __poplib:AddEntry("CHAT_ROSTER", funcName);
            end
            __poplib:AddMethod("SET_LOOTMASTER", {
                GetText = function() return "指定为物品分配者"; end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if IsInRaid(1) and UnitIsGroupLeader("player", 1) then
                        local name = ZL.GetFullName(context.name, context.server)
                        name = ZL.pruneCrossRealm(name)
                        local playIsInRaid
                        for i = 1, MAX_RAID_MEMBERS do
                            local _name = GetRaidRosterInfo(i)
                            if _name and _name == name then
                                playIsInRaid = i
                                break
                            end
                        end
                        if playIsInRaid then
                            local lootMethod, _, raidMaster = GetLootMethod()
                            if (lootMethod == 2 or lootMethod == "master") and playIsInRaid ~= raidMaster then
                                return true
                            else
                                return
                            end
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    local name = ZL.GetFullName(context.name, context.server)
                    name = ZL.pruneCrossRealm(name)
                    if SetLootMethod then
                        SetLootMethod("master", name)
                    else
                        C_PartyInfo.SetLootMethod(2, name)
                    end
                end,
                category = "AutoAuction",
            });
            addEntry("SET_LOOTMASTER")
            __poplib:AddMethod("ADD_FINE", {
                GetText = function() return "添加罚款"; end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if PlayerIsML() and IsInRaid(1) then
                        local name = ZL.GetFullName(context.name, context.server)
                        name = ZL.pruneCrossRealm(name)
                        local playIsInRaid
                        for i = 1, MAX_RAID_MEMBERS do
                            local _name = GetRaidRosterInfo(i)
                            if _name and _name == name then
                                playIsInRaid = true
                                break
                            end
                        end
                        if playIsInRaid then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    local data = {
                        ["type"] = "罚款",
                        ["name"] = ZL.GetClassColorName(ZL.GetFullName(context.name, context.server)),
                        ["title"] = "罚款",
                        ["amount"] = ZL.opt.popupPrice,
                    }
                    StaticPopup_Show("ZL_ADDINCOME", "收入", nil, data, ZL.AddIncomeEditboxs)
                end,
                category = "AutoAuction",
            });
            addEntry("ADD_FINE")
            __poplib:AddMethod("SET_BOSS", {
                GetText = function(def, context)
                    local name = ZL.GetFullName(context.name, context.server)
                    -- name = ZL.pruneCrossRealm(name)
                    local className = GetClassColorName(name)
                    if ZL_CURRENT.WagesBiLi and ZL_CURRENT.WagesBiLi[className] and
                    ZL_CURRENT.WagesBiLi[className]["biLi"] and ZL_CURRENT.WagesBiLi[className]["biLi"] == 0 then
                        return "|T130751:18:18:0:0|t " .. "老板"  --是老板
                    else
                        return "|T130755:18:18:0:0|t " .. "老板"  --不是老板
                    end
                end,
                IsShown = function(def, context)
                    if not context.name then return end
                    if PlayerIsML() and IsInRaid(1) then
                        local name = ZL.GetFullName(context.name, context.server)
                        name = ZL.pruneCrossRealm(name)
                        local playIsInRaid
                        for i = 1, MAX_RAID_MEMBERS do
                            local _name = GetRaidRosterInfo(i)
                            if _name and _name == name then
                                playIsInRaid = true
                                break
                            end
                        end
                        if playIsInRaid then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    local name = ZL.GetFullName(context.name, context.server)
                    local colorName = GetClassColorName(name)
                    if not ZL_CURRENT.WagesBiLi then ZL_CURRENT.WagesBiLi = {} end
                    if ZL_CURRENT.WagesBiLi and ZL_CURRENT.WagesBiLi[colorName] and
                    ZL_CURRENT.WagesBiLi[colorName]["biLi"] and ZL_CURRENT.WagesBiLi[colorName]["biLi"] == 0 then
                        ZL_CURRENT.WagesBiLi[colorName]["biLi"] = 100
                        ZL.Print(colorName .. "已取消老板，将参与工资计算！", true)
                    else
                        if not ZL_CURRENT.WagesBiLi[colorName] then
                            ZL_CURRENT.WagesBiLi[colorName] = {}
                        end
                        ZL_CURRENT.WagesBiLi[colorName]["biLi"] = 0
                        ZL.Print(colorName .. "已设置为老板，不参与工资计算！", true)
                    end
                    if ZL.AuctionRecordFrame.playerBalanceFrame:IsShown() then
                        ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                    end
                end,
                category = "AutoAuction",
            });
            addEntry("SET_BOSS")

            __poplib:AddMethod("SET_APPOINTMLNAME", {
                GetText = function(def, context)
                    if ZL.opt.appointMLName and ZL.opt.appointMLName == ZL.GetFullName(context.name, context.server) then
                        return "|T130751:18:18:0:0|t " .. "指定拍卖人"  --是
                    else
                        return "|T130755:18:18:0:0|t " .. "指定拍卖人"  --不是
                    end
                end,
                IsShown = function(def, context)
                    if not context.name then return end
                    local name = ZL.GetFullName(context.name, context.server)
                    name = ZL.pruneCrossRealm(name)
                    if IsInRaid(1) and UnitIsGroupLeader("player") and UnitInRaid(name) then
                        local lootMethod = GetLootMethod()
                        if (lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                            return true
                        else
                            return
                        end
                    else
                        return
                    end
                end,
                OnClick = function(def, which, context)
                    MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.GetFullName(context.name, context.server), notice=true})
                end,
                category = "AutoAuction",
            });
            addEntry("SET_APPOINTMLNAME")
        end
    elseif event == "PLAYER_LOGIN" then
        local link = format("|cff87CEEB|Hgarrmission:%s:%s|h[%s]|h|r", "AutoAuction", "ads", "张大爷金团")
        ZL.Print(link .. "欢迎>>>" .. GetClassColorName(UnitName("player")) .."<<<回来 ，界面呼出：|cffffffff/aa|r", true, true)
        if not ZL.AuctionFrame2 then ZL:CreateAuctionFrame2() end
        if not ZL.AuctionRecordFrame then ZL:CreateAuctionRecordFrame() end
        if not ZL.FloatAuctionFrame then ZL:CreateFloatAuctionFrame() end
        if not ZL.ItemSettingFrame then ZL:CreateItemSettingFrame() end

        if not ZL.ZLRemainingTradeTimeFrame then ZL:CreateZLRemainingTradeTimeFrame() end
        if not ZL.ShowAuctionRecordFrame then ZL:CreateShowAuctionRecordFrame() end
        if not ZL.BidderListFrame then ZL:CreateBidderListFrame() end
        if not ZL.PackageListFrame then ZL:CreatePackageListFrame() end
        if not ZL.ScrollingMessageFrame then ZL:CreateScrollingMessageFrame() end

        if not ZL.GroupMembersDropdown then ZL.CreateGroupMembersDropdown() end
        if not ZL.AddIncomeEditboxs then ZL.CreateStaticPopupAddIncomeEditboxs() end
        if not ZL.AddAuctionEditboxs then ZL.CreateStaticPopupAddAuctionEditboxs() end
        if not ZL.QuickRecordFrame then ZL:CreateQuickRecordFrame() end
        if not ZL.BuyItemsFrame then ZL:CreateBuyItemsFrame() end
        
        if not ZL.ConcernFrame then ZL:CreateConcernFrame() end
        if not ZL.SubsidyFrame then ZL:CreateSubsidyFrame() end

        local tabId = abs(ZL.opt.ZLAuctionFrameTabId)
        _G["ZL_NewAuctionFrameTab0"]:Click()
        local AuctionFrame = ZL.AuctionFrame2
        AuctionFrame:SetWidth(AuctionFrame:GetWidth()+0.5)
        C_Timer.After(0.5, function ()
            AuctionFrame:SetWidth(AuctionFrame:GetWidth()-0.5)
        end)
        _G["ZL_NewAuctionFrameTab" .. tabId]:Click()

        --检测老板本数据库历史数据是否有缺少日期的，如果有缺少赋值为"1970-01-01 00:01"
        if ZL_HISTORY and #ZL_HISTORY > 0 then
            --删除历史数据
            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
        ZL.opt.playerInfo = ZL.opt.playerInfo or {}
        --删除1天前的玩家历史数据
        for name, data in ipairs(ZL.opt.playerInfo) do
            if time() - data.updateTimestamp > 86400 then
                ZL.opt.playerInfo[name] = nil
            end
        end
        --将拍卖物品ID设置调整到配置下面，并删除原数据
        ZL.opt.ZL_SETTING = ZL.opt.ZL_SETTING or ZL_SETTING or {itemLevelSetting={}, itemIdSetting={}, filterItemId=filterItemId}
        if ZL_SETTING then ZL_SETTING = nil end

        --检测过滤名单，强制添加拾取绑定并且没有2小时交易时间的物品为不自动拾取
        local ZL_SETTING = ZL.opt.ZL_SETTING
        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
    elseif event == "GROUP_ROSTER_UPDATE" then
        C_Timer.After(1, function ()
            if IsInRaid(1) then
                if PlayerIsML() then
                    CheckForNewMembers()
                end
                C_Timer.After(1, function ()
                    local MLname = GetMLname() or ZL_CURRENT.MLname
                    if MLname then
                        local pruneName = ZL.pruneCrossRealm(MLname)
                        ZL_CURRENT.UnitGuid = UnitGUID(pruneName)
                        ZL_CURRENT.FactionGroup = select(2, UnitFactionGroup(pruneName))
                        ZL_CURRENT.MLname = MLname
                    end
                end)
                ZL.SaveDataRemind()
            else
                previousRoster = {}
            end
        end)
    elseif event == "PARTY_LOOT_METHOD_CHANGED" or event == "PARTY_LEADER_CHANGED" then
        if IsInRaid(1) then
            -- 已包含在"GROUP_ROSTER_UPDATE"事件里
            local lootMethod = GetLootMethod()
            if (lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) and ZL.IsRaidLeader() then
                if (not ZL.opt.appointMLName) or (not UnitInRaid(ZL.opt.appointMLName)) then
                    ZL.opt.appointMLName = ZL.GetFullName()
                end
                MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.opt.appointMLName})
            end
            ZL.AuctionFrame2:Update()
        end
    elseif event == "LOOT_OPENED" and IsInInstance() and (select(2, IsInInstance()) == "raid") and IsInRaid(1) then -- and IsInInstance() and (select(2, IsInInstance()) == "raid")
        --如果是ML打开掉落则开始创建待拍卖窗口
        local NumLootItems = GetNumLootItems()
        if NumLootItems <= 0 then return end
        if (not ZL_CURRENT.sourceGUID) then ZL_CURRENT.sourceGUID = {} end
        local sourceGUID
        for i = 1, NumLootItems do
            sourceGUID = GetLootSourceInfo(i)
            if sourceGUID then break end
        end
        if (not sourceGUID) or ZL_CURRENT.sourceGUID[sourceGUID] then
            return
        end
        if not ZL_CURRENT.sourceGUID[sourceGUID] then ZL_CURRENT.sourceGUID[sourceGUID] = {} end
        ZL_CURRENT.sourceGUID[sourceGUID].time = date("%Y-%m-%d %H:%M:%S", time())

        local npcID = select(6, strsplit("-", sourceGUID))
        if npcID then
            -----副本BOSSID数据收集开始
            local name, _, _, _, _, _, _, instanceID = GetInstanceInfo()
            ZL.opt.encounterLootData = ZL.opt.encounterLootData or {}
            ZL.opt.encounterLootData[name..":"..instanceID] = ZL.opt.encounterLootData[name..":"..instanceID] or {}
            if ZL_CURRENT.bossName and ZL_CURRENT.bossName ~= "其他" then
                ZL.opt.encounterLootData[name..":"..instanceID][tonumber(npcID)] = ZL_CURRENT.bossName
            end
            -----副本BOSSID数据收集结束
            npcID = ZL.BossInfo[tonumber(npcID)] or ZL_CURRENT.bossName or "其他"
        else
            npcID = "其他"
        end
        local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality) --GetLootThreshold()获取当前团队的战利品分配阈值
        local lootMinQuality = (ZL.opt.lootMinQuality == -1 and GetLootThreshold() or ZL.opt.lootMinQuality)
        local lootList = {}
        local lootAuctionList = {}
        local candidates = {}
        local isGetCandidates = false
        --先创建完所有的记录
        local lootMethod = GetLootMethod()
        for numLoot = 1, NumLootItems do
            if LootSlotIsItem(numLoot) then
                local itemlink = GetLootSlotLink(numLoot)
                local _, _, lootQuantity, _, lootQuality, _, isQuestItem = GetLootSlotInfo(numLoot)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                if (not isQuestItem) then
                    local _, auctionFilter, lootFilter = isFilterItem(itemId)
                    --蓝装以上拾取通报
                    if lootQuality > 2 then
                        lootList[itemlink] = (lootList[itemlink] or 0) + lootQuantity
                    end
                    if PlayerIsML() and (lootMethod == "master" or lootMethod == 2) then
                        --拍卖
                        if lootQuality >= minQuality and (not auctionFilter) then
                            --获取候选人
                            if (not isGetCandidates) then
                                candidates = GetMasterLootCandidates(numLoot) --获取候选人信息
                                isGetCandidates = true
                            end
                            --增加自定义itemGUID规则：itemId+GetServerTime()+01
                            if not lootAuctionList[itemlink] then
                                lootAuctionList[itemlink] = {spawnUID={}, lootQuantity=0, increment=1}
                            end
                            local stackCount, _, _, _, _, _, bindType = select(8, cGetItemInfo(itemlink))
                            if stackCount == 1 then
                                local spawnUIDkey = itemId ..GetServerTime() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                if itemId == 47242 then --北伐奖章直接放到其他分类
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                else
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName=npcID, itemGUID={}}
                                end
                                lootAuctionList[itemlink].increment = lootAuctionList[itemlink].increment + 1
                                if bindType == 1 then
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey].candidates = candidates
                                end
                            else
                                if lootAuctionList[itemlink].increment == 1 then
                                    local spawnUIDkey = itemId ..GetServerTime() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                end
                            end
                            lootAuctionList[itemlink].lootQuantity = lootAuctionList[itemlink].lootQuantity + lootQuantity
                        end
                        --ML自动拾取
                        local _, _, _, _, _, _, _, itemStackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                        if lootQuality >= lootMinQuality and ZL.opt.awardToML and (not lootFilter) and (not (itemStackCount > 1 and bindType == 1))
                        and (not ZL.isbuyItems(numLoot , itemId)) then
                            local candidateIndex = 1
                            local candidateName = GetMasterLootCandidate(numLoot, candidateIndex) --用于获取在团队副本中分配战利品时的候选者信息
                            while candidateName do
                                if PlayerIsML(candidateName) then --当候选人是ML时
                                    GiveMasterLoot(numLoot, candidateIndex)
                                    break
                                end
                                candidateIndex = candidateIndex + 1
                                candidateName = GetMasterLootCandidate(numLoot, candidateIndex)
                            end
                        end
                    end
                end
            end
        end
        --拾取通报
        if next(lootList) then
            local reporter
            if ZL_PLAYERLIST.autoNotice and next(ZL_PLAYERLIST.autoNotice) then
                local tempList = {}
                for i = 1, MAX_RAID_MEMBERS do
                    local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
                    if name and online and ZL_PLAYERLIST.autoNotice[name] and ZL_PLAYERLIST.autoNotice[name].confirmLootAnnounce then
                        tinsert(tempList, name)
                    end
                end
                if #tempList > 1 then
                    table.sort(tempList, function (a, b)
                        local aIsML = PlayerIsML(a)
                        local bIsML = PlayerIsML(b)
                        if aIsML and not bIsML then
                            return true
                        elseif not aIsML and bIsML then
                            return false
                        end
                        local aIsLeader = UnitIsGroupLeader(a)
                        local bIsLeader = UnitIsGroupLeader(b)
                        if aIsLeader and not bIsLeader then
                            return true
                        elseif not aIsLeader and bIsLeader then
                            return false
                        end
                        return a < b
                    end)
                end
                reporter = tempList[1]
                tempList = nil
            end
            if reporter == UnitName("player") then
                SendChatMessage("[AutoAuction]拾取通报：", "RAID")
                C_Timer.After(0.3, function ()
                    for link, num in pairs(lootList) do
                        if num > 1 then
                            SendChatMessage(link .. "x" .. num, "RAID")
                        else
                            SendChatMessage(link, "RAID")
                        end
                    end
                end)
            end
        end
        if PlayerIsML() and (lootMethod == "master" or lootMethod == 2) then
            ZL_CURRENT.sourceGUID[sourceGUID].candidates = candidates
            --开始创建拍卖物品
            if next(lootAuctionList, nil) then
                local keyList = {}
                for key, _ in pairs(lootAuctionList) do
                    table.insert(keyList, key)
                end
                local sendData = {type="拾取创建", data={}, globalConfigData=ZL.globalConfigData()}
                for _, itemlink in ipairs(keyList) do
                    --bindType 1为拾取绑定
                    local _, _, _, itemLevel, _, _, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                    local lootQuantity = lootAuctionList[itemlink].lootQuantity
                    local spawnUID = lootAuctionList[itemlink].spawnUID
                    local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                    local indexList = {}
                    local itemindex = 1
                    if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == itemlink) then
                                itemindex = itemindex + 1
                                if not ZL.opt.notItemStack and data.state ~= "success" and data.state ~= "auctioning" then
                                    table.insert(indexList, num) --可能因交易名单不同存在多个拍卖记录
                                end
                            end
                        end
                    end
                    local data = {}
                    local index
                    if #indexList > 0 then
                        for _, _index in ipairs(indexList) do
                            index = _index  --相同物品都创建到一个拍卖物品上面，取消根据不同拾取权限重新创建
                        end
                    end
                    if index then
                        local fdata = ZL_CURRENT.auctionlist[index]
                        table.insert(ZL_CURRENT.auctionlist[index]["sourceGUID"], sourceGUID)
                        ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                        --堆叠数量为1，需要添加进去，大于1不需要
                        if fdata.stackCount == 1 then
                            for key, value in pairs(spawnUID) do
                                ZL_CURRENT.auctionlist[index]["spawnUID"][key] = value
                            end
                        end
                        if fdata.isPackage then
                            --如果是打包物品则更新[打包拍卖]数量
                            local __data, __index = ZL.FetchDataFromItemId("[打包拍卖]", 1)
                            if __index then
                                ZL_CURRENT.auctionlist[__index]["itemList"][itemlink]["itemCount"] = __data["itemList"][itemlink]["itemCount"] + lootQuantity
                            end
                        end
                        fdata = ZL_CURRENT.auctionlist[index]
                        if fdata.state == "failed" then
                            --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                            C_Timer.After(20, function ()
                                ZL.reportFailedItem(true)
                            end)
                        end
                        data = {
                            type = "数量更新",
                            data2 = ZL_CURRENT.auctionlist[index],
                        }
                    else
                        if not ZL_CURRENT.name then ZL.CreateAuctionInfo() end
                        if (not ZL_CURRENT.globalConfig) then
                            ZL_CURRENT.globalConfig = ZL.globalConfigData()
                        end
                        --不存在则创建
                        local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                        bidIncrement = ZL.GetDiffrentIncrementBid(startbidamount, bidIncrement)
                        --ML自己创建，不参与插件同步创建
                        local data2 = {
                            type = "自动创建",
                            itemId = itemId,
                            itemlink = itemlink,
                            itemindex = itemindex,
                            startbidamount = startbidamount,
                            bidIncrement = bidIncrement,
                            state = "waiting",
                            lgnore = false,
                            endTime = nil,
                            bidderlist = {},
                            itemCount = lootQuantity,
                            sourceGUID = {sourceGUID},
                            spawnUID = spawnUID,
                            stackCount = stackCount,
                            bindType = bindType,
                            itemLevel = itemLevel,
                            itemSubType = itemSubType,
                            createTime = date("%Y-%m-%d %H:%M:%S", GetServerTime()),
                        }
                        ZL_CURRENT.auctionlist = ZL_CURRENT.auctionlist or {}
                        table.insert(ZL_CURRENT.auctionlist, data2)
                        local index2 = #ZL_CURRENT.auctionlist
                        data = {
                            type = "创建拍卖",
                            data2 = ZL_CURRENT.auctionlist[index2],
                        }
                    end
                    table.insert(sendData.data, data)
                end
                ZL.AuctionListSort()
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC0", sendData)
            end
            --开始拾取包装备的
            local numLoot = 1
            local function tempfunc()
                if numLoot <= GetNumLootItems() then
                    local delay = 0
                    if LootSlotIsItem(numLoot ) then
                        local itemlink = GetLootSlotLink(numLoot )
                        local _, _, _, _, _, _, isQuestItem = GetLootSlotInfo(numLoot )
                        local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                        if (not isQuestItem) then
                            --自动分配给包装备的
                            if ZL.opt.autoMaster and ZL_CURRENT.buyerItemList and #ZL_CURRENT.buyerItemList > 0 then
                                for _, data in ipairs(ZL_CURRENT.buyerItemList) do
                                    local isBreak
                                    if data.itemId == itemId and data.hasLootCounts < data.itemCounts then
                                        local buyerName = ParseClassColorName(data.buyerName)
                                        local candidateIndex = 1
                                        local candidateName = GetMasterLootCandidate(numLoot , candidateIndex)
                                        while candidateName do
                                            if ZL.GetFullName(candidateName) == buyerName then
                                                GiveMasterLoot(numLoot , candidateIndex)
                                                isBreak = true
                                                delay = 0.2
                                                break
                                            end
                                            candidateIndex = candidateIndex + 1
                                            candidateName = GetMasterLootCandidate(numLoot , candidateIndex)
                                        end
                                    end
                                    if isBreak then break end
                                end
                            end
                        end
                    else
                        delay = 0
                    end
                    numLoot = numLoot + 1
                    C_Timer.After(delay, tempfunc)
                end
            end
            C_Timer.After(0.3, function ()
                tempfunc()
            end)
        end
    elseif event == "LOOT_CLOSED" and PlayerIsML() then
        C_Timer.After(3, ZL.GetLootItemGUID)
    elseif (event == "CHAT_MSG_RAID") or (event == "CHAT_MSG_RAID_LEADER") or (event == "CHAT_MSG_RAID_WARNING") then
        local fullName = arg[2]
        local fullColorName = GetClassColorName(arg[2])
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        if (strfind(msg, "YY") or strfind(msg, "yy") or strfind(msg, "歪歪")) and (not strfind(msg, "待命") and not strfind(msg, "声") and not strfind(msg, "说") and not strfind(msg, "在") and not strfind(msg, "YY:"))
        and not strfind(msg, "开") and (not strfind(msg, "起手")) and not InCombatLockdown() and (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (not PlayerIsML(sender)) and (not UnitIsGroupLeader(sender)) and ZL.opt.welcomeMessageEnable and
        (sender ~= UnitName("player")) and ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0)  then
            SendChatMessage(ZL.opt.MessageString, "RAID")
        end
        do
            --检测biaoge拍卖成功物品
            local itemLink, buyerName, amount = msg:match("{rt6}拍卖成功{rt6} (.-) (.-) (.+)")
            if not (itemLink and buyerName and amount) then
                itemLink, buyerName, amount = msg:match("{rt6}拍賣成功{rt6} (.-) (.-) (.+)")
            end
            if (itemLink and buyerName and amount) then
                local isExist
                if ZL_PLAYERLIST.lootList then
                    for _bossName, bossNameData in pairs(ZL_PLAYERLIST.lootList) do
                        if type(bossNameData) == "table" then
                            for _itemLink, itemLinkData in pairs(bossNameData) do
                                if _itemLink == itemLink and itemLinkData["拾取1"]["counts"] > 0 then
                                    ZL.QuickRecordFrame.bossName = _bossName
                                    isExist = true
                                    break
                                end
                            end
                            if isExist then break end
                        end
                    end
                end
                buyerName = GetClassColorName(buyerName)
                if isExist then
                    ZL.saveQuickRecordData(itemLink, buyerName, amount, 1)
                end
            end
        end
        do
            if PlayerIsML() then
                --检测biaoge流拍物品
                local itemLink = msg:match("{rt7}流拍{rt7} (.+)")
                if itemLink then
                    local auctionIndex
                    if ZL_CURRENT.auctionlist then
                        for index, data in ipairs(ZL_CURRENT.auctionlist) do
                            if data.itemlink == itemLink and (data.state == "waiting" or data.state == "failed") then
                                auctionIndex = index
                                break
                            end
                        end
                    end
                    if auctionIndex then
                        ZL.startOrCanelAuction(auctionIndex, true)
                    end
                end
            end
        end
        do
            local itemLink, startAmount = msg:match("{rt1}拍卖开始{rt1} (.-) 起拍价：(.+)")
            if not (itemLink and startAmount) then
                itemLink, startAmount = msg:match("{rt1}拍卖开始{rt1} (.-) 起拍价：(.+)")
            end
            if itemLink and startAmount then
                local itemId = GetItemInfoFromHyperlink(itemLink)
                if itemId then
                    local selectCharKey = ZL.GetClassColorName() .. " - " .. GetRealmName()
                    if ZL.opt.concernList and ZL.opt.concernList[selectCharKey] and ZL.opt.concernList[selectCharKey]["itemList"][itemId]
                    and select(4, ZL.GetItemNumbers(itemId)) == 0 then
                        C_VoiceChat.StopSpeakingText()
                        PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\guanzhuwupinpaimai.mp3", "Master")
                        ZL.Print("注意！您关注的物品：" .. itemLink .. "开始拍卖，请及时出价！")
                    end
                end
            end
        end
        if ZL_CURRENT.globalConfig and ZL_CURRENT.globalConfig.auctionMode == "团队" then
            --监控全员信息出价
            local AuctioningCount, _index = GetAuctioningCount()
            local isFailedAuction --流拍物品重启拍卖
            local msgStr = ""
            local newBid, index
            local bidCount
            local cmsg = fullwidthToHalfwidth(msg)
            --首先全部剔除空格判断是否存在对应的拍卖物品
            cmsg = msg_gsub(cmsg)
            if cmsg:match("^(|c.-|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") or cmsg:match("^(%[打包拍卖%])(%d+%.?%d*)[gGkKwW]?$") then
                local matchStr = ""
                if cmsg:match("^(|c.-|Hitem:.+|h%[.-%]|h|r)(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)$") then
                    matchStr = "(|c.-|Hitem:.+|r)"
                else
                    matchStr = "(%[打包拍卖%])"
                end
                local bidItemLink
                bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[wW][%*%-xX×]?(%d*)")
                if (not bidItemLink) then
                    bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.?[0-9]*)[kK][%*%-xX×]?(%d*)")
                    if (not bidItemLink) then
                        bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "([0-9]+%.[0-9]*)[%*%-xX×]?(%d*)")
                        if (not bidItemLink) then
                            bidItemLink, newBid, bidCount = cmsg:match(matchStr .. "(%d+)[gG]*[%*%-xX×]?(%d*)")
                            if (not bidItemLink) then
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = ("出价不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(bidItemLink)
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    -- SendChatMessage(msgStr, "RAID")
                                end
                                newBid = nil
                            end
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 1000)
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 10000)
                end
                if bidItemLink then
                    if AuctioningCount > 0 then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemlink == bidItemLink) and (data.state == "auctioning") then
                                    index = num
                                    break
                                end
                            end
                        end
                    end
                    if not index then
                        if AuctioningCount > 0 then
                            --如果此物品没有正在拍卖，则判断是否为多拍模式，多拍模式下，如果是流拍物品，则启动拍卖
                            if ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                isFailedAuction = true
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                            end
                        else
                            --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                            isFailedAuction = true
                        end
                    end
                    if isFailedAuction then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                    index = num
                                    break
                                end
                            end
                        end
                        if not index then
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = bidItemLink .. "没有此流拍物品"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                            end
                        end
                    end
                end
            elseif cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)(|c.-|Hitem:.+|h%[.-%]|h|r)$") or cmsg:match("^(%d+%.?%d*)[gGkKwW]?(%[打包拍卖%])$") then
                local matchStr = ""
                if cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX×]?(%d*)(|c.-|Hitem:.+|h%[.-%]|h|r)$") then
                    matchStr = "(|c.-|Hitem:.+|r)"
                else
                    matchStr = "(%[打包拍卖%])"
                end
                local bidItemLink
                newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.?[0-9]*)[wW][%*%-xX×]?(%d*)" .. matchStr)
                if (not bidItemLink) then
                    newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.?[0-9]*)[kK][%*%-xX×]?(%d*)"  .. matchStr)
                    if (not bidItemLink) then
                        newBid, bidCount, bidItemLink = cmsg:match("([0-9]+%.[0-9]*)[%*%-xX×]?(%d*)" .. matchStr)
                        if (not bidItemLink) then
                            newBid, bidCount, bidItemLink = cmsg:match("(%d+)[gG]*[%*%-xX×]?(%d*)" .. matchStr)
                            if (not bidItemLink) then
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = ("出价不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(bidItemLink)
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    -- SendChatMessage(msgStr, "RAID")
                                end
                                newBid = nil
                            end
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 1000)
                    end
                else
                    newBid = math.floor(tonumber(newBid) * 10000)
                end
                if bidItemLink then
                    if AuctioningCount > 0 then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemlink == bidItemLink) and (data.state == "auctioning") then
                                    index = num
                                    break
                                end
                            end
                        end
                    end
                    if not index then
                        if AuctioningCount > 0 then
                            --如果此物品没有正在拍卖，则判断是否为多拍模式，多拍模式下，如果是流拍物品，则启动拍卖
                            if ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                isFailedAuction = true
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                            end
                        else
                            --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                            isFailedAuction = true
                        end
                    end
                    if isFailedAuction then
                        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                    index = num
                                    break
                                end
                            end
                        end
                        if not index then
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = bidItemLink .. "没有此流拍物品"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                            end
                        end
                    end
                end
            elseif cmsg:match("^(%d+%.?%d*)[gGkKwW]?[%*%-xX]?(%d*)$") then
                if AuctioningCount == 1 then
                    index = _index
                    newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[wW][%*%-xX×]?([0-9]*)")  --万，检测1W，1.1w
                    if (not newBid) then
                        newBid, bidCount = cmsg:match("([0-9]+%.?[0-9]*)[kK][%*%-xX×]?([0-9]*)")  --千，检测1k,1.1K
                        if (not newBid) then
                            newBid, bidCount = cmsg:match("([0-9]+%.[0-9]*)[%*%-xX×]?([0-9]*)") --检测1.1这种数字
                            if (not newBid) then
                                newBid, bidCount = cmsg:match("(%d+)[gG]*[%*%-xX×]?([0-9]*)") --检测不带小数点的数字，可能带有g或G
                            end
                        else
                            newBid = math.floor(tonumber(newBid) * 1000)
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 10000)
                    end
                elseif AuctioningCount > 1 then
                    if PlayerIsML() and ZL.opt.remindInvalidBid and ZL_CURRENT.auctionlist[_index].itemlink then
                        msgStr = "出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        msgStr = ">>>" .. fullName .. "<<<，出价无法识别，当前为多拍模式，请按照如下格式出价：" .. 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 = ("出价不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(bidItemLink)
                                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                                            -- SendChatMessage(msgStr, "RAID")
                                        end
                                        newBid = nil
                                    end
                                end
                            else
                                newBid = math.floor(tonumber(newBid) * 1000)
                            end
                        else
                            newBid = math.floor(tonumber(newBid) * 10000)
                        end
                        if bidItemLink then
                            if AuctioningCount > 0 then
                                if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                                    for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                        if (data.itemlink == bidItemLink) and (data.state == "auctioning") then
                                            index = num
                                            break
                                        end
                                    end
                                end
                            end
                            if not index then
                                if AuctioningCount > 0 then
                                    --如果此物品没有正在拍卖，则判断是否为多拍模式，多拍模式下，如果是流拍物品，则启动拍卖
                                    if ZL_CURRENT.globalConfig.allowMultipleAuctions then
                                        isFailedAuction = true
                                    else
                                        if PlayerIsML() and ZL.opt.remindInvalidBid then
                                            msgStr = "当前为单拍模式，有物品正在拍卖，请结束后重新发送"
                                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                                            return
                                        end
                                    end
                                else
                                    --如果没有物品正在拍卖并且需要拍卖的物品是流拍状态
                                    isFailedAuction = true
                                end
                            end
                            if isFailedAuction then
                                if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
                                    for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                        if (data.itemlink == bidItemLink) and (data.state == "failed") then
                                            index = num
                                            break
                                        end
                                    end
                                end
                                if not index then
                                    if PlayerIsML() and ZL.opt.remindInvalidBid then
                                        msgStr = bidItemLink .. "没有此流拍物品"
                                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    end
                                end
                            end
                        end
                    elseif cmsg:match("^%s*(%d+%.?%d*)%s*[gGkKwW]?%s*[%*%-xX ]?(%d*)%s*$") then
                        if AuctioningCount == 1 then
                            index = _index
                            newBid, bidCount = cmsg:match("%s*([0-9]+%.?[0-9]*)%s*[wW]%s*[%*%-xX× ]?([0-9]*)%s*")  --万，检测1W，1.1w
                            if (not newBid) then
                                newBid, bidCount = cmsg:match("%s*([0-9]+%.?[0-9]*)%s*[kK]%s*[%*%-xX× ]?([0-9]*)%s*")  --千，检测1k,1.1K
                                if (not newBid) then
                                    newBid, bidCount = cmsg:match("%s*([0-9]+%.[0-9]*)%s*[%*%-xX× ]?([0-9]*)%s*") --检测1.1这种数字
                                    if (not newBid) then
                                        newBid, bidCount = cmsg:match("%s*(%d+)%s*[gG]*%s*[%*%-xX× ]?([0-9]*)%s*") --检测不带小数点的数字，可能带有g或G
                                    end
                                else
                                    newBid = math.floor(tonumber(newBid) * 1000)
                                end
                            else
                                newBid = math.floor(tonumber(newBid) * 10000)
                            end
                        elseif AuctioningCount > 1 then
                            if PlayerIsML() and ZL.opt.remindInvalidBid and ZL_CURRENT.auctionlist[_index].itemlink then
                                msgStr = "出价无法识别，当前为多拍模式，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[_index].itemlink .. "400/1k/1.1w"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                msgStr = ">>>" .. fullName .. "<<<，出价无法识别，当前为多拍模式，请按照如下格式出价：" .. 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) <= 100000000) then
                newBid = tonumber(newBid)
                bidCount = bidCount and tonumber(bidCount) or 1
                local fdata = ZL_CURRENT.auctionlist[index]
                if (not ZL.IsCandidate(index, fullColorName)) then
                    if PlayerIsML() then
                        msgStr = fdata.itemlink .. "不能交易给你，无法参与竞拍"
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        msgStr = ">>>" .. fullName .. "<<<".. fdata.itemlink .. "不能交易，无法参与竞拍，出价无效"
                        SendChatMessage(msgStr, "RAID")
                    end
                    return
                end
                if newBid == 666 then
                    if PlayerIsML() then
                        msgStr = ("\"666\"为高频易混淆词，如需竞价请在后面添加一个0，如：%d0，如不竞价，忽略这条提醒"):format(newBid)
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                    end
                    return
                end
                local oldBid = newBid
                --将小数点替换掉
                newBid = string.gsub(tostring(newBid),"%.", "")
                newBid = tonumber(newBid)
                local AuctionFrame = ZL.AuctionFrame2
                local Frame1 = AuctionFrame.entries[index]
                local bidderlist = fdata.bidderlist
                local baseamount, bidIncrement, tarbidamount = ZL.GetNewBidAmount(index)
                newBid = padZeros(newBid, tarbidamount, bidIncrement, baseamount)
                if ((newBid - baseamount) % bidIncrement) == 0 or ((newBid - (baseamount - (baseamount % bidIncrement))) % bidIncrement) == 0 then --按照加价幅度整数倍出价
                    if newBid >= tarbidamount then
                        if isFailedAuction then
                            if PlayerIsML() then
                                --如果存在此流拍物品则先启动拍卖，然后将出价直接添加到数据库里
                                if (not ZL_CURRENT.globalConfig) then
                                    ZL_CURRENT.globalConfig = ZL.globalConfigData()
                                end
                                local curAuctionList = ZL_CURRENT.auctionlist[index]
                                if not ZL.IsCanAuction(curAuctionList) then
                                    msgStr = curAuctionList.itemlink .. "无法拍卖，原因可能是：已分解或已无法交易"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                                --如果是流拍的物品重新拍卖，检测流拍物品是否在流拍包里，如果在移动到其他包里
                                if curAuctionList.state == "failed" and ZL.opt.liupaiToggle and curAuctionList["spawnUID"] and next(curAuctionList["spawnUID"], nil) then
                                    local itemList = {}
                                    for _, value in pairs(curAuctionList["spawnUID"]) do
                                        if value["itemGUID"] and next(value["itemGUID"], nil) then
                                            for key, _ in pairs(value["itemGUID"]) do
                                                local bagID, slotIndex = ZL.FindItemInBag(key)
                                                if bagID and (bagID == ZL.opt.liupaiBagId or bagID == ZL.opt.liupaiBagId2) then
                                                    --从第一个背包开始查询空闲的格子，如果不是流拍背包，也不是自己拍到的背包，则放进去
                                                    local targetBagID, targetslotIndex
                                                    local currentInfo
                                                    for _bagID = 0, NUM_BAG_SLOTS do
                                                        if _bagID ~= ZL.opt.liupaiBagId and _bagID ~= ZL.opt.liupaiBagId2 and _bagID ~= ZL.opt.selfBagId then
                                                            for _slotIndex = 1, C_Container.GetContainerNumSlots(_bagID) do
                                                                currentInfo = C_Container.GetContainerItemInfo(_bagID, _slotIndex)
                                                                if not currentInfo then
                                                                    targetBagID = _bagID
                                                                    targetslotIndex = _slotIndex
                                                                    break
                                                                end
                                                            end
                                                        end
                                                    end
                                                    currentInfo = nil
                                                    if targetBagID then
                                                        table.insert(itemList, {
                                                            bagID = bagID, slotIndex = slotIndex,
                                                            targetBagID = targetBagID, targetslotIndex = targetslotIndex,
                                                        })
                                                    end
                                                end
                                            end
                                        end
                                    end
                                    if #itemList > 0 then
                                        local __index = 1
                                        local function linshi()
                                            if __index <= #itemList then
                                                if not (InCombatLockdown() or UnitIsDeadOrGhost("player")) then
                                                    C_Container.PickupContainerItem(itemList[__index]["bagID"], itemList[__index]["slotIndex"])
                                                    C_Container.PickupContainerItem(itemList[__index]["targetBagID"], itemList[__index]["targetslotIndex"])
                                                    __index = __index + 1
                                                    C_Timer.After(1, linshi)
                                                else
                                                    C_Timer.After(0.2, linshi)
                                                end
                                            end
                                        end
                                        linshi()
                                    end
                                end
                                bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount
                                ZL_CURRENT.auctionlist[index].bidderlist = {}
                                table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                    bidder = fullColorName,
                                    bidamount = newBid,
                                    bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount,
                                    time = GetTime()*1000,
                                })
                                local data = {
                                    type = "开始拍卖",
                                    isRestart = curAuctionList.state,
                                    data2 = ZL_CURRENT.auctionlist[index],
                                    syncIndex = index,
                                    globalConfigData = ZL.globalConfigData(),
                                }
                                MyAddon:TransmitAddonInfo("AUTOAUC SYNC1", data)
                                Frame1.sync = true
                                Frame1.MLframe.functionFrame.CancelBtn:Disable()
                                C_Timer.After(10, function ()
                                    Frame1.sync = nil
                                    Frame1.MLframe.functionFrame.CancelBtn:Enable()
                                end)
                                ZL.Print("开始拍卖发送数据中，请稍等...")
                            end
                        else
                            if (fdata.endTime or 0) - time() > 0 then
                                fdata.endTime = time() + ZL_CURRENT.globalConfig.auctionTimerRefresh
                                Frame1:SetValues(index)
                                if ZL.opt.IsVoiceReminder and ZL.opt.IsComeOnVoiceReminder and (((not ZL_CURRENT.globalConfig) or (not ZL_CURRENT.globalConfig.YYSound)) or PlayerIsML())
                                and ((not ZL.jiayou) or ((ZL.jiayou + ZL.opt.ComeOnVoiceReminderInterval -GetTime()) < 0)) and ((newBid-tarbidamount+bidIncrement) >= ZL.opt.ComeOnVoiceReminderBidIncrement
                                or (newBid >= ZL.opt.ComeOnVoiceReminderBidAmount)) then
                                    C_VoiceChat.StopSpeakingText()
                                    PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\laogongjiayou.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 b.bidder == fullColorName 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 = fullColorName,
                                        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 bidData.bidder == fullColorName and PlayerIsML() then
                                                SendChatMessage("已自动将您当前出价数量调整为：" .. count, "WHISPER", nil ,sender)
                                            end
                                        end
                                        totalBidCount = newTotalBidCount
                                    else
                                        break
                                    end
                                end
                                Frame1:SetValues(index)
                                if ZL.BidderListFrame:IsShown() and ZL.BidderListFrame.index then
                                    ZL.BidderListFrame:Update(ZL.BidderListFrame.index)
                                end
                                ZL.updateTargetAmount(index)
                                if (oldBid == 1 or oldBid == 11 or oldBid == 99) and PlayerIsML() then
                                    msgStr = "插件已记录你的竞拍价:" .. newBid .. "g，如需撤销，请【私聊】我回复：撤销"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                end
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = fdata.itemlink .. "拍卖已结束！"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    return
                                end
                            end
                        end
                    else
                        local isExist
                        for _, bidData in ipairs(bidderlist) do
                            if bidData.bidder == fullColorName and newBid == bidData.bidAmount then
                                isExist = true
                                break
                            end
                        end
                        if (not isExist) and PlayerIsML() and ZL_CURRENT.globalConfig.auctionMode == "团队" then
                            msgStr = ("%s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(fdata.itemlink, tarbidamount)
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            msgStr = ("%s %s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(fullName, fdata.itemlink, tarbidamount)
                            SendChatMessage(msgStr, "RAID")
                            return
                        end
                    end
                else
                    if PlayerIsML() then -- and ZL.opt.remindInvalidBid
                        msgStr = ">>>" .. fullName .."<<<出价无效，请按加价幅度(" .. bidIncrement .. ")的整数倍出价"
                        SendChatMessage(msgStr, "RAID")
                        msgStr = "如需竞拍，请按加价幅度(" .. bidIncrement .. ")的整数倍出价，如不需要竞拍忽略这条信息"
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        return
                    end
                end
            end
        end
    elseif (event == "CHAT_MSG_WHISPER") and PlayerIsML() then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        local __name = GetClassColorName(arg[2])
        if msg == "撤销" then
            local num, index = GetAuctioningCount()
            if num == 1 then
                local itemlink = ZL_CURRENT.auctionlist[index].itemlink
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemlink=itemlink, itemindex=itemindex, playerName=__name})
            else
                if PlayerIsML() then
                    SendChatMessage("当前存在多个拍卖物品，无法撤销出价！", "WHISPER", nil, sender)
                end
            end
        end
    elseif (event == "TRADE_CLOSED") then
		ZL.isTrading = nil
        ZL.needTradeQianKuan = nil
        if not ZL.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Hide()
            ZL.opt.ZLAuctionRecordFrameIsShown = false
        end
        _G["TradeFrame"].PlayerTradeMoneyText:Hide()
        _G["TradeFrame"].TargetTradeMoneyText:Hide()
        TradeFrame.NeedTradeMoneyBtn:Hide()
        TradeFrame.NeedTradeMoneyBtn.balanceAmount = nil
	elseif (event == "TRADE_SHOW") then
		ZL.ZLAuctionRecordFrameIsShown = ZL.AuctionRecordFrame:IsShown() --如果一开始是打开状态，关闭交易的时候该窗口不关闭
        if not _G["TradeFrame"].PlayerTradeMoneyText then
            _G["TradeFrame"].PlayerTradeMoneyText = _G["TradeFrame"]:CreateFontString()
            local PlayerTradeMoneyText = _G["TradeFrame"].PlayerTradeMoneyText
            PlayerTradeMoneyText:SetFont(GameFontNormal:GetFont(), 13)
            PlayerTradeMoneyText:SetPoint("TOPRIGHT", _G["TradeFrame"], "TOPLEFT", 165, -41)
            PlayerTradeMoneyText:SetHeight(20)
            PlayerTradeMoneyText:SetJustifyH("RIGHT")

            _G["TradeFrame"].TargetTradeMoneyText = _G["TradeFrame"]:CreateFontString()
            local TargetTradeMoneyText = _G["TradeFrame"].TargetTradeMoneyText
            TargetTradeMoneyText:SetFont(GameFontNormal:GetFont(), 13)
            -- TargetTradeMoneyText:SetPoint("TOPRIGHT", _G["TradeFrame"], "TOPRIGHT", -5, -41)
            TargetTradeMoneyText:SetPoint("TOPRIGHT", _G["TradeRecipientItem1"], "TOPRIGHT")
            TargetTradeMoneyText:SetHeight(20)
            TargetTradeMoneyText:SetJustifyH("RIGHT")
            TargetTradeMoneyText:Hide()

            local NeedTradeMoneyBtn = CreateFrame("Button", nil, _G["TradePlayerItem1ItemButton"], "UIPanelButtonTemplate")
            TradeFrame.NeedTradeMoneyBtn = NeedTradeMoneyBtn
            NeedTradeMoneyBtn:Hide()
            NeedTradeMoneyBtn:SetSize(162, 24)
            -- NeedTradeMoneyBtn:SetText("请支付:1000000g")
            do
                local fontString = NeedTradeMoneyBtn:GetFontString()
                fontString:SetFont(GameFontNormal:GetFont(), 13)
            end
            NeedTradeMoneyBtn:SetPoint("TOPRIGHT", _G["TradePlayerItem1"], "TOPRIGHT")
            NeedTradeMoneyBtn:SetScript("OnClick", function (self)
                if self.balanceAmount and self.balanceAmount > 0 then
                    local balanceAmount = self.balanceAmount
                    if GetMoney() < balanceAmount then
                        ZL.Print("金币不足，无法支付！")
                        return
                    end
                    local tradeTarget = GetUnitName("npc", true)
                    local hasOpenTrade, hasCloseTrade
                    local function startTrade()
                        if TradeFrame and TradeFrame:IsShown() then
                            if not hasCloseTrade and not hasOpenTrade then
                                TradeFrame:Hide()
                                hasCloseTrade = true
                                C_Timer.After(0.4, startTrade)
                            end
                            if hasOpenTrade then
                                ClickTradeButton(1)
                                C_Timer.After(0.3, function ()
                                    AcceptTrade()
                                end)
                            end
                        else
                            if not hasOpenTrade then
                                PickupPlayerMoney(balanceAmount)
                                InitiateTrade(tradeTarget)
                                hasOpenTrade = true
                            end
                            C_Timer.After(0.1, startTrade)
                        end
                    end
                    startTrade()
                end
            end)
        end
        _G["TradeFrame"].PlayerTradeMoneyText:Show()
        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(ZL.GetFullName(GetUnitName("npc", true)))
            if not ZL.tradeGongZi then
                local playerBuyList = ZL.GetPlayerBuyList()
                local tradeList = {}
                local splitList = {}
                if playerBuyList[ZL.tradePartner] then
                    local balanceAmount = 0
                    local playerPayToMLamount = 0
                    if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                        playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                    end
                    balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                    if balanceAmount < 0 and ((not ZL_CURRENT.tradeGongZi) or (not ZL_CURRENT.tradeGongZi[ZL.tradePartner])) and ((not ZL_CURRENT["mailPlayers"]) or (not ZL_CURRENT["mailPlayers"][ZL.tradePartner] == true)) then
                        _G["TradeFrame"].TargetTradeMoneyText:Show()
                        _G["TradeFrame"].TargetTradeMoneyText:SetText("|cffff0000欠款：|r" .. GetMoneyString(-balanceAmount*10000))
                        SendChatMessage("§总共请支付：".. -balanceAmount .. "g", "WHISPER", nil, ZL.pruneCrossRealm(ParseClassColorName(ZL.tradePartner)))
                        ZL.needTradeQianKuan = -balanceAmount*10000
                    end
                    if playerBuyList[ZL.tradePartner]["items"] and #playerBuyList[ZL.tradePartner]["items"] > 0 then
                        for _, data in ipairs(playerBuyList[ZL.tradePartner]["items"]) do
                            if (not data.isTraded) and data.itemGUID and #data.itemGUID > 0 then
                                local tradeCount = 0
                                for _, itemGUID in ipairs(data.itemGUID) do
                                    if not tradeList[itemGUID] then
                                        local bag, slot = ZL.FindItemInBag(itemGUID)
                                        if bag then
                                            local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                                            local isLocked = GetContainerItemInfo["isLocked"]
                                            local isBound = GetContainerItemInfo["isBound"]
                                            local stackCount = GetContainerItemInfo["stackCount"]
                                            if not isLocked then
                                                local isCanTrade
                                                if isBound then
                                                    --如果已绑定，检测是否还有剩余交易时间
                                                    if (not ZL.ToolTip) then
                                                        ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                                                    end
                                                    ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                                                    ZL.ToolTip:ClearLines()
                                                    ZL.ToolTip:SetBagItem(bag, slot)
                                                    for i = 1, ZL.ToolTip:NumLines() do
                                                        local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                                                        if text then
                                                            local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                                            if timeRemaining then
                                                                isCanTrade = true
                                                                break
                                                            end
                                                        end
                                                    end
                                                else
                                                    isCanTrade = true
                                                end
                                                if isCanTrade and tradeCount < data.itemCount then
                                                    local splitCount = stackCount - (data.itemCount - tradeCount)
                                                    tradeCount = tradeCount + stackCount
                                                    tradeList[itemGUID] = {bag=bag, slot=slot}
                                                    if splitCount > 0 then
                                                        splitList[itemGUID] = {
                                                            splitCount = splitCount,
                                                            bag = bag,
                                                            slot = slot,
                                                        }
                                                    end
                                                    if tradeCount >= data.itemCount then
                                                        break
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                    local function trade()
                        if next(tradeList) then
                            ClearCursor()
                            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) then
                        local tempList = {}
                        for itemGUID in pairs(splitList) do
                            table.insert(tempList, itemGUID)
                        end
                        local index = 1
                        local function split_linshi()
                            if index <= #tempList then
                                local itemGUID = tempList[index]
                                local isfull = true
                                for tarBagID = 0, NUM_BAG_SLOTS do
                                    for tarSlotIndex = 1, C_Container.GetContainerNumSlots(tarBagID) do
                                        local currentInfo = C_Container.GetContainerItemInfo(tarBagID, tarSlotIndex)
                                        if not currentInfo then
                                            C_Container.SplitContainerItem(splitList[itemGUID].bag, splitList[itemGUID].slot, splitList[itemGUID].splitCount)
                                            C_Container.PickupContainerItem(tarBagID, tarSlotIndex)
                                            isfull = false
                                            break
                                        end
                                    end
                                end
                                if isfull then
                                    local msgStr = "注意！注意！背包已满，无法分成目标小堆数量！已移除交易清单"
                                    ZL.Print(msgStr)
                                    tradeList[itemGUID] = nil
                                end
                                if index == #tempList then
                                    C_Timer.After(1, trade)
                                end
                                index = index + 1
                                C_Timer.After(1, split_linshi)
                            end
                        end
                        split_linshi()
                    else
                        trade()
                    end
                end
            end
        elseif PlayerIsML(GetUnitName("npc", true)) then
            ZL.tradePartner = GetClassColorName(ZL.GetFullName(GetUnitName("player", true)))
        else
            ZL.tradePartner = nil
        end
        if PlayerIsML() then
            if ZL.opt.ShowAuctionRecordFrameCheckButtonValue then
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["TradeFrame"], "TOPRIGHT")
            end
        end
	elseif (event == "TRADE_ACCEPT_UPDATE") and ZL.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	elseif (event == "TRADE_PLAYER_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_MONEY_CHANGED") then --交易目标角色金额变化
        if _G["TradeFrame"].TargetTradeMoneyText and _G["TradeFrame"].TargetTradeMoneyText:IsShown() then
            if ZL.needTradeQianKuan and ZL.needTradeQianKuan <= GetTargetTradeMoney() then
                _G["TradeFrame"].TargetTradeMoneyText:SetText("|cffffff00√欠款：|r" .. GetMoneyString(ZL.needTradeQianKuan))
            else
                _G["TradeFrame"].TargetTradeMoneyText:SetText("|cffff0000欠款：|r" .. GetMoneyString(ZL.needTradeQianKuan))
            end
        end
        if ZL.tradePartner then Trade_UpdateMoney() end
    elseif event == "PLAYER_TRADE_MONEY" then
        if _G["TradeFrame"].PlayerTradeMoneyText then
            _G["TradeFrame"].PlayerTradeMoneyText:SetText("|cffffff00金额：|r" .. GetMoneyString(GetPlayerTradeMoney() or 0))
        end
        if ZL.tradePartner then Trade_UpdateMoney() end
    elseif (event == "UI_INFO_MESSAGE") then
        if arg[2] == ERR_TRADE_COMPLETE  then
            if ZL.tradePartner and ZL_CURRENT["IncomeList"] and PlayerIsML() then
                for _, itemlink in ipairs(ZL.MLTradeItems) do
                    for index, data in ipairs(ZL_CURRENT["IncomeList"]) do
                        local isTrue
                        if data.itemList and next(data.itemList, nil) then
                            for _itemlink, _data in pairs(data.itemList) do
                                if (not _data.isTraded) and itemlink == _itemlink and data.player == ZL.tradePartner then
                                    ZL_CURRENT["IncomeList"][index]["itemList"][itemlink]["isTraded"] = true
                                    isTrue = true
                                    break
                                end
                            end
                        end
                        if isTrue then break end
                    end
                end
                --下面为新增数据库
                if ZL.tradeMoneyOther > 0 then
                    --判断是否有欠款
                    local playerBuyList = ZL.GetPlayerBuyList()
                    local balanceAmount = 0
                    local playerPayToMLamount = 0
                    if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                        playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                    end
                    if playerBuyList[ZL.tradePartner] and playerBuyList[ZL.tradePartner].totalAmount then
                        balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                    else
                        balanceAmount = playerPayToMLamount
                    end
                    if PlayerIsML(ZL.tradePartner) then
                        balanceAmount = 0
                    end
                    if balanceAmount < 0 then -- 有欠款则直接记录
                        if not ZL_CURRENT.playerPayToML then ZL_CURRENT.playerPayToML = {} end
                        ZL_CURRENT.playerPayToML[ZL.tradePartner] = (ZL_CURRENT.playerPayToML[ZL.tradePartner] or 0) + ZL.tradeMoneyOther
                        ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                    else --没有欠款，则弹出提示框选择是代交还是自己交或者只是普通的交易不记录
                        local data = {tradeMoneyOther = ZL.tradeMoneyOther, tradePartner = ZL.tradePartner}
                        StaticPopup_Show("ZL_CONFIRMTRADERNAME", ZL.tradePartner, nil, data, ZL.GroupMembersDropdown)
                    end
                end
                ZL.tradePartner = nil
                ZL.AuctionFrame2.Update()
            end
            if ZL.tradeGongZi and PlayerIsML() then
                ZL_CURRENT.tradeGongZi = ZL_CURRENT.tradeGongZi or {}
                ZL_CURRENT.tradeGongZi[ZL.tradeName] = ZL.tradeGongZi
                --剔除邮寄名单
                if ZL_CURRENT["mailPlayers"] then
                    ZL_CURRENT["mailPlayers"][ZL.tradeName] = nil
                end
                ZL.tradeName = nil
                ZL.tradeGongZi = nil
                ZL.tradeGroupMsg = nil
                ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            elseif ZL.tradeGroupGongZi and PlayerIsML() then
                local pruneName = ZL.pruneCrossRealm(ZL.tradeName)
                local raidIndex = UnitInRaid(pruneName)
                if raidIndex then
                    MyAddon:TransmitAddonInfo2("AUTOAUC MY" .. raidIndex, {type="groupGongZi"}, "WHISPER", pruneName)
                end
                ZL_CURRENT.tradeGroupGongZi = ZL_CURRENT.tradeGroupGongZi or {}
                ZL_CURRENT.tradeGroupGongZi[tostring(ZL.tradeGroup)] = ZL.tradeGroupGongZi
                ZL_CURRENT.tradeGongZi = ZL_CURRENT.tradeGongZi or {}
                for name, gongzi in pairs(ZL.tradeGroupGongZi) do
                    ZL_CURRENT.tradeGongZi[name] = gongzi
                    --剔除邮寄名单
                    if ZL_CURRENT["mailPlayers"] then
                        ZL_CURRENT["mailPlayers"][name] = nil
                    end
                end
                SendChatMessage(ZL.tradeGroupMsg[1], "RAID")
                C_Timer.After(0.2, function ()
                    for i = 2, #ZL.tradeGroupMsg do
                        SendChatMessage(ZL.tradeGroupMsg[i], "RAID")
                    end
                    ZL.tradeGroupMsg = nil
                end)
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
                ZL.tradeName = nil
                ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            elseif ZL.otherTradeGongZi and (not PlayerIsML()) then
                ZL_PLAYERLIST.otherTradeGongZi = ZL_PLAYERLIST.otherTradeGongZi or {}
                ZL_PLAYERLIST.otherTradeGongZi[ZL.tradeName] = ZL.otherTradeGongZi
                ZL.tradeName = nil
                ZL.otherTradeGongZi = nil
                ZL.tradeGroupMsg = nil
            end
        else
            if isTradeFailed(arg[2]) then
                ZL.tradeGongZi = nil
                ZL.tradeName = nil
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
                ZL.otherTradeGongZi = nil
            end
		end
	elseif (event == "UI_ERROR_MESSAGE") then
        -- if arg[2] == ERR_PLAYER_WRONG_FACTION then
        --     print("邀请失败，对立阵营！")
        -- end
    elseif (event == "PLAYER_ENTERING_WORLD") then
        if not ZL.OverviewFrame then ZL:CreateOverviewFrame() end
        if not ZL.BillOverviewFrame then ZL.CreateBillOverviewFrame() end
        if not ZL.ReconciliationFrame then ZL:CreateReconciliationFrame() end
        C_FriendList.ShowFriends()
        C_WowTokenPublic.UpdateMarketPrice()
        --切换地图的时候才触发，比如进出副本
        if (not arg[1]) and (not arg[2]) and (IsInRaid(1) or IsInGroup(1)) then
            RequestRaidInfo()
        end
        C_Timer.After(3, function ()
            --获取交易剩余时间定时器
            if not ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(2, function ()
                    ZL.GetRemainingTradeTime()
                end)
            end

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

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

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

                if _G["AtlasLoot_Button_1"] then
                    local count = 1
                    while _G["AtlasLoot_Button_" .. count] do
                        _G["AtlasLoot_Button_" .. count]:HookScript("OnClick", function (self, button)
                            if button == "RightButton" and (not IsModifierKeyDown()) then
                                local selectCharKey = ZL.ConcernFrame.profileDropdown:GetText()
                                selectCharKey = selectCharKey:match("^|T%d+:0:0:2:0|t (.+)")
                                if not selectCharKey then return end
                                if (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
                                (not ZL.opt.concernList[selectCharKey]["itemList"][tonumber(self.ItemID)]) then
                                    ZL.addItem(self.ItemID)
                                else
                                    ZL.deleteItem(self.ItemID)
                                end
                            end
                        end)
                        count = count + 1
                    end
                end
            end)
        end
    elseif (event == "BAG_UPDATE_DELAYED") then
        if ZL.opt.waitingBagHighLight or ZL.opt.auctioningBagHighLight or ZL.opt.successBagHighLight
        or ZL.opt.failedBagHighLight or ZL.opt.lgnoreBagHighLight then
            ZL.BagHighLight()
        end
    elseif (event == "BAG_OPEN") then
        ZL.BagHighLight()
    elseif (event == "PLAYER_REGEN_ENABLED") then
        if ZL.opt.ZLAuctionFrameIsShown then
            ZL.AuctionFrame2:Show()
        end
        if ZL.opt.remainingTradeTimeBtnValue then
            ZL.ZLRemainingTradeTimeFrame:Show()
        end
        if ZL.opt.ItemSettingFrameIsShown then
            ZL.ItemSettingFrame:Show()
        end
        if ZL.opt.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Show()
        end
        if ZL.opt.SettingFrameIsShown then
            ZL.OpenAceConfigDialog("金团拍卖助手")
        end
        if ZL.opt.ZLRolesOverViewFrameIsShown then
            ZL.RolesOverViewFrame:Show()
        end
    elseif (event == "PLAYER_REGEN_DISABLED") then
        --进入战斗，隐藏窗口
        if ZL.opt.AuctionFrameHide then
            ZL.AuctionFrame2:Hide()
        end
        if ZL.opt.RemainingTradeTimeFrameHide then
            ZL.ZLRemainingTradeTimeFrame:Hide()
        end
        if ZL.opt.ItemSettingFrameHide then
            ZL.ItemSettingFrame:Hide()
        end
        if ZL.opt.AuctionRecordFrameHide then
            ZL.AuctionRecordFrame:Hide()
        end
        if ZL.opt.SettingFrameHide then
            if LibStub("AceConfigDialog-3.0").OpenFrames["金团拍卖助手"] then
                ZL.opt.SettingFrameIsShown = true
                LibStub("AceConfigDialog-3.0"):Close("金团拍卖助手")
            else
                ZL.opt.SettingFrameIsShown = false
            end
        end
        if ZL.opt.RolesOverViewFrameHide then
            ZL.RolesOverViewFrame:Hide()
        end
    elseif event == "CHAT_MSG_SYSTEM" then -- and not InCombatLockdown()
        local success, result = pcall(function()
            return (arg[1] == ERR_FRIEND_NOT_FOUND)
        end)
        if not success then
            -- print(type(arg[1])=="string", "|cffff0000无法获取系统消息：|r", arg[1], arg[1], arg[1], arg[1], arg[1], arg[1], arg[1])
            return
        end
        if arg[1] == ERR_FRIEND_NOT_FOUND then
            if ZL.threadId and ZL.threadId["coroutineIsOnline"] then
                ZL.PlayerIsOnline = select(2, coroutine.resume(ZL.threadId["coroutineIsOnline"]))
                ZL.IsOnlinePlayer = nil
            end
        elseif arg[1] == ERR_PARTY_CONVERTED_TO_RAID then --"小队转化为团队"
            ZL.autoChangeLootMethod()
            if IsInRaid(1) and ZL.IsRaidLeader() then
                local lootMethod = GetLootMethod()
                if (lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                    if (not ZL.opt.appointMLName) or (not UnitInRaid(ZL.opt.appointMLName)) then
                        ZL.opt.appointMLName = ZL.GetFullName()
                    end
                    MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="requestback", appointMLName=ZL.opt.appointMLName})
                end
            end
        elseif ZL.IsOnlinePlayer and format(ERR_FRIEND_ADDED_S, ZL.IsOnlinePlayer) == arg[1] then
            ZL.PlayerIsOnline = select(2, coroutine.resume(ZL.threadId["coroutineIsOnline"]))
            ZL.IsOnlinePlayer = nil
        elseif arg[1] == INSTANCE_SAVED then
            if IsInRaid(1) or IsInGroup(1) then
                RequestRaidInfo()
            end
            if IsInRaid(1) then
                C_Timer.After(2, function ()
                    local _, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
                    for i = 1, GetNumSavedInstances() do
                        local _, lockoutId, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
                        if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                            ZL_CURRENT.lockoutId = lockoutId
                            break
                        end
                    end
                end)
            end
        elseif arg[1] == ERR_GROUP_DISBANDED or arg[1] == ERR_LEFT_GROUP_YOU then
            previousRoster = {}
            ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
        elseif ZL.rollTimer and (not ZL.rollTimer:IsCancelled()) and arg[1]:match("(.+)掷出(%d+)（1%-100）") then
            ZL.rollList = ZL.rollList or {}
            local playerName, rollNumber = arg[1]:match("(.+)掷出(%d+)（1%-100）")
            playerName = ZL.GetClassColorName(playerName)
            rollNumber = tonumber(rollNumber)
            if not ZL.rollList[playerName] then
                ZL.rollList[playerName] = {rollNumber, GetTime()*1000}
                ZL.updateRollGameToolTip(ZL.AuctionFrame2.rollBtn)
            end
        elseif IsInRaid(1) and (strmatch(arg[1], ERR_RAID_MEMBER_ADDED_S:gsub("%%s", "(.+)")) or arg[1] == ERR_PARTY_CONVERTED_TO_RAID
        or arg[1] == "^你加入了一个团队。$" or strmatch(arg[1], ERR_NEW_LOOT_MASTER_S:gsub("%%s", "(.+)"))) then
            --发送自己的版本号
            if PlayerIsML() then
                ZL.quickMasterButton:Show()
                MyAddon:TransmitAddonInfo("AUTOAUC PRO", ZL.globalConfigData())
            else
                ZL.quickMasterButton:Hide()
            end
            ZL.AuctionFrame2:Update()
        end
    elseif (event == "GROUP_FORMED" or event == "GROUP_JOINED") and GetNumGroupMembers() > 1 then
        if event == "GROUP_JOINED" and IsInRaid(1) and not ZL.IsRaidLeader() then
            local lootMethod = GetLootMethod()
            if (lootMethod == "group" or lootMethod == 3 or lootMethod == "personalloot" or lootMethod == 5) then
                MyAddon:TransmitAddonInfo2("AUTOAUC ML", {type="request"})
            end
        end
        local chatType
        if IsInRaid(1) then
            chatType = "RAID"
        elseif IsInGroup(1) then
            chatType = "PARTY"
        end
        if chatType then
            local data = {type="request"}
            MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, chatType, nil, "BULK")
        end
    elseif event == "GROUP_LEFT" then
        ZL.opt.appointMLName = nil
        local data = {type="request"}
        MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "GUILD", nil, "BULK")
        if ZL_CURRENT["auctionlist"] then
            local isUpdate
            for num, _data in ipairs(ZL_CURRENT["auctionlist"]) do
                if _data.state == "auctioning" then
                    isUpdate = true
                    ZL_CURRENT.auctionlist[num].state = "waiting"
                    ZL_CURRENT.auctionlist[num].endTime = nil
                    ZL_CURRENT.auctionlist[num].isPaused = nil
                    ZL_CURRENT.auctionlist[num].bidderlist = {}
                end
            end
            if isUpdate then
                ZL.AuctionFrame2:Update()
                ZL.miniMapIconAnimation()
            end
        end
    elseif (event == "ENCOUNTER_END") then
        if arg[5] == 1 and (IsInRaid(1) or IsInGroup(1)) then
            RequestRaidInfo()
        end
    elseif (event == "UPDATE_INSTANCE_INFO") then
        local channel
        if IsInRaid(1) then
            channel = "RAID"
        elseif IsInGroup(1) then
            channel = "PARTY"
        end
        if channel then
            local data = {
                type="myVer", ver=ZL.addonVersion, autoNoticeFoodInRaid=ZL.opt.autoNoticeFoodInRaid,
                confirmLootAnnounce=ZL.opt.confirmLootAnnounce, instancesInfo = ZL.GetPlayerSavedInstanceInfo(),
            }
            MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, channel, nil, "BULK")
        end
    elseif (event == "TOKEN_MARKET_PRICE_UPDATED") then
        ZL.AuctionFrame2.WowTokenBtn.price = C_WowTokenPublic.GetCurrentMarketPrice()
    elseif event == "RAID_INSTANCE_WELCOME" then
        if not IsInRaid(1) then return end
        local instanceName = arg[1]
        C_Timer.After(1, function ()
            local name, _, _, difficultyName, maxPlayers, _, _, instanceID = GetInstanceInfo()
            if instanceID == ZL_CURRENT.instanceID and maxPlayers == ZL_CURRENT.maxPlayers then
                local todayDate = date("%Y-%m-%d", GetServerTime())
                if ZL_CURRENT.auctiondate and (((ZL_CURRENT.auctiondate):match("^(.-)%s")) ~= todayDate) then
                    local msgStr = "|cffffd100" .. instanceName .. "|r已存在|cffffd100" .. ZL_CURRENT.auctiondate .. "|r拍卖记录，是否重置？"
                    StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr, nil, {type="更新日期"})
                end
            else
                ZL_CURRENT.bossName = nil
                difficultyName = difficultyName:gsub("人", ""):gsub("（", ""):gsub("）", "")
                difficultyName = difficultyName ~= "" and name .. "(" .. difficultyName .. ")" or name
                local msgStr = "已进入新副本|cffffd100" .. instanceName .. "|r，是否重置当前拍卖数据？"
                StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr, nil, {type="更新副本", instanceID=instanceID, maxPlayers=maxPlayers, name=difficultyName})
            end
        end)
    elseif event == "START_LOOT_ROLL" then
        local inInstance, instanceType = IsInInstance()
        if not (IsInRaid(1) and inInstance and instanceType == "raid") then return end
        local rollID = arg[1]
        if not rollID then return end
        local itemlink = GetLootRollItemLink(rollID)
        if not itemlink then return end
        local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
        local _, auctionFilter = isFilterItem(itemId)
        if not auctionFilter then
            local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality)
            local _, _, itemQuality, itemLevel, _, itemType, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
            if itemQuality >= minQuality then
                local lootQuantity = select(3, GetLootRollItemInfo(rollID))
                local index
                local itemindex = 1
                if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                    for num, data in ipairs(ZL_CURRENT.auctionlist) do
                        if (data.itemlink == itemlink) then
                            itemindex = itemindex + 1
                            if not ZL.opt.notItemStack and data.state ~= "success" and data.state ~= "auctioning" then
                                index = num
                            end
                        end
                    end
                end
                local spawnUID = {}
                local bossName = ZL_CURRENT.bossName or "其他"
                if itemId == 47242 then --北伐奖章直接放到其他分类
                    bossName = "其他"
                end
                local spawnUIDkey = itemId .. rollID .. GetServerTime()
                spawnUID[spawnUIDkey] = {bossName=bossName, itemGUID={}}
                if index then
                    local fdata = ZL_CURRENT.auctionlist[index]
                    ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                    if fdata.stackCount == 1 then
                        ZL_CURRENT.auctionlist[index]["spawnUID"][spawnUIDkey] = {bossName=bossName, itemGUID={}}
                    end
                    if fdata.isPackage then
                        --如果是打包物品则更新[打包拍卖]数量
                        local __data, __index = ZL.FetchDataFromItemId("[打包拍卖]", 1)
                        if __index then
                            ZL_CURRENT.auctionlist[__index]["itemList"][itemlink]["itemCount"] = __data["itemList"][itemlink]["itemCount"] + lootQuantity
                        end
                    end
                    fdata = ZL_CURRENT.auctionlist[index]
                    if fdata.state == "failed" then
                        --如果是流拍物品，20秒后放到流拍包里面，20秒后如果在背包里面还没查询到该物品，将不再自动调整，需手动
                        C_Timer.After(20, function ()
                            ZL.reportFailedItem(true)
                        end)
                    end
                else
                    if (not ZL_CURRENT.globalConfig) then
                        ZL_CURRENT.globalConfig = ZL.globalConfigData()
                    end
                    local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                    bidIncrement = ZL.GetDiffrentIncrementBid(startbidamount, bidIncrement)
                    local data2 = {
                        type = "自动创建",
                        itemId = itemId,
                        itemlink = itemlink,
                        itemindex = itemindex,
                        startbidamount = startbidamount,
                        bidIncrement = bidIncrement,
                        state = "waiting",
                        lgnore = false,
                        endTime = nil,
                        bidderlist = {},
                        itemCount = lootQuantity,
                        sourceGUID = {},
                        spawnUID = spawnUID,
                        stackCount = stackCount,
                        bindType = bindType,
                        itemLevel = itemLevel,
                        itemSubType = itemSubType,
                        createTime = date("%Y-%m-%d %H:%M:%S", GetServerTime()),
                    }
                    ZL_CURRENT.auctionlist = ZL_CURRENT.auctionlist or {}
                    table.insert(ZL_CURRENT.auctionlist, data2)
                    if ZL.opt.autoPackage and bindType ~= 1 and PlayerIsML() then
                        ZL.packageAuction(#ZL_CURRENT.auctionlist)
                    end
                end
                ZL.AuctionListSort()
            end
        end
    elseif event == "OWNED_AUCTIONS_UPDATED" or event == "AUCTION_CANCELED"
    or event == "AUCTION_HOUSE_AUCTION_CREATED"or event == "AUCTION_HOUSE_AUCTIONS_EXPIRED"
    or event == "AUCTION_OWNED_LIST_UPDATE" then
        getOwnAuctionItemsCount()
    elseif UnitName("player") == "潇湘笛韵" and (event == "UNIT_SPELLCAST_START" or event == "UNIT_SPELLCAST_CHANNEL_START") then
        if not arg[1] or arg[1] ~= "focus" or interruptSound or not UnitIsEnemy("player", arg[1]) then return end
        interruptSound = true
        local spellInfo = C_Spell.GetSpellInfo(arg[3])
        if spellInfo then
            ZL.SpeakText(spellInfo.name)
        end
    elseif event == "UNIT_SPELLCAST_STOP" or event == "UNIT_SPELLCAST_INTERRUPTED" or event == "UNIT_SPELLCAST_CHANNEL_STOP"
    or event == "UNIT_SPELLCAST_FAILED" then
        interruptSound = nil
    end
    arg:Release()
end

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