local FundLevelComp = class("FundLevelComp", LuaComponent)

local CELL = "app/ui/fund/cell/fund_level_cell"

local TAG_COMMON_TOTAL_SIZE = 640
local TAG_SIZE = 178

function FundLevelComp:onClose()
    self.curStage = nil
end

function FundLevelComp:init()
    local uiMap = self:getUIMap()
    self.banner = uiMap["fund_level_comp.bg.banner"]
    self.txTitle = uiMap["fund_level_comp.top.tx_title"]
    self.bg = uiMap["fund_level_comp.top.bg"]
    self.txDesc = uiMap["fund_level_comp.top.bg.desc_1"]
    self.txDesc2 = uiMap["fund_level_comp.top.bg.desc_2"]
    self.btnHelp = uiMap["fund_level_comp.top.tx_title.btn_help"]
    self.scrollrect = uiMap["fund_level_comp.scrollrect"]
    self.txLevel = uiMap["fund_level_comp.scrollrect.title.tx_level"]
    self.txCommon = uiMap["fund_level_comp.scrollrect.title.tx_common"]
    self.txPro = uiMap["fund_level_comp.scrollrect.title.tx_pro"]
    self.btnGet = uiMap["fund_level_comp.btns.btn_get"]
    self.txGet = uiMap["fund_level_comp.btns.btn_get.tx_desc"]
    self.btnBuy = uiMap["fund_level_comp.btns.btn_buy"]
    self.txCost = uiMap["fund_level_comp.btns.btn_buy.tx_cost"]
    self.tagsNode = uiMap["fund_level_comp.tags"]
    self.tagsViewport = uiMap["fund_level_comp.tags.viewport"]
    self.tagsContent = uiMap["fund_level_comp.tags.viewport.content"]
    self.tags = {}
    self.tagImgs = {}
    self.tagDescs = {}
    for i = 1, 20 do
        table.insert(self.tags, uiMap["fund_level_comp.tags.viewport.content.tag_" .. i])
        table.insert(self.tagImgs, uiMap["fund_level_comp.tags.viewport.content.tag_" .. i .. ".img"])
        table.insert(self.tagDescs, uiMap["fund_level_comp.tags.viewport.content.tag_" .. i .. ".img.tx_desc"])
    end
    self.imgProgress = uiMap["fund_level_comp.top.img_prog"]
    self.txProg = uiMap["fund_level_comp.top.img_prog.tx_prog"]
    self.rewardImg = uiMap["fund_level_comp.top.bg.img_reward"]
    self.txGetAll = uiMap["fund_level_comp.top.bg.tx_get_all"]

    self.txDesc:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_DESC_4))
    self.txDesc2:setText(I18N:getGlobalText(I18N.GlobalConst.FORCE_DESC_29))
    self.txLevel:setText(I18N:getGlobalText(I18N.GlobalConst.EQUIP_DESC_31))
    self.txCommon:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_DESC_5))
    self.txPro:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_DESC_6))
    self.txGet:setText(I18N:getGlobalText(I18N.GlobalConst.BTN_CLAIM_ALL))

    self.btnBuy:addClickListener(function()
        local giftId = DataManager.FundLevelData:getProActId(self.curStage)
        ModuleManager.FundLevelManager:onBuyLevelGift(giftId)
    end)
    self.btnGet:addClickListener(function()
        ModuleManager.FundLevelManager:getReward(self.curStage)
    end)
    self.btnHelp:addClickListener(function()
        ModuleManager.TipsManager:showDescTips(I18N:getGlobalText(I18N.GlobalConst.FUND_DESC_2), self.btnHelp)
    end)
    self:bind(DataManager.FundLevelData, "isDirty", function()
        if not DataManager.FundLevelData:getIsOpen() then
            return
        end
        if not DataManager.FundLevelData:isStageUnlock(self.curStage) then
            self.curStage = DataManager.FundLevelData:getCurStage()
        end
        if self.curStage == nil then
            return
        end
        if not DataManager.FundLevelData:canGetRewards(self.curStage) then
            local claimedStage = DataManager.FundLevelData:getMinUnclaimedStage()
            if claimedStage ~= nil then
                self.curStage = claimedStage
            end
        end
		self:refresh(true)
	end)
end

function FundLevelComp:refresh(isAuto)
    if self.curStage == nil then
        self.curStage = DataManager.FundLevelData:getMinUnclaimedStage() or DataManager.FundLevelData:getMaxUnclaimedStage()
        isAuto = true
    end

    self:updateData(self.curStage)
    self:refreshStageTags()
    if isAuto then
        local stageList = DataManager.FundLevelData:getUnlockStageList()
        local index
        for k, v in pairs(stageList) do
            if self.curStage == v then
                index = k
            end
        end
        if index then
            self.tagsContent:setAnchoredPositionX(-self.tags[index]:getAnchoredPositionX())
        end
    end
    if not DataManager.FundLevelData:getProBought(self.curStage) then
		local giftId = DataManager.FundLevelData:getProActId(self.curStage)
		local cfg = ConfigManager:getConfig("act_gift")[giftId]
        self.txCost:setText(GFunc.getFormatPrice(cfg.recharge_id))
        self.txProg:setText(cfg.value .. "%")
		self.btnBuy:setActive(true)
	else
		self.btnBuy:setActive(false)
	end
    self.btnGet:setActive(DataManager.FundLevelData:canGetRewards(self.curStage))

    if self.curStage == 1 then
        self.banner:setTexture("assets/arts/textures/background/fund/fund_banner_2.png")
        self.txTitle:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_DESC_1))
    else
        self.banner:setTexture("assets/arts/textures/background/fund/fund_banner_2.png")
        self.txTitle:setText(I18N:getGlobalText(I18N.GlobalConst["FUND_TAG_DESC_" .. self.curStage]))
    end
    local w = self.txTitle:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT_MESH_PRO).preferredWidth
    if w > 600 then
        self.txTitle:setSizeDeltaX(610)
    else
        self.txTitle:setSizeDeltaX(w + 10)
    end

    self.maxIndex = #self.cfgList
    self.minIndex = DataManager.FundLevelData:getMinUnclaimedRewardIndex(self.curStage)
    if self.scrollRect == nil then
        self.scrollRect = self.scrollrect:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
        self.scrollRect:addInitCallback(function()
            return CELL
        end)
        self.scrollRect:addRefreshCallback(function(index, cell)
            cell:refresh(self.cfgList[index], index == self.maxIndex)
        end)
    end
    if self.scrollRect:getTotalCount() == nil or self.scrollRect:getTotalCount() <= 0 then
		self.scrollRect:refillCells(self.maxIndex)
    elseif self.scrollRect:getTotalCount() ~= self.maxIndex then
		self.scrollRect:clearCells()
		self.scrollRect:refillCells(self.maxIndex)
	else
		self.scrollRect:updateAllCell()
	end
    self.scrollRect:moveToIndex(self.minIndex)

    if self.curStage then
        BIReportV2:postOperation(BIReportV2.OPERATION_UI_NAME.FUND_CHAPTER .. self.curStage)
    end
    local count = 0
    for i,id in ipairs(self.cfgList) do
        local cfgFree = DataManager.FundLevelData:getFreeRewards(id)
        local cfgPro = DataManager.FundLevelData:getProRewards(id)
        if cfgFree then
            for _,v in ipairs(cfgFree) do
                count = count + v.num
            end
        end
        if cfgPro then
            for _,v in ipairs(cfgPro) do
                count = count + v.num
            end
        end
    end
    self.txGetAll:setText(count)
    GFunc.centerImgAndTx(self.rewardImg, self.txGetAll)
end

function FundLevelComp:updateData(stage)
    stage = stage or DataManager.FundLevelData:getCurStage()
	if DataManager.FundLevelData:getIsOpen(stage) then
		self.cfgList = DataManager.FundLevelData:getListByStage(stage)
    else
        self.cfgList = {}
	end
end

function FundLevelComp:onClickStageTag(stage)
    self.curStage = stage
    self:refresh()
end

function FundLevelComp:refreshStageTags()
    local stageList = DataManager.FundLevelData:getUnlockStageList()
    if #stageList <= 1 then
        self.tagsNode:setActive(false)
        return
    end
    self.tagsNode:setActive(true)
    local totalWidth = #stageList * TAG_SIZE + (#stageList - 1) * 5 + 20
    self.tagsContent:setSizeDeltaX(totalWidth)
    self.tagsViewport:setSizeDeltaX(totalWidth < TAG_COMMON_TOTAL_SIZE and totalWidth or TAG_COMMON_TOTAL_SIZE)

    for i, tag in ipairs(self.tags) do
        local stage = stageList[i]
        if stage then
            tag:setActive(true)
            local isSelect = self.curStage == stage
            self.tagImgs[i]:setSprite(GConst.ATLAS_PATH.COMMON, isSelect and "common_menu_3" or "common_menu_4")
            self.tagImgs[i]:setAnchoredPositionY(isSelect and 5 or 0)
            self.tagDescs[i]:setText(I18N:getGlobalText(I18N.GlobalConst["FUND_TAG_DESC_" .. stage]))

            if DataManager.FundLevelData:canGetRewards(stage) then
                tag:addRedPoint(74, 22, 0.9)
            else
                tag:removeRedPoint()
            end

            tag:addClickListener(function()
                if isSelect then
                    return
                end
                self:onClickStageTag(stage)
            end)
        else
            tag:setActive(false)
        end
    end
end

return FundLevelComp