local ArmorInfoComp = class("ArmorInfoComp", LuaComponent)
local BTN_ICON = {"common_btn_green_2", "common_btn_grey_2"}
local DEFAULT_FACTOR = GConst.BattleConst.DEFAULT_FACTOR
local ARMOR_PART_INDEX = {
    [1] = GConst.EquipConst.PART_TYPE.HAT,
    [2] = GConst.EquipConst.PART_TYPE.CLOTHES,
    [3] = GConst.EquipConst.PART_TYPE.HANDGUARD,
    [4] = GConst.EquipConst.PART_TYPE.BELT,
}
-- 升级
local EFFECT_UP_GRADE = {
    "assets/prefabs/effects/ui/vfx_ui_equip_up_b01.prefab",
    "assets/prefabs/effects/ui/vfx_ui_equip_up_b02.prefab",
    "assets/prefabs/effects/ui/vfx_ui_equip_up_b03.prefab",
}

function ArmorInfoComp:init()
    local uiMap = self:getUIMap()

    self.txAttr = uiMap["armor_info.attr.tx_attr"]
    self.txDesc = uiMap["armor_info.tx_desc"]
    self.btnUp = uiMap["armor_info.upgrade.btn_up"]
    self.txUp = uiMap["armor_info.upgrade.btn_up.tx_desc"]
    self.txNum = uiMap["armor_info.upgrade.btn_up.tx_num"]
    self.btnAttr = uiMap["armor_info.attr"]
    self.imgCurBg = uiMap["armor_info.current.cur_armor.bg"]
    self.rootCurEffect = uiMap["armor_info.current.cur_armor.root_effect"]
    self.txCurName = uiMap["armor_info.current.cur_armor.name.tx_name"]
    self.imgCurIcon = uiMap["armor_info.current.cur_armor.img_icon"]
    self.txCurLevel = uiMap["armor_info.current.cur_armor.tx_num"]
    self.imgNextBg = uiMap["armor_info.current.next_armor.bg"]
    self.txNextName = uiMap["armor_info.current.next_armor.name.tx_name"]
    self.imgNextIcon = uiMap["armor_info.current.next_armor.img_icon"]
    self.txNextLevel = uiMap["armor_info.current.next_armor.tx_num"]
    self.attr = {}
    for i = 1, 2 do
        self.attr[i] = uiMap["armor_info.attr_" .. i]
    end
    self.armor = {}
    for i = 1, 4 do
        self.armor[i] = uiMap["armor_info.other.armor_" .. i]
        self.armor[i]:addClickListener(function()
            self:onSelectIdx(i)
        end)
    end

    self.txAttr:setText(I18N:getGlobalText(I18N.GlobalConst.EQUIP_DESC_6))
    self.txDesc:setText(I18N:getGlobalText(I18N.GlobalConst.EQUIP_DESC_16))
    self.txUp:setText(I18N:getGlobalText(I18N.GlobalConst.EQUIP_DESC_3))

    DataManager.ShopData:checkPopGift(PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT)

    self.btnUp:addClickListener(function()
        ModuleManager.EquipManager:reqUpgrade(self.heroEntity:getCfgId(), self.selectPart)
    end)
    self.btnAttr:addClickListener(function()
        ModuleManager.TipsManager:showDescTips(DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), self.selectPart):getAttrDesc(), self.btnAttr)
    end)
    self:bind(DataManager.BagData.ItemData, "dirty", function()
        self:refresh()
    end)
end

function ArmorInfoComp:setParentUI(ui)
    self.uiRoot = ui
end

function ArmorInfoComp:setHeroData(heroEntity)
    self.heroEntity = heroEntity
    self.selectPart = self.selectPart or GConst.EquipConst.PART_TYPE.HAT
end

function ArmorInfoComp:refresh()
    self:onSelectIdx(self:getIndexByPart(self.selectPart))
end

function ArmorInfoComp:onSelectIdx(index)
    self.selectPart = ARMOR_PART_INDEX[index]
    self:bind(DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), self.selectPart), "isDirty", function()
        self:refresh()
    end)

    self:refreshSelectArmor()

    for index, value in ipairs(self.armor) do
        self:refreshPart(index)
    end
end

function ArmorInfoComp:refreshSelectArmor()
    -- current
    local armorEntity = DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), self.selectPart)
    self.txCurName:setText(armorEntity:getName())
    self.imgCurBg:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, "frame_" .. armorEntity:getStage() + 1)
    self.imgCurIcon:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, tostring(armorEntity:getIconId()), function()
        self.imgCurIcon:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_IMAGE):SetNativeSize()
    end)
    self.txCurLevel:setText("+".. armorEntity:getLevel())

    -- next
    local armorNextEntity = armorEntity:getNextLevelEntity()
    self.txNextName:setText(armorNextEntity:getName())
    self.imgNextBg:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, "frame_" .. armorNextEntity:getStage() + 1)
    self.imgNextIcon:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, tostring(armorNextEntity:getIconId()), function()
        self.imgNextIcon:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_IMAGE):SetNativeSize()
    end)
    self.txNextLevel:setText("+".. armorNextEntity:getLevel())

    -- 基础属性
    local curAtk = armorEntity:getAttack()
    local curNormalHurt = armorEntity:getNormalHurt()
    local curSkillHurt = armorEntity:getSkillHurt()
    local curHp = armorEntity:getHp()
    local diffBaseAtk = (armorNextEntity:getBaseAttack() - armorEntity:getBaseAttack()) // DEFAULT_FACTOR
    local diffBaseNormalHurt = (armorNextEntity:getNormalHurt() - armorEntity:getNormalHurt()) // DEFAULT_FACTOR
    local diffBaseSkillHurt = (armorNextEntity:getSkillHurt() - armorEntity:getSkillHurt()) // DEFAULT_FACTOR
    local diffBaseHp = (armorNextEntity:getBaseHp() - armorEntity:getBaseHp()) // DEFAULT_FACTOR
    local showAttrType = {}
    for index, obj in ipairs(self.attr) do
        local map = obj:genAllChildren()
        local imgIcon = map["img_icon"]
        local txTitle = map["tx_title"]
        local txNum = map["tx_num"]
        obj:setVisible(true)

        if not table.containValue(showAttrType, GConst.MATCH_ATTACK_NAME[self.heroEntity:getMatchType()]) and (curAtk > 0 or diffBaseAtk > 0) then
            table.insert(showAttrType, GConst.MATCH_ATTACK_NAME[self.heroEntity:getMatchType()])
            imgIcon:setSprite(GConst.ATLAS_PATH.COMMON, "common_dec_5")
            txTitle:setText("<color=#FCB501>"..I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_3).."</color>")
            local numStr = curAtk // DEFAULT_FACTOR
            if diffBaseAtk > 0 then
                numStr = numStr .. "<color=#A2FF29>+" .. diffBaseAtk .. "</color>"
            end
            txNum:setText(numStr)
        elseif not table.containValue(showAttrType, GConst.MATCH_NORMAL_HURT_NAME[self.heroEntity:getMatchType()]) and (curNormalHurt > 0 or diffBaseNormalHurt > 0) then
            table.insert(showAttrType, GConst.MATCH_NORMAL_HURT_NAME[self.heroEntity:getMatchType()])
            imgIcon:setSprite(GConst.ATLAS_PATH.COMMON, "common_dec_20")
            txTitle:setText("<color=#4CCFFA>"..I18N:getGlobalText(I18N.GlobalConst.ATTR_NORMAL_HURT).."</color>")
            local numStr = curNormalHurt // DEFAULT_FACTOR
            if diffBaseNormalHurt > 0 then
                numStr = numStr .. "<color=#A2FF29>+" .. diffBaseNormalHurt .. "</color>"
            end
            txNum:setText(numStr)
        elseif not table.containValue(showAttrType, GConst.MATCH_SKILL_HURT_NAME[self.heroEntity:getMatchType()]) and (curSkillHurt > 0 or diffBaseSkillHurt > 0) then
            table.insert(showAttrType, GConst.MATCH_SKILL_HURT_NAME[self.heroEntity:getMatchType()])
            imgIcon:setSprite(GConst.ATLAS_PATH.COMMON, "common_dec_21")
            txTitle:setText("<color=#EC80FF>"..I18N:getGlobalText(I18N.GlobalConst.ATTR_SKILL_HURT).."</color>")
            local numStr = curSkillHurt // DEFAULT_FACTOR
            if diffBaseSkillHurt > 0 then
                numStr = numStr .. "<color=#A2FF29>+" .. diffBaseSkillHurt .. "</color>"
            end
            txNum:setText(numStr)
        elseif not table.containValue(showAttrType, GConst.MATCH_HP_NAME[self.heroEntity:getMatchType()]) and (curHp > 0 or diffBaseHp > 0) then
            table.insert(showAttrType, GConst.MATCH_HP_NAME[self.heroEntity:getMatchType()])
            imgIcon:setSprite(GConst.ATLAS_PATH.COMMON, "common_dec_4")
            txTitle:setText("<color=#FB6895>"..I18N:getGlobalText(I18N.GlobalConst.HERO_DESC_2).."</color>")
            local numStr = curHp // DEFAULT_FACTOR
            if diffBaseHp > 0 then
                numStr = numStr .. "<color=#A2FF29>+" .. diffBaseHp .. "</color>"
            end
            txNum:setText(numStr)
        else
            obj:setVisible(false)
        end
    end

    -- 消耗材料
    local cost = armorEntity:getUpgradeMaterials()
    for i = 1, 3 do
        local uiMap = self:getUIMap()
        local costNode = uiMap["armor_info.upgrade.cost.cost_" .. i]
        if cost[i] then
            costNode:setActive(true)
            local icon = uiMap["armor_info.upgrade.cost.cost_" .. i .. ".img_icon"]
            local num = uiMap["armor_info.upgrade.cost.cost_" .. i .. ".tx_num"]
            local add = uiMap["armor_info.upgrade.cost.cost_" .. i .. ".img_icon.img_add"]

            local costId = GFunc.getRewardId(cost[i])
            local costNum = GFunc.getRewardNum(cost[i])
            local haveNum = DataManager.BagData.ItemData:getItemNumById(costId)
            if haveNum < costNum then
                num:setText("<color=#FF5252>" .. haveNum .. "</color>/" .. costNum)
            else
                num:setText(haveNum .. "/" .. costNum)
            end
            local atlas, name = GFunc.getIconRes(costId)
            icon:setSprite(atlas, name, function ()
                icon:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_IMAGE):SetNativeSize()
            end)
            add:setActive(costNum - haveNum > 0)
            icon:addClickListener(function()
                ModuleManager.EquipManager:showItemGetPop(armorEntity:getHeroId(), armorEntity:getPart(), costId, costNum - haveNum < 0 and 0 or costNum - haveNum)
            end)
        else
            costNode:setActive(false)
        end
    end
    self.txNum:setText(armorEntity:getUpgradeGoldNum())

    self.btnUp:setTouchEnable(self.heroEntity:isActived())
    local canLvUp = armorEntity:canLevelUp()
    if self.heroEntity:isActived() and canLvUp then
        self.btnUp:addRedPoint(120, 50, 0.6)
        self.btnUp:setSprite(GConst.ATLAS_PATH.COMMON, BTN_ICON[1])
    else
        self.btnUp:removeRedPoint()
        self.btnUp:setSprite(GConst.ATLAS_PATH.COMMON, BTN_ICON[2])
    end
end

function ArmorInfoComp:refreshPart(index)
    local part = ARMOR_PART_INDEX[index]
    local armorObj = self.armor[index]
    -- Logger.logHighlight("index:"..index)
    -- Logger.logHighlight("part:"..part)
    if not armorObj then
        Logger.logHighlight("不存在部位："..part)
        return
    end

    local armorEntity = DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), part)
    local map = armorObj:genAllChildren()
    local imgSelect = map["img_select"]
    local imgBg = map["img_bg"]
    local imgIcon = map["img_icon"]
    local imgType = map["img_type"]
    local txLevel = map["tx_num"]

    local stage = armorEntity:getStage() + 1
    imgSelect:setActive(part == self.selectPart)
    imgSelect:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, "frame_select_" .. math.floor(stage / 2) + stage % 2)
    imgBg:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, "frame_" .. stage)
    imgIcon:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, tostring(armorEntity:getIconId()), function()
        imgIcon:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_IMAGE):SetNativeSize()
    end)
    imgType:setSprite(GConst.ATLAS_PATH.ICON_EQUIP, stage <= 1 and "frame_dec_1" or "frame_dec_2")
    txLevel:setText("+".. armorEntity:getLevel())

    if armorEntity:canLevelUp() then
        armorObj:addRedPoint(50, 50, 0.6)
    else
        armorObj:removeRedPoint()
    end
end

-- 播放部位升级动效
function ArmorInfoComp:playPartUpgradeEffect(part)
    local armorObj = self.armor[self:getIndexByPart(part)]
    if not armorObj then
        Logger.logHighlight("不存在部位："..part)
        return
    end

    local map = armorObj:genAllChildren()
    local rootEffect = map["root_effect"]
    rootEffect:removeAllChildren()
    local stage = DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), part):getStage() + 1
    EffectManager:loadUIEffectAsync(EFFECT_UP_GRADE[math.floor(stage / 2) + stage % 2], self.uiRoot, rootEffect, GConst.UI_EFFECT_ORDER.LEVEL5, function(obj)
        obj:playComplete(function()
            rootEffect:removeAllChildren()
        end)
    end)
end

function ArmorInfoComp:getIndexByPart(part)
    for i, p in ipairs(ARMOR_PART_INDEX) do
        if p == part then
            return i
        end
    end
    return nil
end

-- 播放升级动效
function ArmorInfoComp:playUpgradeEffect(part)
    AudioManager:playEffect(AudioManager.EFFECT_ID.EQUIP_ARMOR_UP)
    self:playPartUpgradeEffect(part)
    self.rootCurEffect:removeAllChildren()
    local stage = DataManager.EquipData:getEquip(self.heroEntity:getCfgId(), part):getStage() + 1
    EffectManager:loadUIEffectAsync(EFFECT_UP_GRADE[math.floor(stage / 2) + stage % 2], self.uiRoot, self.rootCurEffect, GConst.UI_EFFECT_ORDER.LEVEL5, function(obj)
        obj:playComplete(function()
            self.rootCurEffect:removeAllChildren()
        end)
    end)
end

return ArmorInfoComp