local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local GetDiffTime = ZL.GetDiffTime
local emptytable = ZL.emptytable
local cGetItemInfo = C_Item and C_Item.GetItemInfo or GetItemInfo
local PickupContainerItem = C_Container and C_Container.PickupContainerItem or PickupContainerItem

ChatFrame_AddMessageEventFilter("CHAT_MSG_SYSTEM", function (self, event, text)
    if event == "CHAT_MSG_SYSTEM" and text == ERR_CHAT_THROTTLED then
        return true
    end
end)
local defaults = {
	profile = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
        AuctionSortLock = true,
        AuctionStartPrice= 99,
        AucitonPriceDown = 1,
        DefaultStackCount = 1,
        DefaultNumStacks = 1,
        defaultStackCountOrdefaultNumStacksFirst = 1,
        AuctionPriceSaveDays = 7,
        BuyItemsHistorySaveDays = 28,
        ShowBuyItemsHistorySaveDays = 1,
        AuctionDefaultTime = 1,
        AHPriceChartDays = 7,
  	},
    global = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
	},
}
function ZL:OnProfileEnable()
	ZL.opt = ZL.db.profile
    ZL.glb = ZL.db.global
end

local function tooltipInfo(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
    if ZL.opt.showItemCounts then
        local inventoryCount, bagCount, itemBankCount, itemTotalCount = ZL.GetItemNumbers(itemId)
        local auctionCount = ZL.opt.OwnAuctionItemsCount and (ZL.opt.OwnAuctionItemsCount[itemId] or 0) or 0
        itemTotalCount = itemTotalCount + auctionCount
        local txt = ""
        if inventoryCount > 0 then
            txt = "装备: |cffffffff" .. inventoryCount .. "|r "
        end
        if bagCount > 0 then
            txt = txt .. "背包: |cffffffff" .. bagCount .. "|r "
        end
        if itemBankCount > 0 then
            txt = txt .. "银行: |cffffffff" .. itemBankCount .. "|r "
        end
        if auctionCount > 0 then
            txt = txt .. "拍卖: |cffffffff" .. auctionCount .. "|r "
        end
        if itemTotalCount > 0 then
            txt = txt .. "|cff03CCFF合计: |r|cffffffff" .. itemTotalCount .. "|r"
            GameTooltip:AddLine(txt)
        end
    end
    if ZL.opt.showSoldToNPC then
        local sellPrice = select(11, cGetItemInfo(itemId))
        if sellPrice and sellPrice > 0 then
            GameTooltip:AddLine("商人：|cffffffff" .. GetMoneyString(sellPrice) .. "|r")
        end
    end
    if ZL.opt.showAuctionPostItemsHistoryPrice and ZL.opt.AuctionPostItemsHistoryPrice and ZL.opt.AuctionPostItemsHistoryPrice[itemId] then
        local itemIdInfo = ZL.opt.AuctionPostItemsHistoryPrice[itemId][1]
        if itemIdInfo then
            local diffDate = floor(GetDiffTime(itemIdInfo[3], date("%Y-%m-%d", time())) / 86400)
            local dayTxt = ""
            if diffDate == 0 then
                dayTxt = "今日"
            elseif diffDate == 1 then
                dayTxt = "昨日"
            elseif diffDate == 2 then
                dayTxt = "前日"
            else
                dayTxt = diffDate .. "天前"
            end
            GameTooltip:AddLine(dayTxt .. "最低：|cffffffff" .. GetMoneyString(itemIdInfo[1]) .. "|r")
            GameTooltip:AddLine(dayTxt .. "最近：|cffffffff" .. GetMoneyString(itemIdInfo[2]) .. "|r")
        end
    end
    if ZL.opt.showBuyItemsHistoryPrice and ZL.opt.BuyItemsHistoryList and ZL.opt.BuyItemsHistoryList[itemId] and next(ZL.opt.BuyItemsHistoryList[itemId]) then
        local priceList = ZL.opt.BuyItemsHistoryList[itemId]
        local perPrcie, totalCount, totalMoney = 0, 0, 0
        for d, data in pairs(priceList) do
            if GetDiffTime(d, date("%Y-%m-%d", time())) < ZL.opt.ShowBuyItemsHistorySaveDays*86400 then
                totalCount = totalCount + data[1]
                totalMoney = totalMoney + data[2]
            end
        end
        if totalCount > 0 and totalMoney > 0 then
            GameTooltip:AddLine(format("%d天购买均价:|cffffffff%s|r", ZL.opt.ShowBuyItemsHistorySaveDays, GetMoneyString(perPrcie)))
        end
    end
--[=[  
    if ZL.opt.showAHPriceChartFrame then
        -- print(ZL.getDateDaysAgo(1), ZL.getDateDaysAgo(2), ZL.getDateDaysAgo(3))
        local AHPriceChartFrame = ZL.AHPriceChartFrame
        for _, f in ipairs(AHPriceChartFrame.scanEntries) do f:Hide() end
        local showDays = ZL.opt.AHPriceChartDays
        local pointSpacing = AHPriceChartFrame:GetWidth() / (showDays+1) -- 数据点之间的水平间距
        if ZL.opt.AuctionPostItemsHistoryPrice and ZL.opt.AuctionPostItemsHistoryPrice[itemId] and #ZL.opt.AuctionPostItemsHistoryPrice[itemId]>0 then
            local scanPriceList = {}
            local info = ZL.opt.AuctionPostItemsHistoryPrice[itemId]
            local tarDate, price
            local minPrice, maxPrice = 0, 0
            for i = (showDays-1), 0, -1 do
                tarDate = ZL.getDateDaysAgo(i)
                price = 0
                for _, data in ipairs(info) do
                    if data[3] == tarDate then
                        price = data[1]
                        break
                    end
                end
                tinsert(scanPriceList, price)
                if price > 0 then
                    minPrice = minPrice==0 and price or min(minPrice, price)
                    maxPrice = maxPrice==0 and price or max(maxPrice, price)
                end
            end
            local f
            local barSpacing = (AHPriceChartFrame:GetWidth()-10)/showDays
            local barWidth = barSpacing*0.9
            local barHeight = AHPriceChartFrame:GetHeight()-20
            for i, v in ipairs(scanPriceList) do
                -- print(v, maxPrice)
                f = AHPriceChartFrame.scanEntries[i]
                f:SetSize(barWidth, v==0 and 0.001 or (v / maxPrice) * barHeight)
                f:SetPoint("BOTTOMLEFT", AHPriceChartFrame, "BOTTOMLEFT", (i - 1) * barSpacing+5, 0)
                f:Show()
            end
            scanPriceList = nil
            f = nil
        end
        -- GameTooltip_AddBlankLineToTooltip(GameTooltip)
        GameTooltip_InsertFrame(GameTooltip, ZL.AHPriceChartFrame)
    end
]=]  
end

local function mainInit(self, event, ...)
    local arg = emptytable(...)
    if event == "ADDON_LOADED" and arg[1] == "FastAuction" then
        ZL:UnregisterEvent("ADDON_LOADED")
        SLASH_FA_RELOAD1 = "/rl"
        SlashCmdList.FA_RELOAD = ReloadUI

        ZL.db = LibStub("AceDB-3.0"):New("FA_Profile", defaults, true) --创建默认配置数据库
        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.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = "Interface\\AddOns\\" .. addonName .. "\\Images\\FA.png",
			OnClick = function(self, button)
                if button == "LeftButton" then
                    
                end
			end,
		})
        
        function ZL.LDB:OnTooltipShow()
            self:AddLine("FastAuction[拍卖行助手FA](|cffffffff" .. ZL.addonVersion .. "|r)")
            self:AddLine("支持时光服拍卖行无卡顿快速批量购买、发布和取消拍卖", 1, 1, 1, true)
            self:AddLine(" ")
            self:AddLine("左键|cffffffff: 打开设置|r ")
        end
        function ZL.LDB:OnEnter()
            ZL.LDB.OnTooltipShow(GameTooltip)
            GameTooltip:Show()
        end
        function ZL.LDB:OnLeave()
            GameTooltip:Hide()
        end
        ZL.FAminimapicon = LibStub("LibDBIcon-1.0")
		ZL.FAminimapicon:Register("FASTAUCTION", ZL.LDB, ZL.opt)
        GameTooltip:HookScript("OnTooltipSetItem", tooltipInfo)
        ItemRefTooltip:HookScript("OnTooltipSetItem", tooltipInfo)

        local function hookContainerFrameItemButton_OnModifiedClick(self, button)
            local containerInfo = C_Container.GetContainerItemInfo(self:GetParent():GetID(), self:GetID())
            if not containerInfo then return end
            if button == "LeftButton" and IsShiftKeyDown() and AuctionFrameBrowse and AuctionFrameBrowse:IsShown() then
                local itemIsValidAuctionItem = true--(itemLocation:IsValid() and C_AuctionHouse.IsSellItemValid(itemLocation, --[[ displayError = ]] false))
                if itemIsValidAuctionItem then
                    ClearCursor()
                    ClickAuctionSellItemButton()
                    ClearCursor()
                    PickupContainerItem(self:GetParent():GetID(), self:GetID())
                    ClickAuctionSellItemButton()
                    ClearCursor()
                end
            end
        end
        hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", hookContainerFrameItemButton_OnModifiedClick)
    elseif event == "PLAYER_LOGIN" then
        if not ZL.ScrollingMessageFrame then ZL:CreateScrollingMessageFrame() end
        LibDBIcon10_FASTAUCTION:Hide()
    end
    wipe(arg)
end

ZL:RegisterEvent("ADDON_LOADED")
ZL:RegisterEvent("PLAYER_LOGIN")
ZL:SetScript("OnEvent", mainInit)
