local addonName, ZLAUTO = ...

local ZL = ZLAUTO.mainFrame
local ScrollFrame_OnMouseWheel = ZL.ScrollFrame_OnMouseWheel
local CreateButton = ZL.CreateButton
local GameTooltipShow = ZL.GameTooltipShow
local CreateEditBox = ZL.CreateEditBox
local ZLCreateFrame = ZL.ZLCreateFrame
local emptytable = ZL.emptytable

function ZL:CreateImportWagesFrame()
    local playerNameWidth, wagesWidth, stateWidth, tradeWidth, delWidth = 180, 100, 60, 60, 60
    local lineHeight = 20
    local totalWidth = playerNameWidth + wagesWidth + stateWidth + tradeWidth + delWidth + 30

    ZL.ImportWagesFrame = ZLCreateFrame(nil, ZL, 800, 600, nil, true, true, "手动交易工资记录")
    local ImportWagesFrame = ZL.ImportWagesFrame
    ImportWagesFrame:Hide()
    ImportWagesFrame:SetResizeBounds(totalWidth, 400, totalWidth, GetScreenHeight()-110)
    ImportWagesFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
        if not ZL.glb.ZLImportWagesFrame then ZL.glb.ZLImportWagesFrame = {} end
        ZL.glb.ZLImportWagesFrame.point, _, ZL.glb.ZLImportWagesFrame.relative, ZL.glb.ZLImportWagesFrame.x, ZL.glb.ZLImportWagesFrame.y = self:GetPoint()
    end)
    ImportWagesFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    ImportWagesFrame:SetScript("OnShow", function (self)
        ImportWagesFrame:Update()
    end)
    local resizeButton = ImportWagesFrame.resizeButton
    -- 设置鼠标按下时开始调整大小
    resizeButton:SetScript("OnMouseDown", function(self, button)
        if button == "LeftButton" then
            ImportWagesFrame:StartSizing("BOTTOMRIGHT")
        end
    end)
    -- 鼠标松开时停止调整大小
    resizeButton:SetScript("OnMouseUp", function(self, button)
        ImportWagesFrame:StopMovingOrSizing()
        ZL.glb.ZLImportWagesFrame = ZL.glb.ZLImportWagesFrame or {}
        ZL.glb.ZLImportWagesFrame.Width, ZL.glb.ZLImportWagesFrame.Height = ImportWagesFrame:GetSize()
    end)
    ImportWagesFrame:ClearAllPoints()
    if ZL.glb.ZLImportWagesFrame and ZL.glb.ZLImportWagesFrame.point then
        ImportWagesFrame:SetPoint(ZL.glb.ZLImportWagesFrame.point, UIParent, ZL.glb.ZLImportWagesFrame.relative, ZL.glb.ZLImportWagesFrame.x, ZL.glb.ZLImportWagesFrame.y)
    else
        ImportWagesFrame:SetPoint("CENTER")
    end
    if ZL.glb.ZLImportWagesFrame and ZL.glb.ZLImportWagesFrame.Height then
        ImportWagesFrame:SetSize(totalWidth, min(ZL.db.global.ZLImportWagesFrame.Height, GetScreenHeight()-110))
    else
        ImportWagesFrame:SetSize(totalWidth, 400)
    end

    local importBtn = CreateButton(nil, ImportWagesFrame, "导入/导出", "TOPLEFT", ImportWagesFrame.TitleBottom, "BOTTOMLEFT", 3, -10, 110, 20, 14, true, 0)
    importBtn:SetScript("OnClick", function ()
        if not ZL.ExportWagesFrame then ZL:CreateExportWagesFrame() end
        ZL.ExportWagesFrame:Show()
    end)
    local btnTexture = [[Interface\ACHIEVEMENTFRAME\UI-Achievement-Parchment-Horizontal]]
    local playerNameBtn = CreateButton(nil, ImportWagesFrame, "角色名", "TOPLEFT", importBtn, "BOTTOMLEFT", 0, -5, playerNameWidth)
    playerNameBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    playerNameBtn:SetNormalTexture(btnTexture)
    playerNameBtn:ClearHighlightTexture()

    local wagesBtn = CreateButton(nil, ImportWagesFrame, "金额", "LEFT", playerNameBtn, "RIGHT", 0, 0, wagesWidth)
    wagesBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    wagesBtn:SetNormalTexture(btnTexture)
    wagesBtn:ClearHighlightTexture()

    local stateBtn = CreateButton(nil, ImportWagesFrame, "状态", "LEFT", wagesBtn, "RIGHT", 0, 0, stateWidth)
    stateBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    stateBtn:SetNormalTexture(btnTexture)
    stateBtn:ClearHighlightTexture()

    local tradeBtn = CreateButton(nil, ImportWagesFrame, "交易", "LEFT", stateBtn, "RIGHT", 0, 0, tradeWidth)
    tradeBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    tradeBtn:SetNormalTexture(btnTexture)
    tradeBtn:ClearHighlightTexture()

    local delBtn = CreateButton(nil, ImportWagesFrame, "删除", "LEFT", tradeBtn, "RIGHT", 0, 0, delWidth)
    delBtn:GetFontString():SetFont(GameFontNormal:GetFont(), 14, "OUTLINE")
    delBtn:SetNormalTexture(btnTexture)
    delBtn:ClearHighlightTexture()

    --创建滚动条
    ImportWagesFrame.ScrollFrame = CreateFrame("ScrollFrame", nil, ImportWagesFrame, "UIPanelScrollFrameTemplate")
    local SearchItemsFrame_ScrollFrame = ImportWagesFrame.ScrollFrame
    SearchItemsFrame_ScrollFrame:SetFrameLevel(ImportWagesFrame:GetFrameLevel() + 1)
    SearchItemsFrame_ScrollFrame:SetPoint("TOPLEFT", playerNameBtn, "BOTTOMLEFT", 0, 0)
    SearchItemsFrame_ScrollFrame:SetPoint("BOTTOMRIGHT", ImportWagesFrame, "BOTTOMRIGHT", -2, 3)
    SearchItemsFrame_ScrollFrame:SetClipsChildren(true)
    SearchItemsFrame_ScrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel)
    SearchItemsFrame_ScrollFrame.ScrollBar:ClearAllPoints()
    SearchItemsFrame_ScrollFrame.ScrollBar:SetPoint("TOPLEFT", SearchItemsFrame_ScrollFrame, "TOPRIGHT", -20, -16)
    SearchItemsFrame_ScrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", SearchItemsFrame_ScrollFrame, "BOTTOMRIGHT", 0, 16)
    SearchItemsFrame_ScrollFrame.content = CreateFrame("Frame", nil, SearchItemsFrame_ScrollFrame)
    local wagesListContent = SearchItemsFrame_ScrollFrame.content
    wagesListContent:SetPoint("TOPLEFT", SearchItemsFrame_ScrollFrame, "TOPLEFT", 0, 0)
    wagesListContent:SetSize(180, 100)
    SearchItemsFrame_ScrollFrame:SetScrollChild(wagesListContent)
    local function OnEnter(f)
        f:SetNormalTexture("Interface\\FriendsFrame\\UI-FriendsFrame-HighlightBar")
    end
    local function OnLeave(f)
        f:ClearNormalTexture()
    end
    ImportWagesFrame.entries = setmetatable({}, {
        __index = function (t, v)
            local f = CreateFrame("Button", nil, wagesListContent)
            f:Hide()
            f:SetScript("OnEnter", OnEnter)
            f:SetScript("OnLeave", OnLeave)
            f:SetSize(totalWidth-30, lineHeight)
            f:SetPoint("TOPLEFT", wagesListContent, "TOPLEFT", 0, -(v-1)*lineHeight)
            f.Background = f:CreateTexture(nil,"BACKGROUND")
            f.Background:SetPoint("TOPLEFT")
            f.Background:SetPoint("BOTTOMRIGHT")
            if v%2 == 1 then
                f.Background:SetColorTexture(0, 0, 0, .8)
            else
                f.Background:SetColorTexture(0.15, 0.15, 0.15, .8)
            end
            f.playerNameLabel = f:CreateFontString(nil, "ARTWORK")
            f.playerNameLabel:SetFont(GameFontNormal:GetFont(), 13, "OUTLINE")
            f.playerNameLabel:SetSize(playerNameWidth, lineHeight)
            f.playerNameLabel:SetPoint("LEFT")
            f.playerNameLabel:SetJustifyH("LEFT")
            f.wagesBox = CreateEditBox(f, wagesWidth, lineHeight-2, 13, "RIGHT")
            f.wagesBox:SetPoint("LEFT", f.playerNameLabel, "RIGHT", 0, 0)
            f.wagesBox.Background:SetColorTexture(0,0,0,0)
            -- f.wagesBox:SetScript("OnEnter", function ()
            --     OnEnter(f)
            -- end)
            -- f.wagesBox:SetScript("OnLeave", function ()
            --     OnLeave(f)
            -- end)
            f.wagesBox:SetScript("OnTextChanged", function (self)
                local wages = self:GetNumber()
                ZL.opt.ManualImportWagesRecords[f.playerName][1] = wages
                f.wages = wages
            end)

            f.stateBtn = CreateFrame("Button", nil, f)
            f.stateBtn:SetSize(stateWidth, lineHeight)
            f.stateBtn:SetPoint("LEFT", f.wagesBox, "RIGHT", 0, 0)
            f.stateBtn.stateIcon = f.stateBtn:CreateTexture(nil, "OVERLAY")
            f.stateBtn.stateIcon:SetSize(lineHeight, lineHeight)
            f.stateBtn.stateIcon:SetPoint("LEFT", f.stateBtn, "LEFT", (stateWidth-lineHeight)/2, 0)
            f.stateBtn:SetScript("OnEnter", function ()
                OnEnter(f)
            end)
            f.stateBtn:SetScript("OnLeave", function ()
                OnLeave(f)
            end)
            f.stateBtn:SetScript("OnClick", function (self)
                local function tempMenuTable()
                    local menuList = {
                        {text="更改交易状态", isTitle=1},
                    }
                    for i, va in ipairs({"已交易", "未交易"}) do
                        tinsert(menuList, {
                            text = va,
                            checkable = 1,
                            checked = function ()
                                if i == 1 then
                                    if ZL.opt.ManualImportWagesRecords[f.playerName][2] then
                                        return true
                                    else
                                        return false
                                    end
                                else
                                    if ZL.opt.ManualImportWagesRecords[f.playerName][2] then
                                        return false
                                    else
                                        return true
                                    end
                                end
                            end,
                            func = function ()
                                if i == 1 then
                                    ZL.opt.ManualImportWagesRecords[f.playerName][2] = true
                                else
                                    ZL.opt.ManualImportWagesRecords[f.playerName][2] = false
                                end
                                ImportWagesFrame:Update()
                            end
                        })
                    end
                    return menuList
                end
                ZL.GUI:ToggleMenu(self, tempMenuTable(), 'TOPLEFT', self, 'BOTTOMLEFT', 0, 0)
            end)

            f.tradeBtn = CreateButton(nil, f, "交易", "LEFT", f.stateBtn, "RIGHT", 0, 0, tradeWidth, lineHeight-2, 13, true, 0)
            f.tradeBtn:SetScript("OnEnter", function ()
                OnEnter(f)
            end)
            f.tradeBtn:SetScript("OnLeave", function ()
                OnLeave(f)
            end)
            f.tradeBtn:SetScript("OnClick", function (self)
                local playerName = ZL.GetFullName(f.playerName)
                playerName = ZL.pruneCrossRealm(playerName)
                if not UnitExists(playerName) then
                    ZL.Print(format("|cffffffff%s|r 不存在", playerName))
                    return
                end
                if UnitIsDeadOrGhost(playerName) then
                    ZL.Print(format("|cffffffff%s|r 死亡状态，无法交易", playerName))
                    return
                end
                if InCombatLockdown() then
                    ZL.Print("战斗中，无法交易")
                    return
                end
                if not CheckInteractDistance(playerName, 2) then
                    ZL.Print(format("|cffffffff%s|r 超出交易范围", playerName))
                    return
                end
                if GetMoney() < f.wages*10000 then
                    ZL.Print("金币不足，无法交易。")
                    return
                end
                self:Disable()
                C_Timer.After(3, function ()
                    self:Enable()
                end)
                local hasOpenTrade, hasCloseTrade
                local function startTrade()
                    if TradeFrame and TradeFrame:IsShown() then
                        if not hasCloseTrade and not hasOpenTrade then
                            TradeFrame:Hide()
                            hasCloseTrade = true
                            C_Timer.After(0.3, startTrade)
                        end
                        if hasOpenTrade then
                            ClickTradeButton(1)
                            C_Timer.After(0.3, function ()
                                AcceptTrade()
                            end)
                        end
                    else
                        if not hasOpenTrade then
                            ImportWagesFrame.tradeGongZi = f.wages*10000
                            ImportWagesFrame.playerName = f.playerName
                            PickupPlayerMoney(f.wages*10000)
                            InitiateTrade(f.playerName)
                            hasOpenTrade = true
                        end
                        C_Timer.After(0.1, startTrade)
                    end
                end
                startTrade()
            end)
            f.delBtn = CreateButton(nil, f, "-", "LEFT", f.tradeBtn, "RIGHT", 0, 0, delWidth, lineHeight)
            f.delBtn:SetPoint("LEFT", f.tradeBtn, "RIGHT", 0, 0)
            f.delBtn.Background:SetColorTexture(0,0,0,0)
            f.delBtn.BorderTop:Hide()
            f.delBtn.BorderLeft:Hide()
            f.delBtn.BorderBottom:Hide()
            f.delBtn.BorderRight:Hide()
            f.delBtn:SetScript("OnClick", function ()
                ZL.opt.ManualImportWagesRecords[f.playerName] = nil
                ImportWagesFrame:Update()
            end)
            f.delBtn:SetScript("OnEnter", function ()
                OnEnter(f)
            end)
            f.delBtn:SetScript("OnLeave", function ()
                OnLeave(f)
            end)
            t[v] = f
            return f
        end
    })

    function ImportWagesFrame:Update()
        for _, f in ipairs(ImportWagesFrame.entries) do f:Hide() end
        if ZL.opt.ManualImportWagesRecords and next(ZL.opt.ManualImportWagesRecords) then
            local tmepList = {}
            local f, data
            for name in pairs(ZL.opt.ManualImportWagesRecords) do
                tinsert(tmepList, name)
            end
            sort(tmepList)
            for i, name in ipairs(tmepList) do
                data = ZL.opt.ManualImportWagesRecords[name]
                f = ImportWagesFrame.entries[i]
                f.playerName = name
                f.wages = data[1]
                f.playerNameLabel:SetText(name)
                f.wagesBox:SetNumber(data[1])
                if data[2] then
                    f.stateBtn.stateIcon:SetTexture([[interface/raidframe/readycheck-ready]])
                    f.tradeBtn:Disable()
                else
                    f.stateBtn.stateIcon:SetTexture()
                    f.tradeBtn:Enable()
                end
                f:Show()
            end
        end
    end

    -- ImportWagesFrame:RegisterEvent("TRADE_SHOW")
    -- ImportWagesFrame:RegisterEvent("TRADE_CLOSED")
    ImportWagesFrame:RegisterEvent("UI_INFO_MESSAGE")
    -- ImportWagesFrame:RegisterEvent("PLAYER_TRADE_MONEY")
    ImportWagesFrame:SetScript("OnEvent", function (self, event, ...)
        local arg = emptytable(...)
        if event == "UI_INFO_MESSAGE" then
            if arg[2] == ERR_TRADE_COMPLETE  then
                if ImportWagesFrame.playerName and ImportWagesFrame.tradeGongZi then
                    ZL.opt.ManualImportWagesRecords[ImportWagesFrame.playerName][2] = true
                    ImportWagesFrame.tradeGongZi = nil
                    ImportWagesFrame.playerName = nil
                    ImportWagesFrame:Update()
                end
            else
                if ZL.isTradeFailed(arg[2]) then
                    ImportWagesFrame.tradeGongZi = nil
                    ImportWagesFrame.playerName = nil
                end
            end
        end
        wipe(arg)
    end)

end

function ZL:CreateExportWagesFrame()
    ZL.ExportWagesFrame = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
    ExportWagesFrame = ZL.ExportWagesFrame
    ExportWagesFrame:Hide()
    ExportWagesFrame:SetSize(600, 400)
    ExportWagesFrame:SetPoint("CENTER")
    ExportWagesFrame:SetFrameStrata("DIALOG")
    ExportWagesFrame:SetToplevel(true)
    ExportWagesFrame:SetMovable(true)
    ExportWagesFrame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true,
        tileSize = 32,
        edgeSize = 32,
        insets = { left = 11, right = 12, top = 12, bottom = 11 }
    })
    ExportWagesFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
    end)
    ExportWagesFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    ExportWagesFrame:SetScript("OnShow", function ()
        ExportWagesFrame.ScrollingEditBox:SetText("")
    end)
    local colseBtn = CreateFrame("Button", nil, ExportWagesFrame, "UIPanelCloseButton")
    colseBtn:SetSize(25, 25)
    colseBtn:SetPoint("TOPRIGHT", -15, -15)
    local lable1 = ExportWagesFrame:CreateFontString(nil, "ARTWORK")
    lable1:SetSize(ExportWagesFrame:GetWidth()-30, 20)
    lable1:SetFont(GameFontNormal:GetFont(), 18)
    lable1:SetPoint("TOP", 0, -20)
    lable1:SetText("导入/导出工资清单")
    lable1:SetTextColor(1, 0.82, 0)

    local importBtn = CreateButton(nil, ExportWagesFrame, "导入", "TOPLEFT", ExportWagesFrame, "TOPLEFT", 15, -lable1:GetHeight()-25, 60, 20, 14, true, 0)
    importBtn:SetScript("OnClick", function ()
        local text = ZL.ExportWagesFrame.ScrollingEditBox:GetText() or ""
        if #text == 0 then
            ZL.Print("请粘贴需要导入的工资文本", true, nil, 1, 0, 0)
            return
        end
        local tempList = {}
        local textList = strsplittable(";", text)
        tDeleteItem(textList, "")
        local name, wages, groupList
        local totalRecords = 0
        for _, group in ipairs(textList) do
            groupList = strsplittable(",", group)
            tDeleteItem(groupList, "")
            if #groupList == 2 or #groupList == 3 then
                name = groupList[1]
                wages = tonumber(groupList[2]) or 0
                tempList[name] = {wages, false}
                totalRecords = totalRecords + 1
            end
        end
        if totalRecords > 0 then
            ZL.opt.ManualImportWagesRecords = tempList
            ZL.ImportWagesFrame:Update()
        end
        ZL.Print(format("导入记录数：%d", totalRecords))
        tempList = nil
    end)
    importBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("文本格式要求")
        GameTooltip:AddLine("1、角色A-服务器,1000\\n角色B-服务器,2000\\n角色C-服务器,3000", 1, 1, 1)
        GameTooltip:AddLine("2、需带服务器名字，不带服务器名字的默认为当前角色服务器", 1, 1, 1)
        GameTooltip:Show()
    end)
    importBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    local exportBtn = CreateButton(nil, ExportWagesFrame, "导出", "LEFT", importBtn, "RIGHT", 5, 0, 60, 20, 14, true, 0)
    ExportWagesFrame.exportBtn = exportBtn
    exportBtn:SetScript("OnClick", function ()
        if ZL.opt.ManualImportWagesRecords and next(ZL.opt.ManualImportWagesRecords) then
            local txt
            for name, data in pairs(ZL.opt.ManualImportWagesRecords) do
                if not txt then
                    txt = format("%s,%d,%s", name, data[1], data[2] and "true" or "false")
                else
                    txt = txt .. ";" .. format("%s,%d,%s", name, data[1], data[2] and "true" or "false")
                end
            end
            ZL.ExportWagesFrame.ScrollingEditBox:SetText(txt)
            ZL.ExportWagesFrame.ScrollingEditBox:SetFocus()
            ZL.ExportWagesFrame.ScrollingEditBox:HighlightText()
            txt = nil
        else
            ZL.Print("没有工资交易记录！")
        end
    end)

    local sf = CreateFrame("Frame", nil, ExportWagesFrame, "TooltipBackdropTemplate")
    sf:SetPoint("TOPLEFT", importBtn, "BOTTOMLEFT", 0, -5)
    sf:SetPoint("BOTTOMRIGHT", ExportWagesFrame, "BOTTOMRIGHT", -15, 15)
    local ScrollFrame = CreateFrame("ScrollFrame", nil, sf, "UIPanelScrollFrameTemplate")
    ScrollFrame:SetPoint("TOPLEFT", 10, -8)
    ScrollFrame:SetPoint("BOTTOMRIGHT", -5, 8)
    ScrollFrame:SetClipsChildren(true)
    ScrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel)
    ScrollFrame.ScrollBar:ClearAllPoints()
    ScrollFrame.ScrollBar:SetPoint("TOPLEFT", ScrollFrame, "TOPRIGHT", -18, -18)
    ScrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", ScrollFrame, "BOTTOMRIGHT", 2, 18)
    local ScrollingEditBox = CreateFrame("EditBox", nil, ScrollFrame)
    ExportWagesFrame.ScrollingEditBox = ScrollingEditBox
    ScrollingEditBox:SetSize(ScrollFrame:GetWidth()-20, 20)
    ScrollingEditBox:SetMultiLine(true)
    ScrollingEditBox:SetAutoFocus(false)
    ScrollingEditBox:SetFontObject("GameFontHighlightSmall")
    ScrollFrame:SetScrollChild(ScrollingEditBox)
    ScrollFrame:SetScript("OnMouseDown", function ()
        ScrollingEditBox:SetFocus()
    end)
    ScrollFrame:SetScript("OnMouseUp", function ()
        ScrollingEditBox:HighlightText()
    end)
    ScrollingEditBox:SetScript("OnEscapePressed",function (self)
        self:ClearFocus()
    end)
    ScrollingEditBox:SetScript("OnEditFocusLost",function (self)
        self:HighlightText(0, 0)
    end)
    ScrollingEditBox:SetScript("OnEditFocusGained",function (self)
        self:HighlightText()
    end)
    ScrollingEditBox:SetScript("OnMouseUp", function (self)
        self:HighlightText()
    end)
end