local PlayerManager = class("PlayerManager", BaseModule)

function PlayerManager:init()
    self:addEventListener(EventManager.CUSTOM_EVENT.GETED_REWARD_SUCCESS, function(rewards)
        self:checkUnlockAvatar(rewards)
        self:checkUnlockFrame(rewards)
    end)
end

function PlayerManager:showPlayerUpUI(currLv, rewards)
	local params = {
		fromLevel = currLv,
		rewards = rewards,
	}
    UIManager:showUI("app/ui/player/player_level_up_ui", params)
end

function PlayerManager:levelUp()
	self:sendMessage(ProtoMsgType.FromMsgEnum.LevelUpReq, {}, {}, self.onLevelUpFinish, BIReport.ITEM_GET_TYPE.PLAYER_LV_UP)
end

function PlayerManager:onLevelUpFinish(result)
	if result.err_code == GConst.ERROR_STR.SUCCESS then
		local currLv = DataManager.PlayerData:getLv()
		local diffLv = result.level - currLv
		DataManager.PlayerData:setLv(result.level, result.exp)
		if diffLv > 0 then
			self:showPlayerUpUI(currLv, result.rewards)
			ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_PLAYER_LV_REACH, diffLv)
			DataManager:tryOpenModules()
			BIReport:postPlayerLvUp(currLv, result.level)
		end
	end
end

-- 修改昵称
function PlayerManager:reqChangeNickname(changeName)
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChangeNameReq, {name = changeName}, {}, self.respChangeNickname, BIReport.ITEM_GET_TYPE.CHANGE_NAME)
end

function PlayerManager:respChangeNickname(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
		DataManager.PlayerData:setNickname(result.reqData.name)
		EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.RENAME_SUCCESS)
	elseif result.err_code == GConst.ERROR_STR.NAME_HAS_EXISTED then
		GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.CANNOT_RENAME_DESC_4))
    end
end

-- 修改头像
function PlayerManager:reqChangeAvatar(changeId)
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChangeAvatarReq, {id = changeId}, {}, self.respChangeAvatar, BIReport.ITEM_GET_TYPE.CHANGE_AVATAR)
end

function PlayerManager:respChangeAvatar(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
		DataManager.PlayerData:setAvatarUsing(result.reqData.id)
    end
end

-- 修改头像框
function PlayerManager:reqChangeFrame(changeId)
    self:sendMessage(ProtoMsgType.FromMsgEnum.ChangeAvatarFrameReq, {id = changeId}, {}, self.respChangeFrame, BIReport.ITEM_GET_TYPE.CHANGE_FRAME)
end

function PlayerManager:respChangeFrame(result)
    if result.err_code == GConst.ERROR_STR.SUCCESS then
		DataManager.PlayerData:setFrameUsing(result.reqData.id)
    end
end

-- 检查解锁头像
function PlayerManager:checkUnlockAvatar(checkData)
	local unlockIds = DataManager.PlayerData:getCanUnlockAvatarIds(checkData)
	table.foreach(unlockIds, function (idx, id)
		DataManager.PlayerData:setAvatarUnlock(id)
	end)
end

-- 检查解锁头像框
function PlayerManager:checkUnlockFrame(checkData)
	local unlockIds = DataManager.PlayerData:getCanUnlockFrameIds(checkData)
	table.foreach(unlockIds, function (idx, id)
		DataManager.PlayerData:setFrameUnlock(id)
	end)
end

return PlayerManager