local FundChapterComp = class("FundChapterComp", LuaComponent)

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

local TAG_COMMON_TOTAL_SIZE = 640
local TAG_SIZE = 178

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

function FundChapterComp:init()
    local uiMap = self:getUIMap()
    self.banner = uiMap["fund_chapter_comp.bg.banner"]
    self.txTitle = uiMap["fund_chapter_comp.top.tx_title"]
    self.bg = uiMap["fund_chapter_comp.top.bg"]
    self.txDesc = uiMap["fund_chapter_comp.top.bg.desc_1"]
    self.txDesc2 = uiMap["fund_chapter_comp.top.bg.desc_2"]
    self.btnHelp = uiMap["fund_chapter_comp.top.tx_title.btn_help"]
    self.scrollrect = uiMap["fund_chapter_comp.scrollrect"]
    self.txLevel = uiMap["fund_chapter_comp.scrollrect.title.tx_level"]
    self.txCommon = uiMap["fund_chapter_comp.scrollrect.title.tx_common"]
    self.txPro = uiMap["fund_chapter_comp.scrollrect.title.tx_pro"]
    self.btnGet = uiMap["fund_chapter_comp.btns.btn_get"]
    self.txGet = uiMap["fund_chapter_comp.btns.btn_get.tx_desc"]
    self.btnBuy = uiMap["fund_chapter_comp.btns.btn_buy"]
    self.txCost = uiMap["fund_chapter_comp.btns.btn_buy.tx_cost"]
    self.tagsNode = uiMap["fund_chapter_comp.tags"]
    self.tagsViewport = uiMap["fund_chapter_comp.tags.viewport"]
    self.tagsContent = uiMap["fund_chapter_comp.tags.viewport.content"]
    self.tags = {}
    self.tagImgs = {}
    self.tagDescs = {}
    self.txTitle:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_CHAPTER_DESC_1))
    self.txDesc:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_CHAPTER_DESC_4))
    -- self.txDesc2:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_CHAPTER_DESC_4))
    self.txLevel:setText(I18N:getGlobalText(I18N.GlobalConst.CHAPTER_TEAM_DESC_2))
    self.txCommon:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_CHAPTER_DESC_5))
    self.txPro:setText(I18N:getGlobalText(I18N.GlobalConst.FUND_CHAPTER_DESC_6))
    self.txGet:setText(I18N:getGlobalText(I18N.GlobalConst.ONE_KEY_GET_DESC))
    for i = 1, 20 do
        table.insert(self.tags, uiMap["fund_chapter_comp.tags.viewport.content.tag_" .. i])
        table.insert(self.tagImgs, uiMap["fund_chapter_comp.tags.viewport.content.tag_" .. i .. ".img"])
        table.insert(self.tagDescs, uiMap["fund_chapter_comp.tags.viewport.content.tag_" .. i .. ".img.tx_desc"])
    end
    self.rewardImg = uiMap["fund_chapter_comp.top.bg.icon"]
    self.txGetAll = uiMap["fund_chapter_comp.top.bg.tx_get_all"]

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

function FundChapterComp:refresh(isAuto)
    if self.curStage == nil then
        self.curStage = DataManager.ChapterFundData:getMinUnclaimedStage() or DataManager.ChapterFundData:getMaxUnclaimedStage()
        isAuto = true
    end
    
    self:updateData(self.curStage)
    self:refreshStageTags()
    if isAuto then
        local stageList = DataManager.ChapterFundData: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.ChapterFundData:getProBought(self.curStage) then
		local giftId = DataManager.ChapterFundData:getProGiftId(self.curStage)
		local cfg = ConfigManager:getConfig("act_gift")[giftId]
        self.txCost:setText(GFunc.getFormatPrice(cfg.recharge_id))
		self.btnBuy:setActive(true)
	else
		self.btnBuy:setActive(false)
	end
    self.btnGet:setActive(DataManager.ChapterFundData:canGetRewards(self.curStage))

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

    self.maxIndex = #self.cfgList
    self.minIndex = DataManager.ChapterFundData: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_LEVEL .. self.curStage)
    end

    local count = 0
    for i, id in ipairs(self.cfgList) do
        local cfgFree = DataManager.ChapterFundData:getFreeRewards(id)
        local cfgPro = DataManager.ChapterFundData: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 FundChapterComp:updateData(stage)
    stage = stage or DataManager.ChapterFundData:getCurStage()
	if DataManager.ChapterFundData:getIsOpen(stage) then
		self.cfgList = DataManager.ChapterFundData:getListByStage(stage)
    else
        self.cfgList = {}
	end
end

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

function FundChapterComp:refreshStageTags()
    local stageList = DataManager.ChapterFundData: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_CHAPTER_TAG_DESC_" .. stage]))

            if DataManager.ChapterFundData: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 FundChapterComp