local IdleDropUI = class("IdleDropUI", BaseUI)

local IDLE_UNIT_COMPONENT = "app/ui/idle/component/idle_unit_comp"
local FIGHT_STATE_STOP = 0
local FIGHT_STATE_FIGHT = 1
local FIGHT_STATE_WAIT = 2
local REFRESH_INTERVAL_TIME = 60

function IdleDropUI:isFullScreen()
    return  false
end

function IdleDropUI:getPrefabPath()
    return "assets/prefabs/ui/idle/idle_drop_ui.prefab"
end

function IdleDropUI:ctor()
    self.itemList = {}
    self.canRefreshReward = false
    self.fightState = FIGHT_STATE_STOP
    self.fightWaitTime = 0
end

function IdleDropUI:onCover()
    if self.cdSid then
        self:pauseScheduleGlobal(self.cdSid)
    end
end

function IdleDropUI:onReshow()
    if self.cdSid then
        self:resumeScheduleGlobal(self.cdSid)
    end
    -- 检查是否升级
    if DataManager.PlayerData:getIfCanLevelUp() then
        ModuleManager.PlayerManager:levelUp()
    end
end

function IdleDropUI:onClose()
    if self.fightRoot then
        self.fightRoot:removeAllChildren()
    end
end

function IdleDropUI:onLoadRootComplete()
    local uiMap = self.root:genAllChildren()
    self.uiMap = uiMap
    uiMap["idle_drop_ui.bg.title_text"]:setText(I18N:getGlobalText(I18N.GlobalConst.IDLE_DROP_REWARD))
    uiMap["idle_drop_ui.bg.desc_tx_1"]:setText(I18N:getGlobalText(I18N.GlobalConst.IDLE_DROP_DESC_1))
    self.timeTx = uiMap["idle_drop_ui.bg.time_tx"]

    local goldPerHour = GFunc.num2Str(DataManager.IdleData:getGoldPerHour())
    local expPerHour = GFunc.num2Str(DataManager.IdleData:getExpPerHour())
    uiMap["idle_drop_ui.bg.bg_1.desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.PER_HOUR, goldPerHour))
    uiMap["idle_drop_ui.bg.bg_2.desc"]:setText(I18N:getGlobalText(I18N.GlobalConst.PER_HOUR, expPerHour))

    local idleMaxTime = DataManager.IdleData:getIdleMaxTime()
    uiMap["idle_drop_ui.bg.desc_tx_2"]:setText(I18N:getGlobalText(I18N.GlobalConst.IDLE_DROP_DESC_2, idleMaxTime // 3600))
    self.quickBtn = uiMap["idle_drop_ui.bg.quick_btn"]
    self.quickBtn:addClickListener(function()
        ModuleManager.IdleManager:showIdleQuickDropUI()
    end)
    uiMap["idle_drop_ui.bg.quick_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.IDLE_QUICK))
    self.getBtn = uiMap["idle_drop_ui.bg.get_btn"]
    self.getBtn:addClickListener(function()
        self.lastRefreshTime = Time:getServerTime()
        ModuleManager.IdleManager:getIdleRewrad()
    end)
    uiMap["idle_drop_ui.bg.get_btn.text"]:setText(I18N:getGlobalText(I18N.GlobalConst.BTN_CLAIM))
    uiMap["idle_drop_ui.bg.close_btn"]:addClickListener(function()
        self:closeUI()
    end)

    self.fightRoot = self.uiMap["idle_drop_ui.bg.fight_root"]

    self:initRewards()
    self:initSmallFight()
    self:bindData()
    self:refreshCD()
	self.cdSid = self:scheduleGlobal(function()
		self:refreshCD()
	end, 1)
    self:scheduleGlobal(function(dt)
		self:tickFight(dt)
	end, 0)
end

function IdleDropUI:initRewards()
    self.scrollRect = self.uiMap["idle_drop_ui.bg.scroll_rect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
    self.scrollRect:addInitCallback(function()
		return GConst.TYPEOF_LUA_CLASS.REWARD_CELL
	end)
	self.scrollRect:addRefreshCallback(function(index, cell)
		cell:refreshByConfig(self.itemList[index])
	end)
    self.scrollRect:clearCells()
    self.scrollRect:setTotalCount(0)
end

function IdleDropUI:initSmallFight()
    if self.atkUnit == nil then
        local stageFormation = DataManager.FormationData:getStageFormation()
        local tmpList = GFunc.getTempList()
        for k, v in pairs(stageFormation) do
            table.insert(tmpList, v)
        end
        if #tmpList <= 0 then
            GFunc.recycleTempList(tmpList)
            return
        end
        local heroId = tmpList[math.random(1, #tmpList)]
        GFunc.recycleTempList(tmpList)
        local heroInfo = ConfigManager:getConfig("hero")[heroId]
        if heroInfo == nil then
            return
        end
        SpineManager:loadHeroAsync(heroInfo.model_id, self.fightRoot, function(spineObject)
            spineObject:setDefaultMix(0)
            local atkUnitComp = spineObject:addLuaComponent(IDLE_UNIT_COMPONENT)
			atkUnitComp:prepare(1, heroInfo.model_id)
            atkUnitComp:initSkills(heroInfo.hurt_skill)
			self.atkUnit = atkUnitComp
            self:onIdleUnitInitFinish()
        end)
    end

    if self.defUnit == nil then
        local chapterId = DataManager.ChapterData:getMaxChapterId()
        if chapterId <= 0 then
            chapterId = DataManager.ChapterData:getChapterId()
        end
        local chapterInfo = ConfigManager:getConfig("chapter")[chapterId]
        if chapterInfo == nil then
            return
        end
        local tmpMap = GFunc.getTempMap()
        self.monsterList = {}
        local monsterCfg = ConfigManager:getConfig("monster")
        for k, v in ipairs(chapterInfo.monster) do
            local monsterInfo = monsterCfg[v]
            if monsterInfo ~= nil then
                if monsterInfo.is_boss == nil and tmpMap[monsterInfo.model_id] == nil then
                    tmpMap[monsterInfo.model_id] = true
                    table.insert(self.monsterList, v)
                end
            end
        end
        GFunc.recycleTempMap(tmpMap)
        if #self.monsterList <= 0 then
            return
        end
        if self.idleMonsterIndex == nil then
            self.idleMonsterIndex = math.random(1, #self.monsterList)
        else
            local temp = self.monsterList[#self.monsterList]
            self.monsterList[#self.monsterList] = self.monsterList[self.idleMonsterIndex]
            self.monsterList[self.idleMonsterIndex] = temp
            self.idleMonsterIndex = math.random(1, #self.monsterList - 1)
        end
        self.idleMonsterId = self.monsterList[self.idleMonsterIndex]
        self:getDefUnit(function(defUnitComp)
            self.defUnit = defUnitComp
            self:onIdleUnitInitFinish()
        end)
    end
end

function IdleDropUI:onIdleUnitInitFinish()
    if self.atkUnit == nil then
        return
    end
    if self.defUnit == nil then
        return
    end
    self.atkUnit:setTarget(self.defUnit)
    self.defUnit:setTarget(self.atkUnit)
    self.fightWaitTime = self.defUnit:getBornTime() + 0.2
    self.fightState = FIGHT_STATE_WAIT
    self.atkUnit:playBorn()
    self.defUnit:playBorn()
end

function IdleDropUI:bindData()
    self:bind(DataManager.IdleData, "dirty", function()
        self:onRefresh()
        self.canRefreshReward = true
        self:refreshCD()
    end)
end

function IdleDropUI:onRefresh()
    self:refreshRewards()
    self:refreshBtns()
end

function IdleDropUI:refreshRewards()
    for i = 1, #self.itemList do
        table.remove(self.itemList)
    end
    local rewards = DataManager.IdleData:getIdleRewards()
    for _, item in pairs(rewards) do
        if item.num > 0 then
            table.insert(self.itemList, item)
        end
    end
    if #self.itemList > 1 then
        -- 道具类型从低到高>道具ID从低到高>品质从高到低
        local cfg = ConfigManager:getConfig("item")
        local infoA
        local infoB
        table.sort(self.itemList, function(a, b)
            infoA = cfg[a.id]
            infoB = cfg[b.id]
            if infoA.type == infoB.type then
                if infoA.qlt == infoB.qlt then
                    return infoA.qlt > infoB.qlt
                else
                    return a.id < b.id
                end
            else
                return infoA.type < infoB.type
            end
        end)
    end
    if self.scrollRect:getTotalCount() ~= #self.itemList then -- 打开界面的时候定位到当前可领取的最低等级奖励，如果没有则定位到当前等级
		self.scrollRect:refillCells(#self.itemList)
	else
		self.scrollRect:updateAllCell()
    end
end

function IdleDropUI:refreshBtns()
    if #self.itemList > 0 then
        self.getBtn:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_green_2")
        self.getBtn:setTouchEnable(true)
    else
        self.getBtn:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_grey_2")
        self.getBtn:setTouchEnable(false)
    end
    local quickTimes = DataManager.IdleData:getQuickIdleRemainTimes()
    if quickTimes > 0 then
        self.quickBtn:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_yellow_2")
        self.quickBtn:setTouchEnable(true)
        self:addQuickBtnRedPoint()
    else
        self.quickBtn:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_grey_2")
        self.quickBtn:setTouchEnable(false)
        self:removeQuickBtnRedPoint()
    end
end

function IdleDropUI:refreshCD()
    local time = Time:getServerTime() - DataManager.IdleData:getLastDropTime()
    local idleMaxTime = DataManager.IdleData:getIdleMaxTime()
    if time >= idleMaxTime then
        if #self.itemList > 0 then
            self:addGetBtnRedPoint()
        else
            self:removeGetBtnRedPoint()
        end
        self.timeTx:setText(Time:formatNumTime(idleMaxTime))
    else
        self:removeGetBtnRedPoint()
        self.timeTx:setText(Time:formatNumTime(time))
    end
    if self.lastRefreshTime == nil then
        self.lastRefreshTime = Time:getServerTime()
    elseif Time:getServerTime() - self.lastRefreshTime > REFRESH_INTERVAL_TIME then
        if not self.canRefreshReward then
            return
        end
        self.canRefreshReward = false
        self.lastRefreshTime = Time:getServerTime()
        ModuleManager.IdleManager:getIdleShowRewrad()
    end
end

function IdleDropUI:addGetBtnRedPoint()
    if self.getBtnRedPoint == true then
        return
    end
    self.getBtnRedPoint = true
    self.getBtn:addRedPoint(121, 42, 0.8)
end

function IdleDropUI:removeGetBtnRedPoint()
    if self.getBtnRedPoint == false then
        return
    end
    self.getBtnRedPoint = false
    self.getBtn:removeRedPoint()
end

function IdleDropUI:addQuickBtnRedPoint()
    if self.quickBtnRedPoint == true then
        return
    end
    self.quickBtnRedPoint = true
    self.quickBtn:addRedPoint(121, 42, 0.8)
end

function IdleDropUI:removeQuickBtnRedPoint()
    if self.quickBtnRedPoint == false then
        return
    end
    self.quickBtnRedPoint = false
    self.quickBtn:removeRedPoint()
end

function IdleDropUI:findNextDefUnit()
    local temp = self.monsterList[#self.monsterList]
    self.monsterList[#self.monsterList] = self.monsterList[self.idleMonsterIndex]
    self.monsterList[self.idleMonsterIndex] = temp
    self.idleMonsterIndex = math.random(1, #self.monsterList - 1)
    self.idleMonsterId = self.monsterList[self.idleMonsterIndex]
    self:getDefUnit(function(defUnit)
        self:recycleDefUnit(self.defUnit)
        self.defUnit = defUnit
        self.atkUnit:setTarget(self.defUnit)
        self.defUnit:setTarget(self.atkUnit)
        self.fightWaitTime = self.defUnit:getBornTime() + 0.2
        self.fightState = FIGHT_STATE_WAIT
        self.defUnit:playBorn()
    end)
end

function IdleDropUI:getDefUnit(callback)
    if self.cacheUnit == nil then
        self.cacheUnit = {}
    end
    local monsterCfg = ConfigManager:getConfig("monster")
    local monsterInfo = monsterCfg[self.idleMonsterId]
    local defUnit = self.cacheUnit[monsterInfo.model_id]
    if defUnit then
        defUnit:setActive(true)
        return callback(defUnit)
    end
    SpineManager:loadHeroAsync(monsterInfo.model_id, self.fightRoot, function(spineObject)
        spineObject:setDefaultMix(0)
        local defUnitComp = spineObject:addLuaComponent(IDLE_UNIT_COMPONENT)
        defUnitComp:prepare(2, monsterInfo.model_id)
        callback(defUnitComp)
    end)
end

function IdleDropUI:recycleDefUnit(defUnit)
    if self.cacheUnit == nil then
        self.cacheUnit = {}
    end
    defUnit:setActive(false)
    self.cacheUnit[defUnit:getModelId()] = defUnit
end

function IdleDropUI:changeNextDefUnit()
    self.defUnit:playDead(function()
        self:findNextDefUnit()
    end)
end

function IdleDropUI:tickFight(dt)
    if self.fightState == FIGHT_STATE_STOP then
        return
    end
    self.atkUnit:tick(dt)
    self.defUnit:tick(dt)
    if self.fightState == FIGHT_STATE_FIGHT then
    elseif self.fightState == FIGHT_STATE_WAIT then
        self.fightWaitTime = self.fightWaitTime - dt
        if self.fightWaitTime < 0 then
            self.fightState = FIGHT_STATE_FIGHT
            self.atkUnit:doAttack(function()
                self:changeNextDefUnit()
            end)
        end
    end
end

return IdleDropUI