local RunesInfoComp = class("RunesInfoComp", LuaComponent)

local LOCK_ICON = "common_lock"
local UNLOCK_ICON = "common_lock_1"

function RunesInfoComp:onClose()
    if self.autoSid then
        self.baseObject:unscheduleGlobal(self.autoSid)
        self.autoSid = nil
    end
    if self.autoSyncSid then
        self.baseObject:unscheduleGlobal(self.autoSyncSid)
        self.autoSyncSid = nil
    end
end

function RunesInfoComp:init()
    local uiMap = self:getUIMap()
    self.btnHelp = uiMap["runes_info.btn_help"]
    self.imgProg = uiMap["runes_info.prog.img_prog"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)
    self.txProg = uiMap["runes_info.prog.tx_prog"]
    self.txLevel = uiMap["runes_info.level.tx_level"]
    self.btnSuit = uiMap["runes_info.btn_suit"]
    self.txSuit = uiMap["runes_info.btn_suit.tx_suit"]
    self.itemMaterial = uiMap["runes_info.item_material"]
    self.txNum = uiMap["runes_info.item_material.tx_num"]
    self.btnUse = uiMap["runes_info.bottom.btn_use"]
    self.txUse = uiMap["runes_info.bottom.btn_use.tx_use"]
    self.imgCost = uiMap["runes_info.bottom.btn_use.cost.img_cost"]
    self.txCost = uiMap["runes_info.bottom.btn_use.cost.tx_cost"]
    self.btnAuto = uiMap["runes_info.bottom.btn_auto"]
    self.spineAuto = uiMap["runes_info.bottom.btn_auto.spine_auto"]
    self.txAuto = uiMap["runes_info.bottom.btn_auto.tx_auto"]
    self.txEmpty = uiMap["runes_info.suits.tx_empty"]
    self.mask = uiMap["runes_info.bottom.mask"]
    self.btnAutoEnd = uiMap["runes_info.bottom.btn_auto_end"]
    self.txAutoEnd = uiMap["runes_info.bottom.btn_auto_end.tx_end"]
    self.suitsNode = uiMap["runes_info.suits"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)
    self.suits = {}
    for i = 1, 3 do
        self.suits[i] = uiMap["runes_info.suits.item_suit_" .. i]
    end
    self.grids = {}
    for i = 1, 6 do
        self.grids[i] = uiMap["runes_info.list_attr.grid_" .. i]
    end

    self.mask:setActive(false)
    self.txSuit:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_2))
    self.txUse:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_5))
    self.txEmpty:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_23))
    self.txAutoEnd:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_29))
    self.txAuto:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_4))

    self.itemMaterial:addClickListener(function()
        UIManager:showUI("app/ui/runes/runes_source_ui")
    end)
    self.btnHelp:addClickListener(function()
        UIManager:showUI("app/ui/runes/runes_level_ui")
    end)
    self.btnSuit:addClickListener(function()
        UIManager:showUI("app/ui/runes/runes_suit_ui", self.heroEntity)
    end)
    self.btnAuto:addClickListener(function()
        if not DataManager.RunesData:canAutoMake() then
            GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_27, DataManager.RunesData:getAutoMakeOpenLevel()))
            return
        end

        local checkIds = DataManager.RunesData:getCheckQualityIds()
        if #checkIds > 0 then
            local params ={
                content = I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_21, I18N:getGlobalText(I18N.GlobalConst["RUNES_QLT_" .. DataManager.RunesData:getCheckQualityIds()[1]]), I18N:getGlobalText(I18N.GlobalConst["RUNES_QLT_" .. DataManager.RunesData:getCheckQualityIds()[2]])),
                boxType = GConst.MESSAGE_BOX_TYPE.MB_OK_CANCEL,
                showToday = GConst.MESSAGE_BOX_SHOW_TODAY.RUNES_AUTO,
                okFunc = function()
                    self:checkQuenching(true)
                end,
            }
            GFunc.showMessageBox(params)
        else
            self:checkQuenching(true)
        end
    end)
    self.btnAutoEnd:addClickListener(function()
        -- 玩家点击停止自动淬炼
        ModuleManager.RunesManager:reqSyncQuenching(true)
    end)
    self.btnUse:addClickListener(function()
        self:checkQuenching(false)
    end)
    self:bind(DataManager.BagData.ItemData, "dirty", function()
        self:refresh()
    end)
    self:bind(DataManager.RunesData, "isDirty", function()
        self:refresh()
    end)
end

function RunesInfoComp:setHeroData(heroEntity)
    self.heroEntity = heroEntity
    self.runesEntity = DataManager.RunesData:getRunes(self.heroEntity:getCfgId())
end

function RunesInfoComp:updateData()
    self.exp = self.runesEntity:getExp()
end

function RunesInfoComp:refresh()
    if self.autoSid then
        self.baseObject:unscheduleGlobal(self.autoSid)
        self.autoSid = nil
    end
    if self.autoSyncSid then
        self.baseObject:unscheduleGlobal(self.autoSyncSid)
        self.autoSyncSid = nil
    end
    if ModuleManager.RunesManager:isInAutoQuenching() then
        self:startAutoQuenching()
        return
    end

    self.txCost:setText(GFunc.getRewardNum(self.runesEntity:getMaterialCost()))
    GFunc.centerImgAndTx(self.imgCost, self.txCost)
    if DataManager.RunesData:canAutoMake() then
        self.spineAuto:playAnim("idle", true, true)
    else
        self.spineAuto:playAnim("idle2", true, true)
    end

    self:refreshLevelExp()
    self:refreshSuit()
    self:refreshRunes()

    if self.isAutoQuenching then
        -- 结束自动淬炼
        self:endAutoQuenching()
    end
end

-- 自动淬炼刷新
function RunesInfoComp:autoQuenching()
    self:refreshSuit()
    self:refreshRunes()

    if not ModuleManager.RunesManager:isInSyncQuenching() then
        DataManager.RunesData:onAutoQuenchingOnce()
        self.tempExp = self.tempExp + self.tempCostNum
        self.tempMaterialCount = self.tempMaterialCount - self.tempCostNum
        self.tempLevel = DataManager.RunesData:getLevelByExp(self.tempExp)

        local curCfg = DataManager.RunesData:getLevelConfig()[self.tempLevel]
        local nextCfg = DataManager.RunesData:getLevelConfig()[self.tempLevel + 1]
        local maxExp = (nextCfg and nextCfg.cost or 0) - (curCfg and curCfg.cost or 0)
        if maxExp then
            local levelExp = self.tempExp - (curCfg and curCfg.cost or 0)
            self.imgProg.value = levelExp / maxExp
            self.txProg:setText(levelExp .. "/" .. maxExp)
        else
            self.imgProg.value = 1
            self.txProg:setText(I18N:getGlobalText(I18N.GlobalConst.STR_MAX))
        end
        self.txLevel:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_1, self.tempLevel))
        self.txNum:setText(GFunc.num2Str(self.tempMaterialCount))
        if self.tempMaterialCount < self.tempCostNum then
            -- 剩余材料不够，结束自动淬炼
            ModuleManager.RunesManager:reqSyncQuenching(true)
        else
            DataManager.RunesData:checkAutoTime()
        end
        EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.RUNE_QUENCHING_SUCCESS, self.tempMaterialCount)
    end
end

-- 刷新等级经验、道具个数
function RunesInfoComp:refreshLevelExp()
    local curExp = DataManager.RunesData:getLevelExp()
    local maxExp = DataManager.RunesData:getNextLevelTotalExp()
    if maxExp then
        self.imgProg.value = curExp / maxExp
        self.txProg:setText(curExp .. "/" .. maxExp)
    else
        self.imgProg.value = 1
        self.txProg:setText(I18N:getGlobalText(I18N.GlobalConst.STR_MAX))
    end
    self.txLevel:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_1, DataManager.RunesData:getLevel()))
    self.txNum:setText(GFunc.num2Str(DataManager.RunesData:getMaterialCount()))
end

-- 刷新符文
function RunesInfoComp:refreshRunes()
    for index, obj in ipairs(self.grids) do
        local map = obj:genAllChildren()
        local imgQlt = map["img_qlt"]
        local imgSuit = map["img_suit"]
        local txAttr = map["tx_attr"]
        local imgLock = map["img_lock"]
        local lock = map["lock"]
        local txLock = map["tx_lock"]
        obj:getComponent(GConst.TYPEOF_UNITY_CLASS.ANIMATOR).enabled = false

        if ModuleManager.RunesManager:isInAutoQuenching() and index <= DataManager.RunesData:getLevelConfig()[self.tempLevel].grid or DataManager.RunesData:isUnlock(index) then
            lock:setActive(false)
            local qlt = self.runesEntity:getGridQuality(index)
            if qlt then
                imgQlt:setSprite(GConst.ATLAS_PATH.HERO, GConst.RunesConst.QUALITY_ICON[qlt])
            end
            local suit = self.runesEntity:getGridSuit(index)
            if suit then
                imgSuit:setSprite(GConst.ATLAS_PATH.HERO, "hero_rune_"..suit)
            end
            imgLock:setSprite(GConst.ATLAS_PATH.COMMON, self.runesEntity:isAttrLock(index) and LOCK_ICON or UNLOCK_ICON)
            local attr = self.runesEntity:getGridAttr(index)
            if attr then
                txAttr:setText(GFunc.getAttrDesc(attr.type, attr.num))
            end
            imgLock:addClickListener(function()
                ModuleManager.RunesManager:reqChangeLockGrid(self.heroEntity:getCfgId(), index, not self.runesEntity:isAttrLock(index))
            end)
        else
            lock:setActive(true)
            txLock:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_3, DataManager.RunesData:getUnlockLevel(index)))
        end
	end
end

-- 刷新套装
function RunesInfoComp:refreshSuit()
    local ids = self.runesEntity:getSuitIds()

    local isEmpty = true
    for index, obj in ipairs(self.suits) do
        local map = obj:genAllChildren()
        local img = map["img"]
        local tx = map["tx"]

        if ids[index] then
            local level = self.runesEntity:getSuitLevel(ids[index].id)
            if level > 0 then
                isEmpty = false
                obj:setActive(true)
                img:setSprite(GConst.ATLAS_PATH.HERO, "hero_rune_"..ids[index].id)
                tx:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_26, level))
            else
                obj:setActive(false)
            end
        else
            obj:setActive(false)
        end
	end

    self.txEmpty:setActive(isEmpty)

    self.suitsNode:RefreshLayout()
end

-- 检查淬炼
function RunesInfoComp:checkQuenching(isAuto)
    -- 是否全部锁定
    if DataManager.RunesData:getRunes(self.heroEntity:getCfgId()):getAttrLockCount() >= DataManager.RunesData:getUnlockCount() then
        GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_25))
        return
    end
    -- 材料是否足够
    local cost = self.runesEntity:getMaterialCost()
    if not GFunc.checkCost(GFunc.getRewardId(cost), GFunc.getRewardNum(cost), true) then
        UIManager:showUI("app/ui/runes/runes_source_ui")
        return
    end

    if self.runesEntity:isUnlockHighQlt() then
        local params ={
            content = I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_28, I18N:getGlobalText(I18N.GlobalConst["RUNES_QLT_" .. DataManager.RunesData:getCheckQualityIds()[1]])),
            boxType = GConst.MESSAGE_BOX_TYPE.MB_OK_CANCEL,
            okText = I18N:getGlobalText(I18N.GlobalConst.CONTINUE_DESC),
            okFunc = function()
                self:reqQuenching(isAuto)
            end,
        }
        GFunc.showMessageBox(params)
    else
        self:reqQuenching(isAuto)
    end
end

-- 请求淬炼
function RunesInfoComp:reqQuenching(isAuto)
    if isAuto then
        -- 自动淬炼
        self.isAutoQuenching = true
        self.mask:setActive(true)
        self.btnUse:setActive(false)
        self.txAuto:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_30))
        self.spineAuto:playAnim("attack", true, true)
        ModuleManager.RunesManager:reqAutoQuenching(self.heroEntity:getCfgId())
    else
        -- 单次淬炼
        ModuleManager.RunesManager:reqQuenching(self.heroEntity:getCfgId())
    end
end

-- 开始自动淬炼
function RunesInfoComp:startAutoQuenching()
    self.tempLevel = DataManager.RunesData:getLevel()
    self.tempExp = DataManager.RunesData:getExp()
    self.tempCostNum = self.runesEntity:getMaterialCostNum()
    self.tempMaterialCount = DataManager.RunesData:getMaterialCount()

    self.autoSid = self.baseObject:scheduleGlobal(function() self:autoQuenching() end, 1 / GConst.RunesConst.AUTO_INTERVAL)
    self.autoSyncSid = self.baseObject:scheduleGlobal(function() ModuleManager.RunesManager:reqSyncQuenching(false, true) end, GConst.RunesConst.SYNC_INTERVAL)
end

-- 结束自动淬炼
function RunesInfoComp:endAutoQuenching()
    self.isAutoQuenching = false
    self.mask:setActive(false)
    self.btnUse:setActive(true)
    self.txAuto:setText(I18N:getGlobalText(I18N.GlobalConst.RUNES_DESC_4))
    self.spineAuto:playAnim("idle", true, true)

    for index, obj in ipairs(self.grids) do
        local qlt = self.runesEntity:getGridQuality(index)
        if qlt and table.containValue(DataManager.RunesData:getCheckQualityIds(), qlt) and not self.runesEntity:isAttrLock(index) then
            obj:getTransform():SetAsLastSibling()
            local animator = obj:getComponent(GConst.TYPEOF_UNITY_CLASS.ANIMATOR)
            animator.enabled = true
            -- CS.UnityEngine.Animator.StringToHash("runes_shake") 结果是1132417824
            animator:Play(1132417824, -1, 0)
        end
	end
end

return RunesInfoComp