local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local pruneCrossRealm = ZL.pruneCrossRealm
local Prefix = ZL.Prefix
local emptytable = ZL.emptytable
local PlayerIsML = ZL.PlayerIsML
local GetStartAndIncrementBid = ZL.GetStartAndIncrementBid
local GetAuctioningCount = ZL.GetAuctioningCount
local fullwidthToHalfwidth = ZL.fullwidthToHalfwidth
local tableSort = ZL.tableSort
local LootSlotIsItem = ZL.LootSlotIsItem
local isFilterItem = ZL.isFilterItem
local TransmitAddonInfo_Pro = ZL.TransmitAddonInfo_Pro
local padZeros = ZL.padZeros
local msg_gsub = ZL.msg_gsub
local GetCurrentRoster = ZL.GetCurrentRoster
local GetMasterLootCandidates = ZL.GetMasterLootCandidates
local GetClassColorName = ZL.GetClassColorName
local ParseClassColorName = ZL.ParseClassColorName
local GetMLname = ZL.GetMLname
local CheckWaVersion = ZL.CheckWaVersion
local GetWeekDay = ZL.GetWeekDay
local InportToStatistics = ZL.InportToStatistics
local RGBAToHex = ZL.RGBAToHex
local GetDiffTime = ZL.GetDiffTime
local cGetItemInfo = C_Item and C_Item.GetItemInfo or GetItemInfo
local cGetItemIcon = C_Item and C_Item.GetItemIconByID or GetItemIcon

local previousRoster = {} --初始化团队成员
ZL.count = 0

local defaults = {
	profile = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 5,
		startBid = 300,
		increment = 100,
        baseAmount1 = 5000,
        baseAmount2 = 10000,
        baseAmount3 = 50000,
        bidIncrement1 = 500,
        bidIncrement2 = 1000,
        bidIncrement3 = 1000,
		minQuality = -1,
        lootMinQuality = -1,
		awardToML = false,
		buttonReenableDelay = 1,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = false,
        developerMode = false,
        announceRaidWarning = false,
        CountdownAnnounceRaidWarning = false,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistoryDays = 1,
        autoClearHistoryIncomeDays = 3,
        showIncomeDays = 3,
        overrideArchive = true,
        profanityFilter = true,
        IsVoiceReminder = true,
        IsTradeRemainingVoiceReminder = true,
        TradeRemainingTimer = 30,
        TradeRemainingReminderPinlv = 5,
        RLBuTieType = 1,
        ZLAuctionFrameTabId = 1,
        showAllWages = false,
        wagesGroupMembers = 0,
        MLChangeGroup = false,
        liupaiToggle = false,
        liupaiBagId = 0,
        liupaiBagId2 = 1,
        liupaiDirection = false,
        selfToggle = false,
        selfBagId = 0,
        selfDirection = false,
        BOEToggle = false,
        BOEBagId = 0,
        BOEDirection = false,
        emptyOneSpace = true,
        isSYNCAll = false,
        waitingBagHighLight = false,
        auctioningBagHighLight = false,
        successBagHighLight = false,
        failedBagHighLight = false,
        lgnoreBagHighLight = false,
        auctionStateTip = true,
        historyMaxAndMin = true,
        historyTrendChart = true,
        levelSort = false,
        timeSort = "up",
        autoAddStartBid = false,
        AuctionFrameHide = false,
        RemainingTradeTimeFrameHide = true,
        ItemSettingFrameHide = true,
        AuctionRecordFrameHide = true,
        SettingFrameHide = true,
        VoiceReminderSoundType = 1,
        startAuctionSound = true,
        intervalBidIncrement = false,
        maxFrameHide = false,
        bidColumnHide = false,
        startbidColumnHide = false,
        functionColumnHide = false,
        itemLevelHide = false,
        itemCountHide = false,
        itemIndexHide = false,
        itemNameHide = false,
        bidEditBoxHide = false,
        bidBtnHide = false,
        lgnoreBtnHide = true,
        bidCountsHide = false,
        startBidHide = false,
        inrementHide = false,
        startBtnHide = false,
        pauseBtnHide = false,
        countdownBtnHide = false,
        packageBtnHide = false,
        reverseBidBtnHide = false,
        syncBtnHide = false,
        delAuctionBtnHide = false,
        floatBidFrameHide = false,
        floatStartBidFrameHide = false,
        floatFunctionFrameHide = false,
        ShortcutTipHide = false,
        currentDetailToolTipHide = false,
        xiaoFeiToolTipHide = false,
        recordShortcutTipHide = false,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        YYSound = false,
        ZLRolesOverViewFrameScale = 1,
        auctionMode = "团队",
        autoPackage = true,
        quickBidIncrement = 500,
  	},
    global = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 5,
		startBid = 300,
		increment = 100,
        baseAmount1 = 5000,
        baseAmount2 = 10000,
        baseAmount3 = 50000,
        bidIncrement1 = 500,
        bidIncrement2 = 1000,
        bidIncrement3 = 1000,
		minQuality = -1,
        lootMinQuality = -1,
		awardToML = false,
		buttonReenableDelay = 1,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = false,
        developerMode = false,
        announceRaidWarning = false,
        CountdownAnnounceRaidWarning = false,
        ZLAuctionFrameIsShown = true,
        ItemSettingFrameIsShown = false,
        ZLAuctionRecordFrameIsShown = false,
        reloadUITimerJump = 600,
        isReloadUI = true,
        isShowItemLevel = true,
        ZLAuctionFrameScale = 1,
        ZLItemSettingFrameScale= 1,
        ZLAuctionRecordFrameScale = 1,
        ZLRemainingTradeTimeFrameScale =1,
        ZLRolesOverViewFrameScale = 1,
        auctionFaildNotCountdown = true,
        maxFrameFlashingReminder = true,
        ShowAuctionRecordFrameCheckButtonValue = false,
        autoClearHistoryDays = 1,
        autoClearHistoryIncomeDays = 3,
        showIncomeDays = 3,
        overrideArchive = true,
        profanityFilter = true,
        IsVoiceReminder = true,
        IsTradeRemainingVoiceReminder = true,
        TradeRemainingTimer = 30,
        TradeRemainingReminderPinlv = 5,
        RLBuTieType = 1,
        ZLAuctionFrameTabId = 1,
        showAllWages = false,
        wagesGroupMembers = 0,
        MLChangeGroup = false,
        liupaiToggle = false,
        liupaiBagId = 0,
        liupaiBagId2 = 1,
        liupaiDirection = false,
        selfToggle = false,
        selfBagId = 0,
        selfDirection = false,
        BOEToggle = false,
        BOEBagId = 0,
        BOEDirection = false,
        emptyOneSpace = true,
        isSYNCAll = false,
        waitingBagHighLight = false,
        auctioningBagHighLight = false,
        successBagHighLight = false,
        failedBagHighLight = false,
        lgnoreBagHighLight = false,
        auctionStateTip = true,
        historyMaxAndMin = true,
        historyTrendChart = true,
        levelSort = false,
        timeSort = "up",
        autoAddStartBid = false,
        AuctionFrameHide = false,
        RemainingTradeTimeFrameHide = true,
        ItemSettingFrameHide = true,
        AuctionRecordFrameHide = true,
        SettingFrameHide = true,
        VoiceReminderSoundType = 1,
        startAuctionSound = true,
        intervalBidIncrement = false,
        maxFrameHide = false,
        bidColumnHide = false,
        startbidColumnHide = false,
        functionColumnHide = false,
        itemLevelHide = false,
        itemCountHide = false,
        itemIndexHide = false,
        itemNameHide = false,
        bidEditBoxHide = false,
        bidBtnHide = false,
        lgnoreBtnHide = true,
        bidCountsHide = false,
        startBidHide = false,
        inrementHide = false,
        startBtnHide = false,
        pauseBtnHide = false,
        countdownBtnHide = false,
        packageBtnHide = false,
        reverseBidBtnHide = false,
        syncBtnHide = false,
        delAuctionBtnHide = false,
        floatBidFrameHide = false,
        floatStartBidFrameHide = false,
        floatFunctionFrameHide = false,
        ShortcutTipHide = false,
        currentDetailToolTipHide = false,
        xiaoFeiToolTipHide = false,
        recordShortcutTipHide = false,
        saveGroupMembersSound = true,
        overviewFramePlayerModelHide = true,
        realmName = true,
        unitLevel = true,
        itemLevel = true,
        TOC25 = true,
        TOC10 = true,
        OL25 = true,
        OL10 = true,
        ULD25 = true,
        ULD10 = true,
        VOA25 = true,
        VOA10 = true,
        weekQuest = true,
        heroDayQuest = true,
        taiTanDayQuest = true,
        kaiXuanCurrency = true,
        yingXiongCurrency = true,
        rongYuCurrency = true,
        jinBiCurrency = true,
        RolesOverViewFrameHide = true,
        YYSound = false,
	},
}
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]
}

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
    -- print( channelBaseName, type(channelBaseName), #channelBaseName)
    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
        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团")
                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 <= 0.1)) then
                    ZL.lastFilterText = text
                    ZL.lastFilterTime = GetTime()
                    SendSystemMessage(link)
                end
            end
        end
    end
    return false, text, player, l, cs, t, flag, channelId, channelIndex, channelBaseName, ...
end

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

local function mainInit(self, event, ...)
    local arg = emptytable(...)
    local AuctionFrame = ZL.AuctionFrame2
    local function formatTimestamp(text)
        if #text ~= 12 then
            return nil, "日期长度不是12位，格式不对！"
        end
        local year = "20" .. text:sub(1, 2)
        local month = text:sub(3, 4)
        local day = text:sub(5, 6)
        local hour = text:sub(7, 8)
        local minute = text:sub(9, 10)
        local second = text:sub(11, 12)
        return string.format("%s-%s-%s %s:%s:%s", year, month, day, hour, minute, second)
    end
    local function InportToStatisticsFromBiaoGe()
        local msgStr
        if _G["BiaoGe"] and _G["BiaoGe"]["History"] then
            local incomeCounts = 0
            for _, value1 in pairs(_G["BiaoGe"]["History"]) do
                for key2, value2 in pairs(value1) do
                    local auctiondate = formatTimestamp(tostring(key2))
                    if auctiondate then
                        local UnitGuid, RealmName, FactionGroup, listkey
                        local IncomeList = {}
                        if value2["raidRoster"] and value2["raidRoster"]["realm"] then
                            RealmName = value2["raidRoster"]["realm"]
                        end
                        if RealmName and value2["lockoutIDtbl"] and next(value2["lockoutIDtbl"], nil) then
                            local linshiList = {}
                            for _, lockoutValue in pairs(value2["lockoutIDtbl"]) do
                                tinsert(linshiList, lockoutValue["lockoutID"])
                            end
                            table.sort(linshiList)
                            UnitGuid = table.concat(linshiList)
                        end
                        if UnitGuid then
                            for key3, value3 in pairs(value2) do
                                local bossIndex = tonumber(key3:match("boss(%d+)"))
                                local isBreak
                                if bossIndex then
                                    for i = 1, 20 do
                                        if value3["maijia" .. i] and value3["zhuangbei" .. i] and value3["jine" .. i] and tonumber(value3["jine" .. i]) and tonumber(value3["jine" .. i]) > 0 then
                                            if (not FactionGroup) then
                                                if value3["factionGroup" .. i] == "Horde" then
                                                    FactionGroup = "部落"
                                                else
                                                    FactionGroup = "联盟"
                                                end
                                            end
                                            if not FactionGroup then
                                                isBreak = true
                                                break
                                            else
                                                if not listkey then
                                                    listkey = RealmName .. "|" .. FactionGroup .. "|" .. UnitGuid .. "|" .. auctiondate
                                                end
                                                if ZL_Statistics[listkey] then
                                                    isBreak = true
                                                    break
                                                else
                                                    local oldItemLink = value3["zhuangbei" .. i]
                                                    local itemlink, itemCount = oldItemLink:match("^(|c........|Hitem:.+|r)H?x?(%d*)")
                                                    if itemlink then
                                                        --判断是否打包交易
                                                        local isZipTrade
                                                        if value2["tradeTbl"] and #value2["tradeTbl"] > 0 then
                                                            local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                                                            local isBreak2
                                                            for _, tradeTblValue1 in ipairs(value2["tradeTbl"]) do
                                                                for _, tradeTblValue2 in ipairs(tradeTblValue1) do
                                                                    if tradeTblValue2["i"] == i and tradeTblValue2["itemID"] == itemId and tradeTblValue2["b"] == bossIndex then
                                                                        isZipTrade = true
                                                                        isBreak2 = true
                                                                        break
                                                                    end
                                                                end
                                                                if isBreak2 then break end
                                                            end
                                                        end
                                                        if not isZipTrade then
                                                            local r, g, b = unpack(value3["color" .. i])
                                                            r = r*255
                                                            g = g*255
                                                            b = b*255
                                                            local player = RGBAToHex(r, g, b) .. value3["maijia" .. i] .. "|r"
                                                            itemCount = tonumber(itemCount) or 1
                                                            tinsert(IncomeList, {
                                                                ["player"] = player,
                                                                ["notes"] = itemlink,
                                                                ["itemCount"] = itemCount,
                                                                ["amount"] = tonumber(value3["jine" .. i])
                                                            })
                                                            incomeCounts = incomeCounts + 1
                                                        end
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                                if isBreak then break end
                            end
                        end
                        if #IncomeList > 0 then
                            ZL_Statistics[listkey] = {
                                ["IncomeList"] = IncomeList,
                                ["UnitGuid"] = UnitGuid,
                                ["FactionGroup"] = FactionGroup,
                                ["auctiondate"] = auctiondate:match("^(%d+-%d+-%d+)"),
                                ["RealmName"] = RealmName,
                            }
                            IncomeList = nil
                        end
                    end
                end
            end
            if incomeCounts > 0 then
                msgStr = "本次总共导入" .. incomeCounts .. "条成交数据！"
            else
                msgStr = "本次没有数据导入！"
            end
            ZL.Print(nil, nil, nil, nil, nil, msgStr)
        else
            msgStr = "未检测到BiaoGe历史数据，请检查是否有开启插件并且存在历史数据！"
            ZL.Print(nil, nil, nil, nil, nil, msgStr)
        end
    end
    local function Trade_UpdateMoney()
        if PlayerIsML() then
            ZL.tradeMoneyML = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyOther = GetTargetTradeMoney() / 10000
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradeMoneyOther = GetPlayerTradeMoney() / 10000
            ZL.tradeMoneyML = GetTargetTradeMoney() / 10000
        end
    end
    local function Trade_UpdateItemInfo(id)
        local itemLink
        if PlayerIsML() then
            itemLink = GetTradePlayerItemLink(id)
        elseif PlayerIsML(GetUnitName("npc", false)) then
            itemLink = GetTradeTargetItemLink(id)
        end
        if itemLink then
            ZL.MLTradeItems[id] = itemLink
        end
    end
	local tradeFailed = {
		ERR_TRADE_BAG,--"你不能交易装有物品的包";
		ERR_TRADE_BAG_FULL,--"交易失败，你没有足够的物品栏空间。";
		ERR_TRADE_BLOCKED_S,--"%s要求进行交易，你拒绝了。";
		ERR_TRADE_BOUND_ITEM,--"你不能交易一件灵魂绑定物品";
		ERR_TRADE_CANCELLED,--"交易取消。";
		ERR_TRADE_EQUIPPED_BAG,--"你无法交易已经装备的包裹。";
		ERR_TRADE_FACTION_SPECIFIC,--"你无法与对立阵营交易阵营特色物品。";
		ERR_TRADE_GROUND_ITEM,--"你不能交易一件还放在地上的物品。";
		ERR_TRADE_MAX_COUNT_EXCEEDED,--"你拥有超过一件";
		ERR_TRADE_NOT_ON_TAPLIST,--"你只能将绑定物品交易给拥有该物品起始拾取资格的玩家。";
		ERR_TRADE_QUEST_ITEM,--"你不能交易一件任务物品";
		ERR_TRADE_REQUEST_S,--"%s想要和你进行交易。";
		ERR_TRADE_SELF,--"你不能与自己交易。";
		ERR_TRADE_TARGET_BAG_FULL,--"交易失败，交易目标没有足够的物品栏空间。";
		ERR_TRADE_TARGET_DEAD,--"你不能和已死亡的玩家交易";
		ERR_TRADE_TARGET_MAX_COUNT_EXCEEDED,--"交易对象已经拥有该类唯一物品。";
		ERR_TRADE_TARGET_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS,--"你的交易对象只能携带%d个%s";
		ERR_TRADE_TEMP_ENCHANT_BOUND,--"你不能交易带有临时附魔的物品。";
		ERR_TRADE_TOO_FAR,--"交易目标太远";
		ERR_TRADE_WRONG_REALM,--"你只能与来自其它服务器的玩家交易魔法制造的物品";
	}
	local function isTradeFailed(arg2)
		for _,v in pairs(tradeFailed) do
			if arg2 == v then
				return true
			end
		end
		return false
	end
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        local function OnHyperlinkEnter(self, link)
            local linkType, missionID, txt = strsplit(":", link)
            if linkType == "item" then
                -- 在这里可以显示自定义的悬浮提示框
                -- GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT", 30, -45)
                -- GameTooltip:AddLine("玩家: " .. missionID)
                -- GameTooltip:Show()

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

        local function OnHyperlinkLeave()
            GameTooltip:Hide()
        end

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

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

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

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

        ZL.options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(ZL.db)
		ZL.options.args.profiles.order = -1
		LibStub("AceConfig-3.0"):RegisterOptionsTable("金团拍卖助手", ZL.options)
        LibStub("AceConfigDialog-3.0"):SetDefaultSize("金团拍卖助手", 700, 500)
        --将选项表添加到暴雪的内置“界面”选项面板中
        if WOW_PROJECT_ID ~= 2 then
            LibStub("AceConfigDialog-3.0"):AddToBlizOptions("金团拍卖助手", "|cff0011ffAutoAuction|r")
        end
        --Minimap Icon Creation
		ZL.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga",
			OnClick = function(self, button)
                if button == "LeftButton" then
                    StaticPopup_Show("ZL_TEST")
                    if IsShiftKeyDown() then
                        ReloadUI()
                    elseif IsAltKeyDown() then
                        ZL.opt.minIconTooltipHide = true
                        GameTooltip:Hide()
                        local msgStr = "|cff00ff00Alt+右键|r：打开按钮提示"
                        ZL.Print(nil, nil, nil, nil, nil, msgStr)
                    else
                        ZL.OpenAceConfigDialog("金团拍卖助手")
                    end
                elseif button == "RightButton" then
                    if IsShiftKeyDown() then
                        InportToStatisticsFromBiaoGe()
                    elseif IsAltKeyDown() then
                        ZL.opt.minIconTooltipHide = false
                    else
                        ZL.RolesOverViewFrame.locked = true
                        ZL.opt.ZLRolesOverViewFrameIsShown = true
                        ZL.GetOwnRolesData()
                        ZL.RolesOverViewFrame:Show()
                    end
                end
			end,
		})
        
        function ZL.LDB:OnTooltipShow()
            if not ZL.opt.minIconTooltipHide then
                self:AddLine("金团拍卖助手(|cffffffff" .. ZL.addonVersion .. "|r)")
                self:AddLine("自动化拍卖、出价、记账、工资分配、一键批量邮寄工资和补贴、离队计算工资等", 1, 1, 1, true)
                self:AddLine(" ")
                self:AddLine("左键|cffffffff: 打开设置窗口|r ")
                self:AddLine("Shift+左键：|cffffffff重新加载用户界面|r")
                self:AddLine("|cff00B2EEAlt+左键：|r|cffffffff隐藏按钮提示|r")
                self:AddLine("右键|cffffffff: 固定打开角色信息总览窗口|r ")
                self:AddLine("Shift+右键：|cffffffff从BiaoGe插件导入历史成交数据|r")
                self:AddLine("Alt+右键：|cffffffff打开按钮提示|r")
            end
            if not ZL.RolesOverViewFrame.locked then
                ZL.GetOwnRolesData()
                local function IsFrameOverButton(frame, button)
                    if not frame:IsVisible() or not button:IsVisible() then
                        return false
                    end
                    local fX, fY, fWidth, fHeight = frame:GetRect()
                    local bX, bY, bWidth, bHeight = button:GetRect()
                    -- 判断矩形是否相交
                    return fX < bX + bWidth and
                           fX + fWidth > bX and
                           fY < bY + bHeight and
                           fY + fHeight > bY
                end
                local function MoveFrameAwayFromButton(frame, button)
                    if not IsFrameOverButton(frame, button) then return end
                    local bL, bB, bWidth, bHeight = button:GetRect()
                    local bR = GetScreenWidth() - (bL + bWidth)
                    local bT = GetScreenHeight() - (bB + bHeight)
                    frame:ClearAllPoints()
                    if bR > bL then
                        if bT > bB then
                            frame:SetPoint("BOTTOMLEFT", button, "TOPRIGHT", 0, 0)
                        else
                            frame:SetPoint("TOPLEFT", button, "BOTTOMRIGHT", 0, 0)
                        end
                    else
                        if bT > bB then
                            frame:SetPoint("BOTTOMRIGHT", button, "TOPLEFT", 0, 0)
                        else
                            frame:SetPoint("TOPRIGHT", button, "BOTTOMLEFT", 0, 0)
                        end
                    end
                end
                local RolesOverViewFrame = ZL.RolesOverViewFrame
                RolesOverViewFrame:Show()
                MoveFrameAwayFromButton(RolesOverViewFrame, ZL.minimapicon.objects["ZLAUTOLDB"])
            end
        end
        function ZL.LDB:OnEnter()
            ZL.LDB.OnTooltipShow(GameTooltip)
            GameTooltip:Show()
        end
        function ZL.LDB:OnLeave()
            if not ZL.RolesOverViewFrame.locked then
                ZL.RolesOverViewFrame:Hide()
            end
            GameTooltip:Hide()
        end
        ZL.minimapicon = LibStub("LibDBIcon-1.0")
		ZL.minimapicon:Register("ZLAUTOLDB", ZL.LDB, ZL.db.global)
        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

        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.maxFrame then ZL:CreateMaxAuctionFrame() end
        if not ZL.ItemSettingFrame then ZL:CreateItemSettingFrame() end

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

        if not ZL.ItemDateBar then ZL:CreateItemDateBar() end
        if not ZL.ItemWeekDayBar then ZL:CreateItemWeekDayBar() end
        if not ZL.OverviewFrame then ZL:CreateOverviewFrame() end
        if not ZL.GroupMembersDropdown then ZL.CreateGroupMembersDropdown() end
        if not ZL.ReconciliationFrame then ZL:CreateReconciliationFrame() end

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

                                    if data.RealmName == RealmName and data.FactionGroup == FactionGroup then
                                        tinsert(linshiList_local, tonumber(aveDayAmount))
                                        if not dataList_local[aveDayAmount] then dataList_local[aveDayAmount] = {} end
                                        tinsert(dataList_local[aveDayAmount], data.auctiondate)
                                        totalAmount_local = totalAmount_local + incomedata.amount
                                        totalCount_local = totalCount_local + incomedata.itemCount
                                    end
                                end
                            end
                        end
                    end
                    if #linshiList_local > 0 then
                        table.sort(linshiList_local)
                        smax_local = linshiList_local[#linshiList_local]
                        smin_local = linshiList_local[1]
                        save_local = math.floor(totalAmount_local/totalCount_local)
                        local smaxdatelist_local = dataList_local[tostring(smax_local)]
                        table.sort(smaxdatelist_local)
                        smaxdate_local = smaxdatelist_local[#smaxdatelist_local]
                        local smindatelist_local = dataList_local[tostring(smin_local)]
                        table.sort(smindatelist_local)
                        smindate_local = smindatelist_local[#smindatelist_local]
                    end
                    if #linshiList_all > 0 then
                        table.sort(linshiList_all)
                        smax_all = linshiList_all[#linshiList_all]
                        smin_all = linshiList_all[1]
                        save_all = math.floor(totalAmount_all/totalCount_all)
                        local smaxdatelist_all = dataList_all[tostring(smax_all)]
                        table.sort(smaxdatelist_all)
                        smaxdate_all = smaxdatelist_all[#smaxdatelist_all]
                        local smindatelist_all = dataList_all[tostring(smin_all)]
                        table.sort(smindatelist_all)
                        smindate_all = smindatelist_all[#smindatelist_all]
                    end
                    dataList_all = nil
                    linshiList_all = nil
                    dataList_local = nil
                    linshiList_local = nil
                end
                if smax_local then
                    GameTooltip:AddLine("本服本阵营成交(|cffff0000仅供参考|r)：")
                    GameTooltip:AddLine("最高：|cffff0000" .. smax_local .. "（" .. smaxdate_local .."）|r")
                    GameTooltip:AddLine("最低：|cff00ff00" .. smin_local .. "（" .. smindate_local .."）|r")
                    GameTooltip:AddLine("均价：|cffffffff" .. save_local .."|r")
                    if ZL.opt.historyTrendChart then
                        for i = 1, 7 do
                            self:AddLine("　　　　　　")
                        end
                    end
                elseif smax_all then
                    GameTooltip:AddLine("所有成交(|cffff0000仅供参考|r)：")
                    GameTooltip:AddLine("最高：|cffff0000" .. smax_all .. "（" .. smaxdate_all .."）|r")
                    GameTooltip:AddLine("最低：|cff00ff00" .. smin_all .. "（" .. smindate_all .."）|r")
                    GameTooltip:AddLine("均价：|cffffffff" .. save_all .."|r")
                    if ZL.opt.historyTrendChart then
                        for i = 1, 7 do
                            self:AddLine("　　　　　　")
                        end
                    end
                else
                    GameTooltip:AddLine("没有历史成交数据")
                end
            end
        end
        GameTooltip:HookScript("OnTooltipSetItem", historyData)
        ItemRefTooltip:HookScript("OnTooltipSetItem", historyData)
        GameTooltip:HookScript("OnShow", function(self)
            if ZL.opt.historyTrendChart then
                C_Timer.After(0.1, function ()
                    local _, itemlink = self:GetItem()
                    if not itemlink then return end
                    local itemId
                    if type(itemlink) == "string" then
                        itemId = tonumber(itemlink:match("item:(%d+):"))
                    elseif type(itemlink) == "number" then
                        itemId = itemlink
                    end
                    if not itemId then return end
                    local RealmName, FactionGroup = GetRealmName(), select(2, UnitFactionGroup("player"))
                    local dateList_local = {}
                    local weekdayList_local = {
                        ["周一"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周二"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周三"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周四"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周五"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周六"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周日"]={totalAmount=0, totalCounts=0, aveAmount=0},
                    }
                    local dateList_all = {}
                    local weekdayList_all = {
                        ["周一"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周二"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周三"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周四"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周五"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周六"]={totalAmount=0, totalCounts=0, aveAmount=0},
                        ["周日"]={totalAmount=0, totalCounts=0, aveAmount=0},
                    }
                    if ZL_Statistics and next(ZL_Statistics, nil) then
                        -- local itemId = tonumber(itemlink:match("item:(%d+):"))
                        local weekday
                        for _, _data in pairs(ZL_Statistics) do
                            if type(_data) == "table" and _data.IncomeList and #_data.IncomeList > 0 then
                                for _, incomedata in ipairs(_data.IncomeList) do
                                    local _itemId = tonumber(incomedata.notes:match("|Hitem:(%d+):"))
                                    if _itemId == itemId then
                                        if not dateList_all[_data.auctiondate] then
                                            dateList_all[_data.auctiondate] = {totalAmount=0, totalCounts=0, aveAmount=0}
                                        end
                                        dateList_all[_data.auctiondate].totalAmount = dateList_all[_data.auctiondate].totalAmount + incomedata.amount
                                        dateList_all[_data.auctiondate].totalCounts = dateList_all[_data.auctiondate].totalCounts + incomedata.itemCount
                                        dateList_all[_data.auctiondate].aveAmount = math.floor(dateList_all[_data.auctiondate].totalAmount/dateList_all[_data.auctiondate].totalCounts)
                                        weekday = GetWeekDay(_data.auctiondate)
                                        weekdayList_all[weekday].totalAmount = weekdayList_all[weekday].totalAmount + incomedata.amount
                                        weekdayList_all[weekday].totalCounts = weekdayList_all[weekday].totalCounts + incomedata.itemCount
                                        weekdayList_all[weekday].aveAmount = math.floor(weekdayList_all[weekday].totalAmount/weekdayList_all[weekday].totalCounts)
    
                                        if _data.RealmName == RealmName and _data.FactionGroup == FactionGroup then
                                            if not dateList_local[_data.auctiondate] then
                                                dateList_local[_data.auctiondate] = {totalAmount=0, totalCounts=0, aveAmount=0}
                                            end
                                            dateList_local[_data.auctiondate].totalAmount = dateList_local[_data.auctiondate].totalAmount + incomedata.amount
                                            dateList_local[_data.auctiondate].totalCounts = dateList_local[_data.auctiondate].totalCounts + incomedata.itemCount
                                            dateList_local[_data.auctiondate].aveAmount = math.floor(dateList_local[_data.auctiondate].totalAmount/dateList_local[_data.auctiondate].totalCounts)
                                            weekdayList_local[weekday].totalAmount = weekdayList_local[weekday].totalAmount + incomedata.amount
                                            weekdayList_local[weekday].totalCounts = weekdayList_local[weekday].totalCounts + incomedata.itemCount
                                            weekdayList_local[weekday].aveAmount = math.floor(weekdayList_local[weekday].totalAmount/weekdayList_local[weekday].totalCounts)
                                        end
                                    end
                                end
                            end
                        end
                    end
                    local newDateList = {}
                    local aveAmountList = {}
                    local weekList = {
                        "周一", "周二", "周三", "周四", "周五", "周六", "周日",
                    }
                    local totalHeight = 0
                    local h2 = 0
                    -- 计算 GameTooltip 原有行高
                    local lineFont
                    for i = 1, GameTooltip:NumLines() do
                        local line = _G["GameTooltipTextLeft" .. i]
                        if line then --and line:IsVisible()
                            totalHeight = totalHeight + line:GetHeight()
                            if not lineFont and line:GetText() == "　　　　　　" then
                                h2 = line:GetHeight()
                                lineFont = line
                                break
                            end
                        end
                    end
                    totalHeight = totalHeight + 3*h2
                    if next(dateList_local, nil) then
                        for key, value in pairs(dateList_local) do
                            tinsert(newDateList, key)
                            tinsert(aveAmountList, value.aveAmount)
                        end
                        table.sort(newDateList)
                        local itemDateBar = ZL.ItemDateBar
                        -- itemDateBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemDateBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemDateBar:Show()
                        local maxValue = math.max(unpack(aveAmountList)) -- 最大值用于缩放
                        local pointSpacing = itemDateBar:GetWidth() / (#aveAmountList+1) -- 数据点之间的水平间距
                        local previousPoint
                        for _, f in ipairs(ZL.ItemDateBar.entries) do f:Hide() end
                        for i, date in ipairs(newDateList) do
                            -- 计算数据点的位置
                            local value = dateList_local[date]["aveAmount"]
                            local x = i * pointSpacing
                            local y = (value / maxValue) * (itemDateBar:GetHeight()-25)
                            local f = ZL.ItemDateBar.entries[i]
                            f:SetValues(x, y, previousPoint)
                            f:Show()
                            previousPoint = f.point
                        end
    
                        local itemWeekDayBar = ZL.ItemWeekDayBar
                        -- itemWeekDayBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemWeekDayBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemWeekDayBar:Show()
                        local aveWeekDayAmountList = {}
                        for i = 1, 7 do
                            tinsert(aveWeekDayAmountList, weekdayList_local[weekList[i]]["aveAmount"])
                        end
                        maxValue = math.max(unpack(aveWeekDayAmountList))
                        local barSpacing = (itemWeekDayBar:GetWidth()-20) / 7 -- 数据点之间的水平间距
                        local barWidth = barSpacing*0.9
                        local barHeight = itemWeekDayBar:GetHeight()
                        for i = 1, 7 do
                            local bar = itemWeekDayBar.entries[i]
                            bar:SetSize(barWidth, aveWeekDayAmountList[i]==0 and 0.001 or (aveWeekDayAmountList[i] / maxValue) * (barHeight-25))
                            if i == 1 then
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", 10, 0)
                            else
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", (i - 1) * barSpacing+10, 0)
                            end
                        end
                        itemDateBar:ClearAllPoints()
                        itemDateBar:SetPoint("TOPLEFT", lineFont, "BOTTOMLEFT", 0, h2/2)
                        itemDateBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                        itemWeekDayBar:ClearAllPoints()
                        itemWeekDayBar:SetPoint("TOP", itemDateBar, "BOTTOM")
                        itemWeekDayBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                    elseif next(dateList_all, nil) then
                        for key, value in pairs(dateList_all) do
                            tinsert(newDateList, key)
                            tinsert(aveAmountList, value.aveAmount)
                        end
                        table.sort(newDateList)
                        local itemDateBar = ZL.ItemDateBar
                        -- itemDateBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemDateBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemDateBar:Show()
                        local maxValue = math.max(unpack(aveAmountList)) -- 最大值用于缩放
                        local pointSpacing = itemDateBar:GetWidth() / (#aveAmountList+1) -- 数据点之间的水平间距
                        local previousPoint
                        for _, f in ipairs(ZL.ItemDateBar.entries) do f:Hide() end
                        for i, date in ipairs(newDateList) do
                            -- 计算数据点的位置
                            local value = dateList_all[date]["aveAmount"]
                            local x = i * pointSpacing
                            local y = (value / maxValue) * (itemDateBar:GetHeight()-30)
                            local f = ZL.ItemDateBar.entries[i]
                            f:SetValues(x, y, previousPoint)
                            f:Show()
                            previousPoint = f.point
                        end
    
                        local itemWeekDayBar = ZL.ItemWeekDayBar
                        -- itemWeekDayBar:SetWidth(GameTooltip:GetWidth()-20)
                        itemWeekDayBar:SetSize(GameTooltip:GetWidth()-20, 6*h2/2)
                        itemWeekDayBar:Show()
                        local aveWeekDayAmountList = {}
                        for i = 1, 7 do
                            tinsert(aveWeekDayAmountList, weekdayList_all[weekList[i]]["aveAmount"])
                        end
                        maxValue = math.max(unpack(aveWeekDayAmountList))
                        local barSpacing = (itemWeekDayBar:GetWidth()-20) / 7 -- 数据点之间的水平间距
                        local barWidth = barSpacing*0.9
                        local barHeight = itemWeekDayBar:GetHeight()
                        -- local h = 0
                        for i = 1, 7 do
                            local bar = itemWeekDayBar.entries[i]
                            -- h = bar.label:GetHeight()
                            bar:SetSize(barWidth, aveWeekDayAmountList[i]==0 and 0.001 or (aveWeekDayAmountList[i] / maxValue) * (barHeight-30))
                            if i == 1 then
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", 10, 0)
                            else
                                bar:SetPoint("BOTTOMLEFT", itemWeekDayBar, "BOTTOMLEFT", (i - 1) * barSpacing+10, 0)
                            end
                        end
                        -- h = itemDateBar:GetHeight() + itemWeekDayBar:GetHeight() + h + 8
                        itemDateBar:ClearAllPoints()
                        itemDateBar:SetPoint("TOPLEFT", lineFont, "BOTTOMLEFT", 0, h2/2)
                        itemDateBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                        itemWeekDayBar:ClearAllPoints()
                        itemWeekDayBar:SetPoint("TOP", itemDateBar, "BOTTOM")
                        itemWeekDayBar:SetFrameLevel(GameTooltip:GetFrameLevel() + 1)
                    end
                end)
            end
        end)
        GameTooltip:HookScript("OnHide", function (self)
            ZL.ItemDateBar:Hide()
            ZL.ItemWeekDayBar:Hide()
        end)
        _G["TradeFrame"]:HookScript("OnShow", function(self)
            if IsInRaid() then
                ZL.ShowAuctionRecordFrame:ClearAllPoints()
                ZL.ShowAuctionRecordFrame:SetPoint("BOTTOMRIGHT", _G["TradeFrame"], "TOPRIGHT", 20, 0)
                ZL.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 selectCharKey and (not ZL.opt.concernList) or (not ZL.opt.concernList[selectCharKey]) or
            (not ZL.opt.concernList[selectCharKey]["itemList"][itemId]) then
                tinsert(menuList, {
                    text = "关注",
                    func = function ()
                        ZL.addItem(itemId)
                    end,
                })
            else
                tinsert(menuList, {
                    text = "取消关注",
                    func = function ()
                        ZL.deleteItem(itemId)
                    end
                })
            end
            tinsert(menuList, {isSeparator = true})
            if PlayerIsML() then
                tinsert(menuList, {
                    text = "拍卖功能",
                    isTitle = true,
                })
                tinsert(menuList, {
                    text = "创建拍卖",
                    func = function ()
                        if stackCount == 1 then
                            ZL.ManualCreateAuctionItem(itemLink, 1)
                            local msgStr = "已创建拍卖物品：" .. itemLink
                            ZL.Print(nil, nil, nil, nil, nil, msgStr)
                        else
                            StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=nil})
                        end
                    end
                })
                if IsInRaid() and 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 = "开始"
                            elseif data.state == "auctioning" then
                                text = "取消"
                            elseif data.state == "success" then
                                text = "重拍"
                            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 = "拍卖倒数",
                                    func = function ()
                                        f.MLframe.functionFrame.CountDownBtn:Click()
                                    end
                                })
                            end
                            if (data.state == "failed" or data.state == "waiting") then
                                tinsert(menuList, {
                                    text = "快速拍卖",
                                    func = function ()
                                        local _data = {
                                            ["type"] = "指定人员",
                                            ["data"] = data,
                                        }
                                        data.index = index
                                        StaticPopup_Show("ZL_ADDINCOME", "收入", nil, _data)
                                    end
                                })
                            end
                            break
                        end
                    end
                end
            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(nil, nil, 1, 0, 0, msgStr)
                            end
                    end
                })
            end
            return menuList
        end
        --CTR+左键点击物品链接流拍物品自动开始拍卖
        hooksecurefunc("SetItemRef", function(link, text, button)
            local linkType, missionID, txt, arg4 = strsplit(":", link)
            if linkType == "garrmission" then
                if missionID == "AutoAuction" then
                    if txt == "账单" then
                        if button == "LeftButton" then
                            ZL.OverviewFrame:Update(ZL_CURRENT)
                            ZL.OverviewFrame:Show()
                            ZL.ReconciliationFrame:Hide()
                        end
                    elseif txt == "对账" then
                        if ZL.ReconciliationFrame:IsShown() then
                            ZL.ReconciliationFrame:Update()
                        else
                            ZL.ReconciliationFrame:Show()
                        end
                        ZL.OverviewFrame:Hide()
                    elseif txt == "YY号" and arg4 then
                        ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
                        ChatEdit_ChooseBoxForSend():SetText(arg4)
                        ChatEdit_ChooseBoxForSend():HighlightText()
                    end
                end
            elseif linkType == "item" then
                local _, itemLink = cGetItemInfo(link)
                if not itemLink then return end
                if button == "LeftButton" then
                    if (not IsModifierKeyDown()) then

                    elseif IsShiftKeyDown() and (not IsControlKeyDown()) and (not IsAltKeyDown()) then
                        ZL.ChatEditInsertLink(itemLink)
                    elseif (not IsShiftKeyDown()) and IsControlKeyDown() and (not IsAltKeyDown()) then

                    end
                elseif button == "RightButton" then
                    if ItemRefTooltip:IsVisible() then
                        ItemRefTooltip:Hide()
                    end
                    if (not IsModifierKeyDown()) then
                        ZL.GUI:ToggleMenu(self, SetItemRefActivityMenu(itemLink), 'cursor')
                    elseif (not IsShiftKeyDown()) and (not IsControlKeyDown()) and IsAltKeyDown() then
                        local itemId = tonumber(itemLink:match("|Hitem:(%d+):"))
                        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
                end
            end
        end)
        --CTR+右键点击背包物品自动创建拍卖物品
        hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", function(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            local itemLink = containerInfo.hyperlink
            if PlayerIsML() and IsInRaid() and button == "RightButton" and IsControlKeyDown() then
                local itemLoc = ItemLocation:CreateFromBagAndSlot(self:GetParent():GetID(), self:GetID())
                local itemGuid = C_Item.GetItemGUID(itemLoc)
                if (not ZL_CURRENT["itemGUIDUsed"]) or (not ZL_CURRENT["itemGUIDUsed"][itemGuid]) then
                    if not ZL_CURRENT["itemGUIDUsed"] then ZL_CURRENT["itemGUIDUsed"] = {} end
                    local itemId = containerInfo.itemID
                    local stackCount = select(8, cGetItemInfo(itemLink))
                    if stackCount == 1 then
                        ZL.ManualCreateAuctionItem(itemLink, 1, itemGuid)
                        ZL.Print(nil, nil, nil, nil, nil, "已创建拍卖物品：" .. itemLink)
                    else
                        StaticPopup_Show("ZL_ADDAUCTIONITEM", nil, nil, {itemId=itemId, itemGuid=itemGuid})
                    end
                else
                    ZL.Print(nil, nil, nil, nil, nil, "注意：" .. itemLink .. "已存在，请勿重复创建！")
                end
                itemLoc:Clear()
            elseif button == "LeftButton" and IsShiftKeyDown() then
                ZL.ChatEditInsertLink(itemLink)
            end
        end)

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

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

        --如果当前插件有激活输入框，则发送链接到输入框
        hooksecurefunc("HandleModifiedItemClick", function (itemlink)
            -- local edit = GetCurrentKeyBoardFocus()
            -- if edit then
            --     edit:Insert(itemlink)
            -- end
            -- if ZL.focusEditBox then
            --     ZL.focusEditBox:Insert(itemlink)
            -- end
        end)
        --监控WA发送状态
        hooksecurefunc(C_ChatInfo, "SendAddonMessage", function(prefix, message, chatType, target)
            local loaded, total, waName = strsplit(" ", message)
            if not (prefix == "WeakAurasProg" and waName:find("%[AutoAuction%]金团拍卖助手")) then return end
            local dashIndex = target:find("-")
            if dashIndex then
                target = target:sub(1, dashIndex - 1)
            end
            if not ZL.WaLoadStateFrame then ZL:CreateWaLoadStateFrame() end
            if not ZL.WaLoadInfo then ZL.WaLoadInfo = {} end
            if not ZL.WaLoadInfo[target] then ZL.WaLoadInfo[target] = {} end
            if not ZL.WaLoadInfo[target].index then
                ZL.WaLoadInfo[target].loadCount = 0
                for num, f in ipairs(ZL.WaLoadStateFrame.entries) do
                    if (not f.sb.playerName:GetText()) or f.sb.playerName:GetText() == "" then
                        ZL.WaLoadInfo[target].index = num
                        break
                    end
                end
                if not ZL.WaLoadInfo[target].index then
                    ZL.WaLoadInfo[target].index = #ZL.WaLoadStateFrame.entries+1
                end
            end
            local f = ZL.WaLoadStateFrame.entries[ZL.WaLoadInfo[target].index]
            local loadState
            f.btn:SetEnabled(false)
            if loaded == total then
                loadState = math.floor(loaded*100/total) .. "%(传输完成)"
                ZL.WaLoadInfo[target].loadCount = ZL.WaLoadInfo[target].loadCount + 1
                SendChatMessage("您已传输完成，请选择【导入】或【更新光环-更新】后点【加载UI】生效！", "WHISPER", nil ,target)
                f.btn:SetEnabled(true)
            else
                loadState = math.floor(loaded*100/total) .. "%(传输中)"
            end
            local r, g, b = 1, 0.82, 0
            local classFilename = UnitClassBase(target)
            if classFilename then
                r, g, b = GetClassColor(classFilename)
            end
            f:SetValues(total, loaded, r, g, b, target, loadState)
        end)

        local __poplib = __ala_meta__.__poplib
        __poplib:AddMethod("QUERY_TALENT", {
            GetText = function() return "添加罚款"; end,
            IsShown = function() return true; end,
            OnClick = function(def, _, context)
                local msgStr
                if PlayerIsML() then
                    if not context.name then return end
                    local playIsInRaid
                    for i = 1, MAX_RAID_MEMBERS do
                        local _name = GetRaidRosterInfo(i)
                        if _name and _name == context.name then
                            playIsInRaid = true
                            break
                        end
                    end
                    if not playIsInRaid then
                        msgStr = "非团队成员无法添加罚款！"
                        ZL.Print(nil, nil, nil, nil, nil, msgStr)
                        return
                    end
                    local data = {
                        ["type"] = "罚款",
                        ["name"] = context.name,
                        ["title"] = "罚款",
                        ["amount"] = 500,
                    }
                    StaticPopup_Show("ZL_ADDINCOME", "收入", nil, data)
                else
                    msgStr = "你没有权限添加罚款！"
                    ZL.Print(nil, nil, nil, nil, nil, msgStr)
                end
            end,
            category = "AutoAuction",
        });
        __poplib:AddEntry("SELF", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_SELF", "QUERY_TALENT");
        __poplib:AddEntry("PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("FRIEND", "QUERY_TALENT");
        __poplib:AddEntry("FRIEND_OFFLINE", "QUERY_TALENT");
        __poplib:AddEntry("PARTY", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_PARTY", "QUERY_TALENT");
        __poplib:AddEntry("RAID", "QUERY_TALENT");
        __poplib:AddEntry("RAID_PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("_BRFF_RAID_PLAYER", "QUERY_TALENT");
        __poplib:AddEntry("CHAT_ROSTER", "QUERY_TALENT");
    elseif event == "PLAYER_LOGIN" then
        ZL.Print(true, nil, nil, nil, nil, "欢迎回来  >>>" .. GetClassColorName(UnitName("player")) .."<<<")
        if not ZL.RolesOverViewFrame then ZL:CreateRolesOverViewFrame() end
        if not ZL.LgnoreRolesFrame then ZL:CreateLgnoreRolesFrame() end
        if not ZL.ConcernFrame then ZL:CreateConcernFrame() end
        local tabId = ZL.opt.ZLAuctionFrameTabId
        _G["ZL_NewAuctionFrameTab0"]:Click()
        AuctionFrame:SetWidth(AuctionFrame:GetWidth()+0.5)
        C_Timer.After(0.5, function ()
            AuctionFrame:SetWidth(AuctionFrame:GetWidth()-0.5)
        end)
        _G["ZL_NewAuctionFrameTab" .. tabId]:Click()

        ZL.reloadUITime = GetServerTime()
        -- ZL.TradeRemainingReminderTime = GetServerTime() - ZL.opt.TradeRemainingReminderPinlv * 60 + 120
        if PlayerIsML() then
            ZL.mailRegOpen = true
            ZL.AuctionRecordFrame.playerBalanceFrame.mailConfirmBtn:SetText("|cff948cff邮寄登记中|r")
        end
        --检测V1.2.04之前版本物品过滤设置
        if ZL_CURRENT.filterItemId and #ZL_CURRENT.filterItemId > 0 then
            for _, data in ipairs(ZL_CURRENT.filterItemId) do
                if data["loot"] == nil then
                    data["loot"] = true
                end
                if data["auction"] == nil then
                    data["auction"] = true
                end
            end
        end
        --检测老板本数据库历史数据是否有缺少日期的，如果有缺少赋值为"1970-01-01 00:01"
        if ZL_HISTORY and #ZL_HISTORY > 0 then
            for i = #ZL_HISTORY, 1, -1 do
                if (not ZL_HISTORY[i]["auctiondate"]) then
                    ZL_HISTORY[i]["auctiondate"] = "1970-01-01 00:01"
                    -- table.remove(ZL_HISTORY, i)
                end
            end
            --删除历史数据
            local autoClearHistoryDiff = ZL.historyDaysList[ZL.opt.autoClearHistoryDays] * 86400 -- 天数*1天的秒数
            for i = #ZL_HISTORY, 1, -1 do
                if GetDiffTime(ZL_HISTORY[i]["auctiondate"]) >= autoClearHistoryDiff then
                    table.remove(ZL_HISTORY, i)
                end
            end
        end

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

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

        if ZL.opt.profanityFilter then SetCVar("profanityFilter", "0") end --关闭语言过滤器
        if ZL.opt.overrideArchive then SetCVar("overrideArchive", "0") end --反和谐

        if ZL_HISTORY and #ZL_HISTORY > 0 and ZL_Statistics and (not ZL_Statistics.firstCheck) then
            ZL_Statistics.firstCheck = true
            for _, data in ipairs(ZL_HISTORY) do
                InportToStatistics(data)
            end
        end
        --删除历史成交记录
        if ZL_Statistics and next(ZL_Statistics, nil) then
            local autoClearHistoryDiff = ZL.historyDaysList[ZL.opt.autoClearHistoryIncomeDays] * 86400 -- 天数*1天的秒数
            for key, data in pairs(ZL_Statistics) do
                if type(data) == "table" then
                    if GetDiffTime(data["auctiondate"]) >= autoClearHistoryDiff then
                        ZL_Statistics[key] = nil
                    end
                end
            end
        end

    elseif event == "GROUP_ROSTER_UPDATE" then
        C_Timer.After(1, function ()
            -- 函数：获取当前团队成员列表
            local function _GetCurrentRoster()
                local roster = {}
                for i = 1, MAX_RAID_MEMBERS do
                    local name = GetRaidRosterInfo(i)
                    if name then
                        table.insert(roster, name)
                    end
                end
                return roster
            end
            -- 函数：检测是否有新成员加入
            local function CheckForNewMembers()
                local currentRoster = _GetCurrentRoster()
                if next(previousRoster, nil) then
                    for _, name in ipairs(currentRoster) do
                        if (not previousRoster[name]) then
                            -- 新成员加入，发送密语
                            if (UnitIsGroupLeader("player") or PlayerIsML(UnitName("player"))) and (name ~= UnitName("player")) and ZL.opt.welcomeMessageEnable and
                                ZL.opt.MessageString and (#ZL.opt.MessageString > 0) then
                                -- SendChatMessage(ZL.opt.MessageString, "WHISPER", nil, name)
                                SendChatMessage(ZL.opt.MessageString, "RAID")
                            end
                        end
                    end
                end
                -- 更新之前的团队成员列表
                previousRoster = {}
                for _, name in ipairs(currentRoster) do
                    previousRoster[name] = true
                end
            end
            if IsInRaid() then
                if PlayerIsML() then
                    CheckForNewMembers()
                else
                    if ZL.opt.auctionMode ~= "团队" then
                        ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
                    end
                end
                ZL_CURRENT.MLname = ZL.GetMLname() or ZL_CURRENT.MLname
                --发送自己的版本号
                local data = {type="myVer", ver=ZL.addonVersion}
                MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "RAID")
            else
                previousRoster = {}
                if ZL.opt.auctionMode ~= "团队" then
                    ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
                end
            end
            AuctionFrame:Update()
            if (not ZL.opt.ZLAuctionFrameIsShown) and (PlayerIsML() or IsInRaid() or (not ZL.opt.maxFrameHide)) then
                ZL.maxFrame:Show()
            else
                ZL.maxFrame:Hide()
            end
            ZL.SaveDataRemind()
        end)
    elseif event == "PARTY_LOOT_METHOD_CHANGED" then
        --更换ML人员需要用到这个事件
        -- if IsInRaid() then
        --     ZL_CURRENT.MLname = ZL.GetMLname() or ZL_CURRENT.MLname
        -- end
        -- AuctionFrame:Update()
        -- ZL.SaveDataRemind()
    elseif event == "LOOT_OPENED" and IsInInstance() and (select(2, IsInInstance()) == "raid")
        then
        --如果是ML打开掉落则开始创建待拍卖窗口
        local NumLootItems = GetNumLootItems()
        if NumLootItems <= 0 then return end
        if (not ZL_CURRENT.sourceGUID) then ZL_CURRENT.sourceGUID = {} end
        local sourceGUID
        for i = 1, NumLootItems do
            sourceGUID = GetLootSourceInfo(i)
            if sourceGUID then break end
        end
        if (not sourceGUID) or ZL_CURRENT.sourceGUID[sourceGUID] then
            return
        end
        if not ZL_CURRENT.sourceGUID[sourceGUID] then ZL_CURRENT.sourceGUID[sourceGUID] = {} end
        ZL_CURRENT.sourceGUID[sourceGUID].time = date("%Y-%m-%d %H:%M:%S", time())

        local npcID = select(6, strsplit("-", sourceGUID))
        if npcID and ZL.BossInfo[npcID] then
            npcID = ZL.BossInfo[npcID]
        else
            npcID = "其他"
        end
        local msgStr = ""
        local minQuality = (ZL.opt.minQuality == -1 and GetLootThreshold() or ZL.opt.minQuality) --GetLootThreshold()获取当前团队的战利品分配阈值
        local lootMinQuality = (ZL.opt.lootMinQuality == -1 and GetLootThreshold() or ZL.opt.lootMinQuality)
        local lootList = {}
        local lootAuctionList = {}
        local candidates = {}
        local isGetCandidates = false
        --先创建完所有的记录
        for numLoot = 1, NumLootItems do
            if LootSlotIsItem(numLoot) then
                local itemlink = GetLootSlotLink(numLoot)
                local _, _, lootQuantity, _, lootQuality, _, isQuestItem = GetLootSlotInfo(numLoot)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                if (not isQuestItem) then
                    local _, auctionFilter, lootFilter = isFilterItem(itemId)
                    --蓝装以上拾取通报
                    if lootQuality > 2 then
                        lootList[itemlink] = (lootList[itemlink] or 0) + lootQuantity
                    end
                    if PlayerIsML() then
                        --拍卖
                        if lootQuality >= minQuality and (not auctionFilter) then
                            --获取候选人
                            if (not isGetCandidates) then
                                candidates = GetMasterLootCandidates(numLoot) --获取候选人信息
                                isGetCandidates = true
                            end
                            --以下新增测试用
                            --增加自定义itemGUID规则：itemId+time()+01
                            if not lootAuctionList[itemlink] then
                                lootAuctionList[itemlink] = {spawnUID={}, lootQuantity=0, increment=1}
                            end
                            local stackCount, _, _, _, _, _, bindType = select(8, cGetItemInfo(itemlink))
                            if stackCount == 1 then
                                local spawnUIDkey = itemId ..time() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                if itemId == 47242 then --北伐奖章直接放到其他分类
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                else
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName=npcID, itemGUID={}}
                                end
                                lootAuctionList[itemlink].increment = lootAuctionList[itemlink].increment + 1
                                if bindType == 1 then
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey].candidates = candidates
                                end
                            else
                                if lootAuctionList[itemlink].increment == 1 then
                                    local spawnUIDkey = itemId ..time() .. string.format("%02d", lootAuctionList[itemlink].increment)
                                    lootAuctionList[itemlink].spawnUID[spawnUIDkey] = {bossName="其他", itemGUID={}}
                                end
                            end
                            lootAuctionList[itemlink].lootQuantity = lootAuctionList[itemlink].lootQuantity + lootQuantity
                        end
                        --自动拾取
                        local _, _, _, _, _, _, _, itemStackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                        if lootQuality >= lootMinQuality and ZL.opt.awardToML and (not lootFilter) and (not (itemStackCount > 1 and bindType == 1)) 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 ZL.opt.confirmLootAnnounce and next(lootList, nil) then  --拾取通报
            SendChatMessage("[AutoAuction]拾取通报：", "RAID")
            C_Timer.After(0.3, function ()
                for link, num in pairs(lootList) do
                    if num > 1 then
                        SendChatMessage(link .. "x" .. num, "RAID")
                    else
                        SendChatMessage(link, "RAID")
                    end
                end
            end)
        end
        if PlayerIsML() then
            ZL_CURRENT.sourceGUID[sourceGUID].candidates = candidates
            -- ZL_CURRENT.sourceGUID[sourceGUID].lootAuctionList = lootAuctionList
            --开始创建拍卖物品
            if next(lootAuctionList, nil) then
                local keyList = {}
                for key, _ in pairs(lootAuctionList) do
                    table.insert(keyList, key)
                end
                local sendData = {type="拾取创建", data={}}
                for _, itemlink in ipairs(keyList) do
                    --bindType 1为拾取绑定
                    local _, _, _, itemLevel, _, _, itemSubType, stackCount, _, _, _, _, _, bindType = cGetItemInfo(itemlink)
                    local lootQuantity = lootAuctionList[itemlink].lootQuantity
                    local spawnUID = lootAuctionList[itemlink].spawnUID
                    local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                    local indexList = {}
                    local itemindex = nil
                    if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                        for num, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.itemlink == itemlink) then
                                itemindex = data.itemindex
                                if (data.state ~= "success") then
                                    table.insert(indexList, num) --可能因交易名单不同存在多个拍卖记录
                                end
                            end
                        end
                    end
                    if (not itemindex )then
                        itemindex = 1
                    else
                        itemindex = itemindex + 1
                    end
                    local data = {}
                    local index
                    if #indexList > 0 then
                        for _, _index in ipairs(indexList) do
                            local fdata = ZL_CURRENT.auctionlist[_index]
                            if fdata.bindType ~= 1 then --不是拾取绑定的物品，不是拍卖成功的都可以创建到一个拍卖记录上面
                                index = _index
                                break
                            else --拾取绑定的物品
                                --如果是通过自动创建的，有sourceGUID的则判断与第一个sourceGUID交易名单差异
                                if fdata.type == "自动创建" and fdata.sourceGUID and #fdata.sourceGUID > 0 then
                                    local _sourceGUID = fdata.sourceGUID[1]
                                    local _candidates = ZL_CURRENT.sourceGUID[_sourceGUID].candidates
                                    --判断当前的交易名单跟前面的名单对比，有几个不在前面的名单内
                                    local curChaYi = 0
                                    for name, _ in pairs(candidates) do
                                        --不在前面交易名单内
                                        if (not _candidates[name]) then
                                            curChaYi = curChaYi + 1
                                        end
                                    end
                                    --判断前面的交易名单跟现在的对比，有几个不在当前名单内并且还在团队内
                                    local hisChaYi = 0
                                    for name, _ in pairs(_candidates) do
                                        if (not candidates[name]) and UnitInRaid(ParseClassColorName(name)) then
                                            hisChaYi = hisChaYi + 1
                                        end
                                    end
                                    --如果当前的差异不大于拾取数量并且历史差异不大于历史物品数量，则合并拍卖
                                    if curChaYi <= lootQuantity and hisChaYi <= fdata.itemCount then
                                        index = _index
                                        break
                                    end
                                end
                            end
                        end
                    end
                    if index then
                        local fdata = ZL_CURRENT.auctionlist[index]
                        -- table.insert(ZL_CURRENT.auctionlist[index]["candidates"], candidates)  --暂时不能删除
                        table.insert(ZL_CURRENT.auctionlist[index]["sourceGUID"], sourceGUID)
                        ZL_CURRENT.auctionlist[index].itemCount = fdata.itemCount + lootQuantity
                        --新增测试内容↓↓↓↓↓↓
                        --堆叠数量为1，需要添加进去，大于1不需要
                        if fdata.stackCount == 1 then
                            for key, value in pairs(spawnUID) do
                                ZL_CURRENT.auctionlist[index]["spawnUID"][key] = value
                            end
                        end
                        --新增测试内容↑↑↑↑↑↑

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

                                    if #itemList > 0 then
                                        local __index = 1
                                        local function linshi()
                                            if __index <= #itemList then
                                                C_Container.PickupContainerItem(itemList[__index]["bagID"], itemList[__index]["slotIndex"])
                                                C_Container.PickupContainerItem(itemList[__index]["targetBagID"], itemList[__index]["targetslotIndex"])
                                                __index = __index + 1
                                                C_Timer.After(1, linshi)
                                            end
                                        end
                                        linshi()
                                    else
                                        msgStr = "|cffff0000注意：流拍物品重拍，但没有合适的物品从流拍背包中取出！|r"
                                        ZL.Print(nil, nil, nil, nil, nil, msgStr)
                                    end
                                end
                                ZL_CURRENT.auctionlist[index].tradeId = nil
                                ZL_CURRENT.auctionlist[index].startbidamount = startbidamount
                                ZL_CURRENT.auctionlist[index].bidIncrement = _bidIncrement
                                ZL_CURRENT.auctionlist[index].countdownremaining = ZL.opt.auctionTimer
                                ZL_CURRENT.auctionlist[index].auctionTimerRefresh = (ZL_CURRENT.globalConfig and ZL_CURRENT.globalConfig["auctionTimerRefresh"]) and ZL_CURRENT.globalConfig["auctionTimerRefresh"] or ZL.opt.auctionTimerRefresh
                                ZL_CURRENT.auctionlist[index].state = "auctioning"
                                ZL_CURRENT.auctionlist[index].isPaused = false
                                ZL_CURRENT.auctionlist[index].bidderlist = {}
                                table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                    bidder = GetClassColorName(sender),
                                    bidamount = newBid,
                                    bidCount = bidCount > curAuctionList.itemCount and curAuctionList.itemCount or bidCount,
                                    time = GetTime()*1000,
                                })
                                local data = {
                                    type = "开始拍卖",
                                    isRestart = "开始",
                                    data2 = ZL_CURRENT.auctionlist[index],
                                }
                                MyAddon:TransmitAddonInfo("AUTOAUC SYNC1", data)
                            end
                        end
                        if ZL_CURRENT.auctionlist[index].countdownremaining > 0 then
                            ZL_CURRENT.auctionlist[index].countdownremaining = (ZL_CURRENT.globalConfig and ZL_CURRENT.globalConfig["auctionTimerRefresh"]) and ZL_CURRENT.globalConfig["auctionTimerRefresh"] or ZL.opt.auctionTimerRefresh--有新的出价，重新更新倒计时
                            Frame1:SetValues(index)
                            if ZL.opt.IsVoiceReminder and (((not ZL_CURRENT.globalConfig) or (not ZL_CURRENT.globalConfig.YYSound)) or PlayerIsML()) and ((not ZL.jiayou) or ((ZL.jiayou + 30 -GetTime()) < 0))
                            and ((newBid-tarbidamount+bidIncrement) >= 2000 or (newBid >= 10000 )) then
                                PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\老公加油.mp3", "Master")
                                ZL.jiayou = GetTime()
                                if not ZL.playerModel then
                                    ZL.playerModel = CreateFrame("PlayerModel", nil, UIParent)
                                    local playerModel = ZL.playerModel
                                    playerModel:SetPoint("CENTER")
                                    playerModel:SetSize(200, 200)
                                    -- playerModel:SetUnit("player")
                                    playerModel:SetCreature(25305)
                                    playerModel:SetFacing(-0.4)
                                    playerModel:SetAnimation(69)
                                    playerModel:SetAlpha(1)
                                end
                                ZL.playerModel:Show()
                                C_Timer.After(5, function ()
                                    ZL.playerModel:Hide()
                                end)
                            end
                            local isSenderExist = false
                            for bindex, b in ipairs(bidderlist) do
                                if ParseClassColorName(b.bidder) == sender then
                                    ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidamount = newBid
                                    ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidCount = bidCount
                                    ZL_CURRENT.auctionlist[index].bidderlist[bindex].time = GetTime()*1000
                                    isSenderExist = true
                                    break
                                end
                            end
                            if (not isSenderExist) then --如不存在，则直接插入
                                table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {
                                    bidder = GetClassColorName(sender),
                                    bidamount = newBid,
                                    bidCount = bidCount,
                                    time = GetTime()*1000,
                                })
                            end
                            tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                            local totalBidCount = 0
                            for bidindex, bidData in ipairs(bidderlist) do
                                if totalBidCount < fdata.itemCount then
                                    local count = bidData["bidCount"] or 1
                                    local newTotalBidCount = totalBidCount + count
                                    if newTotalBidCount > fdata.itemCount then
                                        count = fdata.itemCount - totalBidCount
                                        ZL_CURRENT.auctionlist[index].bidderlist[bidindex].bidCount = count
                                        if ParseClassColorName(bidData.bidder) == sender and PlayerIsML() then
                                            SendChatMessage("已自动将您当前出价入围数量调整为：" .. count, "WHISPER", nil ,sender)
                                        end
                                    end
                                    totalBidCount = newTotalBidCount
                                else
                                    break
                                end
                            end
                            Frame1:SetValues(index)
                            --更新出价
                            local itemCount = fdata.itemCount
                            local bidCount = Frame1.bidFrame.bidCounts:GetNumber()
                            bidCount = bidCount > 0 and bidCount or 1
                            bidCount = bidCount > itemCount and itemCount or bidCount
                            local _, bidIncrement, tarbidamount, _bidCount, successList = ZL.GetNewBidAmount(index)
                            if bidCount > _bidCount and #successList > 0 then
                                for i = #successList, 1, -1 do
                                    if successList[i][2] >= bidCount then
                                        tarbidamount = successList[i][1] + bidIncrement
                                        break
                                    end
                                end
                            end
                            Frame1.bidFrame.bidEditBox:SetNumber(tarbidamount)
                            if ZL.FloatAuctionFrame:IsShown() then
                                ZL.FloatAuctionFrame.bidFrame.bidEditBox:SetNumber(tarbidamount)
                            end
                            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
                    else
                        if PlayerIsML() and ZL_CURRENT.globalConfig.auctionMode == "团队" then
                            msgStr = ("%s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(fdata.itemlink, tarbidamount)
                            SendChatMessage(msgStr, "WHISPER", nil, sender)
                            msgStr = ("%s %s出价过低，请至少出价(%d)或打完整的出价，以便插件识别"):format(sender, fdata.itemlink, tarbidamount)
                            SendChatMessage(msgStr, "RAID")
                            return
                        end
                    end
                else
                    if PlayerIsML() and ZL_CURRENT.globalConfig.auctionMode == "团队" then -- and ZL.opt.remindInvalidBid
                        msgStr = ">>>" .. sender .."<<<出价无效，请按加价幅度(" .. bidIncrement .. ")的整数倍出价"
                        SendChatMessage(msgStr, "RAID")
                        msgStr = "如需竞拍，请按加价幅度(" .. bidIncrement .. ")的整数倍出价，如不需要竞拍忽略这条信息"
                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                        return
                    end
                end
            end
        end
    elseif (event == "CHAT_MSG_WHISPER") and PlayerIsML() then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        local __name = GetClassColorName(sender)
        if msg == "邮寄" then
            if PlayerIsML(sender) then return end
            if ZL_CURRENT.tradeGongZi and ZL_CURRENT.tradeGongZi[__name] then
                SendChatMessage("你的工资已交易过，无法登记邮寄！", "WHISPER", nil, sender)
                return
            end
            if (not ZL.mailRegOpen) then
                SendChatMessage("登记邮寄工资窗口已关闭，暂时不接受登记！", "WHISPER", nil, sender)
                return
            end
            if (not ZL_CURRENT["mailPlayers"]) then ZL_CURRENT["mailPlayers"] = {} end
            if (ZL_CURRENT["mailPlayers"][__name] == nil) then
                ZL_CURRENT["mailPlayers"][__name] = false
            end
            SendChatMessage("插件已登记邮寄工资，不可撤销！", "WHISPER", nil, sender)
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            local senderIndex = nil
            local subgroup = nil
            for i = 1, MAX_RAID_MEMBERS do
                local name, _, _subgroup = GetRaidRosterInfo(i)
                if name == sender then
                    senderIndex = i
                    subgroup = _subgroup
                    break
                end
            end
            if senderIndex and (not InCombatLockdown()) and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then
                local mailPlayerList = {__name}
                ZL.ChangePlayerGroup(mailPlayerList)
            end
        elseif msg == "撤销" then
            local num, index = GetAuctioningCount()
            if num == 1 then
                local itemId = ZL_CURRENT.auctionlist[index].itemId
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemId=itemId, itemindex=itemindex, playerName=__name})
            else
                if PlayerIsML() then
                    SendChatMessage("当前存在多个拍卖物品，无法撤销出价！", "WHISPER", nil, sender)
                end
            end
        end
    elseif (event == "TRADE_CLOSED") then
		ZL.isTrading = nil
        if not ZL.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Hide()
            ZL.opt.ZLAuctionRecordFrameIsShown = false
        end
        
	elseif (event == "TRADE_SHOW") then
		ZL.ZLAuctionRecordFrameIsShown = ZL.AuctionRecordFrame:IsShown() --如果一开始是打开状态，关闭交易的时候该窗口不关闭
        -- if ZL.tradeGongZi then return end
        
        ZL.isTrading = true
		ZL.tradeMoneyML = 0
		ZL.tradeMoneyOther = 0
        ZL.MLTradeItems = {}
        local function PickupContainerItemToTrade(itemGUID, ibag, islot)
            C_Container.PickupContainerItem(ibag, islot)
            for i = 1, 6 do
                local name = GetTradePlayerItemInfo(i)
                if (not name) then
                    ClickTradeButton(i)
                    break
                end
            end
        end
        if PlayerIsML() then
            ZL.tradePartner = GetClassColorName((GetUnitName("npc", true)))
            local playerBuyList = ZL.GetPlayerBuyList()
            local tradeList = {}
            local splitList = {}
            if playerBuyList[ZL.tradePartner] then
                local balanceAmount = 0
                local playerPayToMLamount = 0
                if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                    playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                end
                balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                if balanceAmount < 0 and ((not ZL_CURRENT.tradeGongZi) or (not ZL_CURRENT.tradeGongZi[ZL.tradePartner])) and ((not ZL_CURRENT["mailPlayers"]) or (not ZL_CURRENT["mailPlayers"][ZL.tradePartner] == true)) then
                    SendChatMessage("总共请支付：".. -balanceAmount .. "g", "WHISPER", nil, ParseClassColorName(ZL.tradePartner))
                end
                if playerBuyList[ZL.tradePartner]["items"] and #playerBuyList[ZL.tradePartner]["items"] > 0 then
                    ClearCursor()
                    for _, data in ipairs(playerBuyList[ZL.tradePartner]["items"]) do
                        -- local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                        if (not data.isTraded) and data.itemGUID and #data.itemGUID > 0 then
                            local tradeCount = 0
                            for _, itemGUID in ipairs(data.itemGUID) do
                                if not tradeList[itemGUID] then
                                    local bag, slot = ZL.FindItemInBag(itemGUID)
                                    if bag then
                                        local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                                        local isLocked = GetContainerItemInfo["isLocked"]
                                        local isBound = GetContainerItemInfo["isBound"]
                                        local stackCount = GetContainerItemInfo["stackCount"]
                                        if not isLocked then
                                            local isCanTrade
                                            if isBound then
                                                --如果已绑定，检测是否还有剩余交易时间
                                                if (not ZL.ToolTip) then
                                                    ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                                                end
                                                ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                                                ZL.ToolTip:ClearLines()
                                                ZL.ToolTip:SetBagItem(bag, slot)
                                                for i = 1, ZL.ToolTip:NumLines() do
                                                    local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                                                    if text then
                                                        local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                                        if timeRemaining then
                                                            isCanTrade = true
                                                            break
                                                        end
                                                    end
                                                end
                                            else
                                                isCanTrade = true
                                            end
                                            if isCanTrade and tradeCount < data.itemCount then
                                                local splitCount = stackCount - (data.itemCount - tradeCount)
                                                tradeCount = tradeCount + stackCount
                                                tradeList[itemGUID] = {bag=bag, slot=slot}
                                                if splitCount > 0 then
                                                    splitList[itemGUID] = {
                                                        splitCount = splitCount,
                                                        bag = bag,
                                                        slot = slot,
                                                    }
                                                end
                                                if tradeCount >= data.itemCount then
                                                    break
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
                local function trade()
                    if next(tradeList, nil) then
                        local tempList = {}
                        for itemGUID, _ in pairs(tradeList) do
                            table.insert(tempList, itemGUID)
                        end
                        local index = 1
                        local function linshi()
                            if index <= #tempList then
                                local itemGUID = tempList[index]
                                PickupContainerItemToTrade(itemGUID, tradeList[itemGUID].bag, tradeList[itemGUID].slot)
                                index = index + 1
                                C_Timer.After(0.3, linshi)
                            end
                        end
                        linshi()
                    end
                end
                if next(splitList, nil) then
                    local tempList = {}
                    for itemGUID, data in pairs(splitList) do
                        table.insert(tempList, itemGUID)
                    end
                    local index = 1
                    local function split_linshi()
                        if index <= #tempList then
                            local itemGUID = tempList[index]
                            local isfull = true
                            for tarBagID = 0, NUM_BAG_SLOTS do
                                for tarSlotIndex = 1, C_Container.GetContainerNumSlots(tarBagID) do
                                    local currentInfo = C_Container.GetContainerItemInfo(tarBagID, tarSlotIndex)
                                    if not currentInfo then
                                        C_Container.SplitContainerItem(splitList[itemGUID].bag, splitList[itemGUID].slot, splitList[itemGUID].splitCount)
                                        C_Container.PickupContainerItem(tarBagID, tarSlotIndex)
                                        isfull = false
                                        break
                                    end
                                end
                            end
                            if isfull then
                                local msgStr = "注意！注意！背包已满，无法分成目标小堆数量！已移除交易清单"
                                ZL.Print(nil, nil, nil, nil, nil, msgStr)
                                tradeList[itemGUID] = nil
                            end
                            if index == #tempList then
                                C_Timer.After(1, trade)
                            end
                            index = index + 1
                            C_Timer.After(1, split_linshi)
                        end
                    end
                    split_linshi()
                else
                    trade()
                end
            end
        elseif PlayerIsML(GetUnitName("npc", false)) then
            ZL.tradePartner = GetClassColorName((GetUnitName("player", true)))
        else
            ZL.tradePartner = nil
        end
        if PlayerIsML() then
            if ZL.opt.ShowAuctionRecordFrameCheckButtonValue then
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["TradeFrame"], "TOPRIGHT")
            end
        end
	elseif (event == "TRADE_ACCEPT_UPDATE") and ZL.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	elseif (event == "TRADE_PLAYER_ITEM_CHANGED") then -- and ZL.tradePartner
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	elseif (event == "TRADE_MONEY_CHANGED") and ZL.tradePartner then
        Trade_UpdateMoney()
	elseif (event == "UI_INFO_MESSAGE") then
        if arg[2] == ERR_TRADE_COMPLETE  then
            if ZL.tradePartner and ZL_CURRENT["IncomeList"] and PlayerIsML() then
                for _, itemlink in ipairs(ZL.MLTradeItems) do
                    for index, data in ipairs(ZL_CURRENT["IncomeList"]) do
                        local isTrue
                        if data.itemList and next(data.itemList, nil) then
                            for _itemlink, _data in pairs(data.itemList) do
                                if (not _data.isTraded) and itemlink == _itemlink and data.player == ZL.tradePartner then
                                    ZL_CURRENT["IncomeList"][index]["itemList"][itemlink]["isTraded"] = true
                                    isTrue = true
                                    break
                                end
                            end
                        end
                        if isTrue then break end
                    end
                end
                --下面为新增数据库
                if ZL.tradeMoneyOther > 0 then
                    --判断是否有欠款
                    local playerBuyList = ZL.GetPlayerBuyList()
                    local balanceAmount = 0
                    local playerPayToMLamount = 0
                    if ZL_CURRENT.playerPayToML and ZL_CURRENT.playerPayToML[ZL.tradePartner] then
                        playerPayToMLamount = ZL_CURRENT.playerPayToML[ZL.tradePartner]
                    end
                    if playerBuyList[ZL.tradePartner] and playerBuyList[ZL.tradePartner].totalAmount then
                        balanceAmount = playerPayToMLamount - playerBuyList[ZL.tradePartner].totalAmount
                    else
                        balanceAmount = playerPayToMLamount
                    end
                    if PlayerIsML(ZL.tradePartner) then
                        balanceAmount = 0
                    end
                    if balanceAmount < 0 then -- 有欠款则直接记录
                        if not ZL_CURRENT.playerPayToML then ZL_CURRENT.playerPayToML = {} end
                        ZL_CURRENT.playerPayToML[ZL.tradePartner] = (ZL_CURRENT.playerPayToML[ZL.tradePartner] or 0) + ZL.tradeMoneyOther
                        ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                    else --没有欠款，则弹出提示框选择是代交还是自己交或者只是普通的交易不记录
                        local data = {tradeMoneyOther = ZL.tradeMoneyOther, tradePartner = ZL.tradePartner}
                        StaticPopup_Show("ZL_CONFIRMTRADERNAME", ZL.tradePartner, nil, data, ZL.GroupMembersDropdown)
                    end
                end
                ZL.tradePartner = nil
            end
            if ZL.tradeGongZi and PlayerIsML() then
                if not ZL_CURRENT.tradeGongZi then ZL_CURRENT.tradeGongZi = {} end
                ZL_CURRENT.tradeGongZi[ZL.tradeName] = ZL.tradeGongZi
                --剔除邮寄名单
                if ZL_CURRENT["mailPlayers"] then
                    ZL_CURRENT["mailPlayers"][ZL.tradeName] = nil
                end
                ZL.tradeName = nil
                ZL.tradeGongZi = nil
                ZL.tradeGroupMsg = nil
            elseif ZL.tradeGroupGongZi and PlayerIsML() then
                if not ZL_CURRENT.tradeGroupGongZi then ZL_CURRENT.tradeGroupGongZi = {} end
                ZL_CURRENT.tradeGroupGongZi[tostring(ZL.tradeGroup)] = ZL.tradeGroupGongZi
                if not ZL_CURRENT.tradeGongZi then ZL_CURRENT.tradeGongZi = {} end
                for name, gongzi in pairs(ZL.tradeGroupGongZi) do
                    ZL_CURRENT.tradeGongZi[name] = gongzi
                    --剔除邮寄名单
                    if ZL_CURRENT["mailPlayers"] then
                        ZL_CURRENT["mailPlayers"][name] = nil
                    end
                end
                SendChatMessage(ZL.tradeGroupMsg[1], "RAID")
                C_Timer.After(0.2, function ()
                    for i = 2, #ZL.tradeGroupMsg do
                        SendChatMessage(ZL.tradeGroupMsg[i], "RAID")
                    end
                    ZL.tradeGroupMsg = nil
                end)
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
            elseif ZL.otherTradeGongZi and (not PlayerIsML()) then
                if not ZL_PLAYERLIST.otherTradeGongZi then ZL_PLAYERLIST.otherTradeGongZi = {} end
                ZL_PLAYERLIST.otherTradeGongZi[ZL.tradeName] = ZL.otherTradeGongZi
                ZL.tradeName = nil
                ZL.otherTradeGongZi = nil
                ZL.tradeGroupMsg = nil
            end
        elseif arg[2] == ERR_MAIL_SENT and ZL.Recipient and PlayerIsML() then --"邮件已发出。"
            ZL.ScrollingMessageFrame:AddMessage("【" .. ZL.Recipient .. "】邮件发送成功！", 1.0, 1.0, 1.0)
            ZL_CURRENT["mailPlayers"][ZL.Recipient] = true
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            ZL.Recipient = nil
        else
            if isTradeFailed(arg[2]) then
                ZL.tradeGongZi = nil
                ZL.tradeName = nil
                ZL.tradeGroupGongZi = nil
                ZL.tradeGroup = nil
                ZL.otherTradeGongZi = nil
            end
		end
	elseif (event == "UI_ERROR_MESSAGE") and PlayerIsML() then
        --"找不到收件人。" "收件人现在无法收到邮件。" "内部邮件数据库错误" 
        if arg[2] == ERR_MAIL_TARGET_NOT_FOUND or arg[2] == ERR_MAIL_RECEPIENT_CANT_RECEIVE_MAIL or arg[2] == ERR_MAIL_DATABASE_ERROR then
            ZL.Recipient = nil
        elseif arg[2] == ERR_MAIL_REACHED_CAP then --"你已经达到了收取邮件的数量上限"
            ZL.Recipient = nil
            ZL.ScrollingMessageFrame:AddMessage("你已经达到了发送邮件数量上限，已停止邮寄，请过一段时间后重试！", 1, 0, 0)
            ZL.StopSendMail = true
        end
    elseif (event == "MAIL_CLOSED") and PlayerIsML() then
        ZL.Recipient = nil
    elseif (event == "MAIL_SHOW") and PlayerIsML() and ZL.GetNeedMailNums() > 0  then
        ZL.Recipient = nil
        local function linshi()
            if (not _G["MailFrame"]) or (not _G["MailFrame"]:IsShown()) then
                C_Timer.After(0.3, linshi)
            else
                if (not ZL.AuctionRecordFrame:IsShown()) then
                    ZL.AuctionRecordFrame:Show()
                else
                    ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                end
                _G["ZLAuctionRecordFrameTab3"]:Click()
                ZL.AuctionRecordFrame:ClearAllPoints()
                ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["MailFrame"], "TOPRIGHT")
            end
        end
        linshi()
    elseif (event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE") and (arg[1] == Enum.PlayerInteractionType.MailInfo) and PlayerIsML() then
        ZL.AuctionRecordFrame:Hide()
        ZL.opt.ZLAuctionRecordFrameIsShown = false
    elseif (event == "PLAYER_ENTERING_WORLD") then
        C_FriendList.ShowFriends()
        --切换地图的时候才触发
        if (not arg[1]) and (not arg[2]) then
            RequestRaidInfo()
            C_Timer.After(1, function ()
                if not next(ZL_CURRENT) then return end
                local inInstance, instanceType = IsInInstance()
                if inInstance and instanceType == "raid" then
                    local instanceName, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
                    local newCD = true
                    for i = 1, GetNumSavedInstances() do
                        local _, _, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
                        if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                            newCD = false
                            break
                        end
                    end
                    if newCD then --and ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) and (ZL_CURRENT.instanceID ~= instanceID) and (ZL_CURRENT.difficultyID ~= difficultyID) 
                        local msgStr = "已进入一个全新副本【|cffffd100" .. instanceName .. "|r】，请确认是否重置当前拍卖数据？"
                        StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
                    else
                        local todayDate = date("%Y-%m-%d", time())
                        if ZL_CURRENT.auctiondate and (((ZL_CURRENT.auctiondate):match("^(.-)%s")) ~= todayDate) then
                            local msgStr = "已进入【|cffffd100" .. instanceName .. "|r】副本，当前副本已存在|cffffd100" .. ZL_CURRENT.auctiondate .. "|r拍卖记录，请确认是否重置这个拍卖数据？"
                            StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
                        end
                    end
                end
            end)
        end
        C_Timer.After(3, function ()
            --获取交易剩余时间定时器
            if not ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(2, function ()
                    ZL.GetRemainingTradeTime()
                end)
            end

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

            local function saveGroupMembersTip ()
                if ZL.opt.saveGroupMembersSound and IsInInstance() and (select(2, IsInInstance()) == "raid") and PlayerIsML()
                and (not ZL_CURRENT["GroupMembersList"] or #ZL_CURRENT["GroupMembersList"] == 0) then
                    local msg = "还未保存团队名单，注意及时保存哦！"
                    ZL.ScrollingMessageFrame:AddMessage(msg)
                    PlaySoundFile("Interface\\AddOns\\" .. addonName .. "\\sound\\" .. ZL.SoundType .. "\\保存团队名单.mp3", "Master")
                end
            end
            -- 保存团队名单提醒
            if not ZL.saveGroupMembers then
                ZL.saveGroupMembers = C_Timer.NewTicker(300, function ()
                    saveGroupMembersTip ()
                end)
            end

        end)
        --请求同步数据
        if arg[1] or arg[2] then
            local delay = arg[1] and 6 or 3
            C_Timer.After(delay, function ()
                if IsInRaid() then
                    --获取团队版本号
                    local data = {type="request", ver=ZL.addonVersion}
                    MyAddon:TransmitAddonInfo2("AUTOAUC VER", data, "RAID")
                    if ZL.opt.auctionMode ~= "团队" and (not PlayerIsML()) then
                        ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
                    end
                    --同步ML拍卖数据
                    if (not PlayerIsML()) and (UnitName("player") ~= ZL_CURRENT.MLname) then
                        local msgStr = "已发送同步拍卖数据请求，等待回应..."
                        ZL.Print(nil, nil, nil, nil, nil, msgStr)
                        MyAddon:TransmitAddonInfo2("AUTOAUC REQ", "同步拍卖数据", "WHISPER", GetMLname())
                    end
                    TransmitAddonInfo_Pro()
                else
                    if ZL.opt.auctionMode ~= "团队" then
                        ZL.AuctionFrame2.auctionModeDropdown:SetValue(1)
                    end
                end

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

                local function ProcessingStatisticsData()
                    while ZL.ReceivedStatisticsData and #ZL.ReceivedStatisticsData > 0 do
                        local data = ZL.ReceivedStatisticsData[1]
                        if data and next(data, nil) then
                            for key, value in pairs(data) do
                                if (not ZL_Statistics[key]) and type(value) == "table" then
                                    ZL_Statistics[key] = value
                                end
                            end
                        end
                        tremove(ZL.ReceivedStatisticsData, 1)
                    end
                    -- 如果还有数据，继续处理，否则等待一段时间再检查
                    if ZL.ReceivedStatisticsData and #ZL.ReceivedStatisticsData > 0 then
                        ProcessingStatisticsData()
                    else
                        C_Timer.After(60, ProcessingStatisticsData)
                    end
                end
                ProcessingStatisticsData()
            end)
        end
    elseif (event == "UPDATE_INSTANCE_INFO") then
        ZL.GetSavedInstanceInfo()
        ZL.SyncRolesTimerStart()
    elseif (event == "BAG_UPDATE_DELAYED") then
        if ZL.opt.waitingBagHighLight or ZL.opt.auctioningBagHighLight or ZL.opt.successBagHighLight
        or ZL.opt.failedBagHighLight or ZL.opt.lgnoreBagHighLight then
            ZL.BagHighLight()
        end
    elseif (event == "BAG_OPEN") then
        ZL.BagHighLight()
    elseif (event == "PLAYER_REGEN_ENABLED") then
        if ZL.opt.ZLAuctionFrameIsShown then
            ZL.AuctionFrame2:Show()
        end
        if ZL.opt.remainingTradeTimeBtnValue then
            ZL.ZLRemainingTradeTimeFrame:Show()
        end
        if ZL.opt.ItemSettingFrameIsShown then
            ZL.ItemSettingFrame:Show()
        end
        if ZL.opt.ZLAuctionRecordFrameIsShown then
            ZL.AuctionRecordFrame:Show()
        end
        if ZL.opt.SettingFrameIsShown then
            ZL.OpenAceConfigDialog("金团拍卖助手")
        end
        if ZL.opt.ZLRolesOverViewFrameIsShown then
            ZL.RolesOverViewFrame:Show()
        end
    elseif (event == "PLAYER_REGEN_DISABLED") then
        --进入战斗，隐藏窗口
        if ZL.opt.AuctionFrameHide then
            ZL.AuctionFrame2:Hide()
        end
        if ZL.opt.RemainingTradeTimeFrameHide then
            ZL.ZLRemainingTradeTimeFrame:Hide()
        end
        if ZL.opt.ItemSettingFrameHide then
            ZL.ItemSettingFrame:Hide()
        end
        if ZL.opt.AuctionRecordFrameHide then
            ZL.AuctionRecordFrame:Hide()
        end
        if ZL.opt.SettingFrameHide then
            if LibStub("AceConfigDialog-3.0").OpenFrames["金团拍卖助手"] then
                ZL.opt.SettingFrameIsShown = true
                LibStub("AceConfigDialog-3.0"):Close("金团拍卖助手")
            else
                ZL.opt.SettingFrameIsShown = false
            end
        end
        if ZL.opt.RolesOverViewFrameHide then
            ZL.RolesOverViewFrame:Hide()
        end
    elseif (event == "CHAT_MSG_ADDON") then
        if arg[1] == "WeakAuras" then
            local Compresser = LibStub:GetLibrary("LibCompress")
            local LibDeflate = LibStub:GetLibrary("LibDeflate")
            local Serializer = LibStub:GetLibrary("AceSerializer-3.0")
            local LibSerialize = LibStub("LibSerialize")
            local decodeB64Table = {}
            local string_char = string.char
            local bit_band, bit_lshift, bit_rshift = bit.band, bit.lshift, bit.rshift
            local B64tobyte = {
                a =  0,  b =  1,  c =  2,  d =  3,  e =  4,  f =  5,  g =  6,  h =  7,
                i =  8,  j =  9,  k = 10,  l = 11,  m = 12,  n = 13,  o = 14,  p = 15,
                q = 16,  r = 17,  s = 18,  t = 19,  u = 20,  v = 21,  w = 22,  x = 23,
                y = 24,  z = 25,  A = 26,  B = 27,  C = 28,  D = 29,  E = 30,  F = 31,
                G = 32,  H = 33,  I = 34,  J = 35,  K = 36,  L = 37,  M = 38,  N = 39,
                O = 40,  P = 41,  Q = 42,  R = 43,  S = 44,  T = 45,  U = 46,  V = 47,
                W = 48,  X = 49,  Y = 50,  Z = 51,["0"]=52,["1"]=53,["2"]=54,["3"]=55,
                ["4"]=56,["5"]=57,["6"]=58,["7"]=59,["8"]=60,["9"]=61,["("]=62,[")"]=63
            }
            local bytetoB64 = {
                [0]="a","b","c","d","e","f","g","h",
                "i","j","k","l","m","n","o","p",
                "q","r","s","t","u","v","w","x",
                "y","z","A","B","C","D","E","F",
                "G","H","I","J","K","L","M","N",
                "O","P","Q","R","S","T","U","V",
                "W","X","Y","Z","0","1","2","3",
                "4","5","6","7","8","9","(",")"
            }
            local function decodeB64(str)
                local bit8 = decodeB64Table;
                local decoded_size = 0;
                local ch;
                local i = 1;
                local bitfield_len = 0;
                local bitfield = 0;
                local l = #str;
                while true do
                  if bitfield_len >= 8 then
                    decoded_size = decoded_size + 1;
                    bit8[decoded_size] = string_char(bit_band(bitfield, 255));
                    bitfield = bit_rshift(bitfield, 8);
                    bitfield_len = bitfield_len - 8;
                  end
                  ch = B64tobyte[str:sub(i, i)];
                  bitfield = bitfield + bit_lshift(ch or 0, bitfield_len);
                  bitfield_len = bitfield_len + 6;
                  if i > l then
                    break;
                  end
                  i = i + 1;
                end
                return table.concat(bit8, "", 1, decoded_size)
            end
            local function StringToTable(inString, fromChat)
                local _, _, encodeVersion, encoded = inString:find("^(!WA:%d+!)(.+)$")
                if encodeVersion then
                  encodeVersion = tonumber(encodeVersion:match("%d+"))
                else
                  encoded, encodeVersion = inString:gsub("^%!", "")
                end

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

        end
    elseif event == "CHAT_MSG_TRADESKILLS" then
        local _msg = TRADESKILL_LOG_FIRSTPERSON:gsub("%%s", "(.+)")
        if strfind(arg[1], _msg) then
            ZL.SyncRolesTimerStart()
        end
    elseif event == "QUEST_TURNED_IN" or event == "CURRENCY_DISPLAY_UPDATE" or event == "PLAYER_MONEY" then
        ZL.SyncRolesTimerStart()
    elseif event == "QUEST_LOG_UPDATE" then
        ZL.SyncRolesTimerStart()
    end
    if (event == "ENCOUNTER_END") then
        if arg[5] == 1 then
            RequestRaidInfo()
        end
    end
--[=[
    if (event == "LOOT_HISTORY_ROLL_COMPLETE") then
        local msgStr = "所有人已ROLL完点"
        ZL.ScrollingMessageFrame:AddMessage(msgStr)
        print(Prefix(msgStr))
        local numItems = C_LootHistory.GetNumItems()
        if numItems == 0 then
            print("没有战利品分配记录。")
            return
        end
    
        for i = 1, numItems do
            local rollID, itemLink, wnumPlayers, isDone, winnerIdx, isMasterLoot = C_LootHistory.GetItem(i)
            print(rollID, itemLink, wnumPlayers, isDone, winnerIdx, isMasterLoot)

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

    if (event == "LOOT_HISTORY_ROLL_CHANGED") then
        local rollID, itemLink, numPlayers, isDone, winnerIdx, isMasterLoot  = C_LootHistory.GetItem(arg[1])
        print(arg[1], arg[2], rollID, itemLink, numPlayers, isDone, winnerIdx, isMasterLoot)
        if isDone then
            print(itemLink, numPlayers, isDone)
            for j = 1, numPlayers do
                local name, class, rollType, roll, isWinner, isMe = C_LootHistory.GetPlayerInfo(arg[1], j)
                print(name, class, rollType, roll, isWinner, isMe)
            end
        end
    end
]=]
    arg:Release()
end

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

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

fZL:SetScript("OnEvent", mainInit)
