local SevenDayUI = class("SevenDayUI", BaseUI)

local TASK_CELL = "app/ui/activity/seven_day/cell/task_cell"

function SevenDayUI:getPrefabPath()
    return "assets/prefabs/ui/activity/seven_day/seven_day_ui.prefab"
end

function SevenDayUI:getCurrencyParams()
    if self.currencyParams == nil then
        self.currencyParams = {
            itemIds = {
				GConst.ItemConst.ITEM_ID_GOLD,
				GConst.ItemConst.ITEM_ID_GEM,
				GConst.ItemConst.ITEM_ID_VIT,
			},
			showType = GConst.CURRENCY_TYPE.HORIZONTAL
        }
    end
 	return self.currencyParams
end

function SevenDayUI:onClose()
    if self.finalAutoRotateTween then
        self.finalAutoRotateTween:Kill()
        self.finalAutoRotateTween = nil
    end
end

function SevenDayUI:ctor()
    self.day = DataManager.SevenDayData:getActDay()
    if self.day < 0 then
        self.day = 1
    elseif self.day > 7 then
        self.day = 7
    end
end

function SevenDayUI:onLoadRootComplete()
    self.uiMap = self.root:genAllChildren()
    self:_display()
    self:_bind()

    self:scheduleGlobal(function()
		self:updateTime()
	end, 1)
    self:updateTime()
end

function SevenDayUI:_display()
    self.uiMap["seven_day_ui.title_bg.title_tx"]:setText(I18N:getGlobalText(I18N.GlobalConst.SEVEN_DAY_TITLE))
    self.uiMap["seven_day_ui.down.desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.SEVEN_DAY_DESC_1))
    self.uiMap["seven_day_ui.down.close_btn"]:addClickListener(function()
        self:closeUI()
    end)

    self.downDesc = self.uiMap["seven_day_ui.down.desc"]
    self.toHeroFundTx = self.uiMap["seven_day_ui.down.to_herofund_tx"]
    self.toHeroFundBtn = self.uiMap["seven_day_ui.down.to_herofund_btn"]
    self.toHeroFundBtnTx = self.uiMap["seven_day_ui.down.to_herofund_btn.text"]
    self.toHeroFundBtnTx:setText(I18N:getGlobalText(I18N.GlobalConst.PART_IN_DESC))
    self.toHeroFundTx:setText(I18N:getGlobalText(I18N.GlobalConst.HERO_FUND_DESCC_1))
    self.toHeroFundBtn:addClickListener(function()
        self:closeUI()
        if DataManager.HeroFundData:getIsOpen() then
            ModuleManager.HeroFundManager:showMainUI()
        end
    end)

    self:initTop()
    self:initTasks()
end

function SevenDayUI:initTop()
    self.dayTextList = {}
    self.dayLockList = {}
    self.stepObjs = {}
    for i = 1, 7 do
        self.dayLockList[i] = self.uiMap["seven_day_ui.day_bg.lock_" .. i]
        self.dayTextList[i] = self.uiMap["seven_day_ui.day_bg.day_" .. i]
        self.dayTextList[i]:setText(I18N:getGlobalText(I18N.GlobalConst.DAY_X, i))
        self.dayTextList[i]:addClickListener(function()
            if i > DataManager.SevenDayData:getActDay() then
                GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.DAY_X_UNLOCK, i))
                return
            end
            self.day = i
            self:refreshDay()
            self:refreshScrollRect()
        end)

        self.stepObjs[i] = {
            btn = self.uiMap["seven_day_ui.slider_bg.btn_" .. i],
            num = self.uiMap["seven_day_ui.slider_bg.num_" .. i],
            spine = self.uiMap["seven_day_ui.slider_bg.btn_" .. i .. ".ui_spine"],
        }
        self.stepObjs[i].btn:addClickListener(function()
            local list = DataManager.SevenDayData:getStepRewardList()
            local id = list[i]
            if id then
                if DataManager.SevenDayData:canClaimStepTask(id) then
                    self:showBoxOpenAnimation(i, id)
                else
                    local reward = DataManager.SevenDayData:getStepReward(id)
                    if id == 7 then
                        ModuleManager.TipsManager:showRewardTips(reward.id, reward.type, self.stepObjs[i].btn)
                    else
                        ModuleManager.TipsManager:showRewardsTips({reward}, nil, self.stepObjs[i].btn)
                    end
                end
            end
        end)
    end
    self.finalBoxCell = self.uiMap["seven_day_ui.slider_bg.btn_7.reward_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.REWARD_CELL)
    self.finalBoxCell:setTouchEnable(false)
    self.finalBoxLight = self.uiMap["seven_day_ui.slider_bg.light_7"]
    self.sevenDayDesc = self.uiMap["seven_day_ui.slider_bg.desc"]
    self.sevenDaySliderComp = self.uiMap["seven_day_ui.slider_bg.slider"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_SLIDER)
    self.daySelectImg = self.uiMap["seven_day_ui.day_bg.day_select"]
    self.timeTx = self.uiMap["seven_day_ui.title_bg.time"]
    self.timeIcon = self.uiMap["seven_day_ui.title_bg.time_icon"]
end

function SevenDayUI:initTasks()
    self.scrollRectComp = self.uiMap["seven_day_ui.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.scrollRectComp:addInitCallback(function()
		return TASK_CELL
	end)
	self.scrollRectComp:addRefreshCallback(function(index, cell)
		cell:refresh(self.taskList[index])
	end)
    self.scrollRectComp:clearCells()
    self.scrollRectComp:setTotalCount(0)
end

function SevenDayUI:_bind()
    self:bind(DataManager.SevenDayData, "isDirty", function()
        self:onRefresh()
    end)
end

function SevenDayUI:onRefresh()
    self:refreshDay()
    self:refreshStepInfo()
    self:refreshScrollRect()
end

function SevenDayUI:refreshDay()
    local actDay = DataManager.SevenDayData:getActDay()
    for i = 1, 7 do
        if i == self.day then
            self.daySelectImg:setAnchoredPositionX(self.dayTextList[i]:fastGetAnchoredPositionX())
        end
        if i > actDay then
            self.dayLockList[i]:setVisible(true)
            self.dayTextList[i]:removeRedPoint()
        else
            self.dayLockList[i]:setVisible(false)
            if DataManager.SevenDayData:showRedPoint(i) then
                self.dayTextList[i]:addRedPoint(40, 26, 0.5)
            else
                self.dayTextList[i]:removeRedPoint()
            end
        end
    end
end

function SevenDayUI:refreshStepInfo()
    local list = DataManager.SevenDayData:getStepRewardList()
    for index, objs in ipairs(self.stepObjs) do
        local id = list[index]
        if id then
            objs.num:setText(DataManager.SevenDayData:getStepNum(id))
            if not self.isInBoxAnimation then
                if index ~= 7 then
                    if DataManager.SevenDayData:getStepCollected(id) then -- 领过了
                        objs.spine:playAnim("idle02", true)
                    else
                        if DataManager.SevenDayData:stepOver(id) then -- 可以领
                            objs.spine:playAnim("ready", true)
                        else
                            objs.spine:playAnim("idle01", true)
                        end
                    end
                end
            end
        end
    end

    local count = DataManager.SevenDayData:getCollectedCount()
    local totalCount = DataManager.SevenDayData:getTotalCount()
    self.sevenDayDesc:setText(I18N:getGlobalText(I18N.GlobalConst.SEVEN_DAY_DESC_2, count, totalCount))
    self.sevenDaySliderComp.value = count / DataManager.SevenDayData:getStepNum(#self.stepObjs)

    local finalId = #list
    local finalReward = DataManager.SevenDayData:getStepReward(finalId)
    if finalReward then
        if DataManager.SevenDayData:getStepCollected(finalId) then
            self.finalBoxCell:refreshByConfig(finalReward, true, true)
            self.finalBoxLight:setVisible(false)
            self.stepObjs[finalId].spine:setVisible(false)
        else
            if DataManager.SevenDayData:stepOver(finalId) then -- 可以领
                self.finalBoxLight:setVisible(true)
                if self.finalAutoRotateTween == nil then
                    self.finalAutoRotateTween = self.finalBoxLight:getTransform():DOLocalRotate(BF.Vector3(0, 0, -360), 3, CS.DG.Tweening.RotateMode.FastBeyond360):SetEase(CS.DG.Tweening.Ease.Linear)
	                self.finalAutoRotateTween:SetLoops(-1)
                end
                self.stepObjs[finalId].spine:setVisible(true)
                self.stepObjs[finalId].spine:playAnim("ready", true)
            else
                self.finalBoxLight:setVisible(false)
                self.stepObjs[finalId].spine:setVisible(false)
            end
            self.finalBoxCell:refreshByConfig(finalReward)
        end
        self.finalBoxCell:setNumTx("x" .. finalReward.num)
    end
end

function SevenDayUI:refreshScrollRect()
    self:sortTaskList(self.day)
    if self.scrollRectComp:getTotalCount() ~= #self.taskList then -- 打开界面的时候定位到当前可领取的最低等级奖励，如果没有则定位到当前等级
		self.scrollRectComp:clearCells()
		self.scrollRectComp:refillCells(#self.taskList)
	else
		self.scrollRectComp:updateAllCell()
	end
end

function SevenDayUI:sortTaskList(day)
    self.day = day
    self.taskList = DataManager.SevenDayData:getTaskListByDay(day or 1)
    table.sort(self.taskList, function(a, b)
        local aClaimed = DataManager.SevenDayData:taskCollected(a)
        local bClaimed = DataManager.SevenDayData:taskCollected(b)
        if aClaimed == false and aClaimed == bClaimed then
            local aCan = DataManager.SevenDayData:canClaimTask(a)
            local bCan = DataManager.SevenDayData:canClaimTask(b)
            if aCan == bCan then
                return a < b
            else
                return aCan
            end
        else
            if aClaimed == bClaimed then
                return a < b
            else
                return not aClaimed
            end
        end
    end)
end

function SevenDayUI:updateTime()
    local endTime = DataManager.SevenDayData:getEndTime()
    local remainTime = endTime - Time:getServerTime()
    if remainTime >= 0 then
        self.timeTx:setText(GFunc.getTimeStr(remainTime))
        if DataManager.HeroFundData and DataManager.HeroFundData:getIsOpen() then
            self.toHeroFundTx:setVisible(true)
            self.toHeroFundBtn:setActive(true)
            self.downDesc:setVisible(false)
        else
            self.toHeroFundTx:setVisible(false)
            self.toHeroFundBtn:setActive(false)
            self.downDesc:setVisible(true)
        end
    else
        UIManager:closeUnderUI(self)
        self:closeUI()
    end
end

function SevenDayUI:showBoxOpenAnimation(index, id)
    if index == 7 then
        ModuleManager.SevenDayManager:claimStepReward(id)
        return
    end
    if self.isInBoxAnimation then
        return
    end
    self.isInBoxAnimation = true
    self:disableUITouch()
    local spine = self.stepObjs[index].spine
    local trackEntry = spine:playAnim("open", false)
    local time = spine:getAnimation(trackEntry).Duration
    self:performWithDelayGlobal(function()
        self:enableUITouch()
        self.isInBoxAnimation = false
        ModuleManager.SevenDayManager:claimStepReward(id)
    end, time)
end

return SevenDayUI