local GMConst = require "app/module/gm/gm_const"
local GMToolUI = class("GMToolUI",BaseUI)

function GMToolUI:ctor()
end

function GMToolUI:getPrefabPath()
	return "assets/prefabs/ui/gm/gm_tool_ui.prefab"
end

function GMToolUI:onLoadRootComplete()
	self.sid = self:scheduleGlobal(function()
		self:updateTime()
	end, 1)
    self:updateTime()
end

function GMToolUI:onRefresh()
	self.uiMap = self.root:genAllChildren()

	local titleTx = self.uiMap['gm_tool_ui.title']
	local okBtn = self.uiMap['gm_tool_ui.ok_btn']
	local okBtnText = self.uiMap['gm_tool_ui.ok_btn.text']
	local inputField = self.uiMap['gm_tool_ui.InputField']
	local scrollView = self.uiMap['gm_tool_ui.ScrollView']
	local textTip = self.uiMap['gm_tool_ui.text_tip']
	local speedUpBtn = self.uiMap["gm_tool_ui.speed_up_btn"]
	local speedUpBtn = self.uiMap["gm_tool_ui.speed_up_btn"]
	local skipTutorialTx = self.uiMap["gm_tool_ui.skip_tutoria.text"]
	local skipTutorialBtn = self.uiMap["gm_tool_ui.skip_tutoria"]
	local skipTutorialCheck = self.uiMap["gm_tool_ui.skip_tutoria.check"]

	self.uiMap['gm_tool_ui.close_btn']:addClickListener(function() self:closeUI() end)
	self.scrollRect = scrollView:getLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
	self.scrollRect:clearCells()
	self.scrollRect:setFadeArgs(0, 0.3)
	self.scrollRect:addInitCallback(function()
		return "app/ui/gm/cell/dev_tool_cell"
	end)
	self.scrollRect:addRefreshCallback(function(index, cell)
		self:initScrollRectCell(index, cell)
	end)
	self.scrollRect:refillCells(#GMConst.GM_INFO)

	self.textTip = textTip
	self.inputField = inputField
	titleTx:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT).text = "GM面板"
	okBtnText:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT).text = "确定"
	skipTutorialTx:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT).text = "跳过引导"

	okBtn:addClickListener(function()
	    local gmCommand = self.inputField:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_INPUT_FIELD).text
	    self:sendMsg(gmCommand)
	    self.inputField:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_INPUT_FIELD).text = ""
	end)

	self.uiMap["gm_tool_ui.exit_btn.text"]:setText("退到登录界面", self.uiMap["gm_tool_ui.exit_btn.text"]:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT))
	self.uiMap["gm_tool_ui.exit_btn"]:addClickListener(function()
		ModuleManager.LoginManager:goToLoginScene()
	end)

	speedUpBtn:addClickListener(function()
		local timeScale = CS.UnityEngine.Time.timeScale
		if timeScale == 1 then
			timeScale = 2
		elseif timeScale == 2 then
			timeScale = 5
		elseif timeScale == 5 then
			timeScale = 10
		else
			timeScale = 1
		end
		CS.UnityEngine.Time.timeScale = timeScale
	end)

	self.uiMap["gm_tool_ui.fps_btn"]:addClickListener(function()
		local comp = UIManager.uiRoot:getComponent(typeof(CS.BF.ShowFPS))
		if comp == nil then
			comp = UIManager.uiRoot:addComponent(typeof(CS.BF.ShowFPS))
		else
			comp.enabled = not comp.enabled
		end
	end)

	skipTutorialCheck:setVisible(ModuleManager.DevToolManager:getSkip() == true)
	skipTutorialBtn:addClickListener(function()
		ModuleManager.DevToolManager:setSkip(not ModuleManager.DevToolManager:getSkip())
		skipTutorialCheck:setVisible(ModuleManager.DevToolManager:getSkip() == true)
	end)
end

function GMToolUI:initScrollRectCell(index, cell)
	local data = GMConst.GM_INFO[index]
	cell:addClickListener(function ()
		self.textTip:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_TEXT).text = data.desc
		self.inputField:getComponent(GConst.TYPEOF_UNITY_CLASS.UI_INPUT_FIELD).text = string.format("%s ", data.type)
	end)
	cell:refresh(data)
end

function GMToolUI:sendMsg(gmCommand)
	if gmCommand == "" then
		GFunc.showToast("GM命令不能为空")
	else
		local args = {}
		args.args = string.split(gmCommand, " ")
		if args.args[1] == "add_buff" then -- 特殊处理
			if not ModuleManager.BattleManager:isInBattle() then
				Logger.logHighlight("不在战斗中")
				return
			end
			self:dealAddBuffGm(args)
		elseif args.args[1] == "set_seal_element" then -- 特殊处理
			if not ModuleManager.BattleManager:isInBattle() then
				Logger.logHighlight("不在战斗中")
				return
			end
			self:dealSetSealElementGm(args.args)
		elseif args.args[1] == "add_monster_skill" then -- 特殊处理
			if not ModuleManager.BattleManager:isInBattle() then
				Logger.logHighlight("不在战斗中")
				return
			end
			self:addMonsterSkill(args.args)
		elseif args.args[1] == "set_board_info" then -- 特殊处理
			ModuleManager.DevToolManager.set_board_info = {
				config = args.args[2],
				idx = tonumber(args.args[3]) or 0,
				isMystery = args.args[4] ~= nil
			}
			self:closeUI()
		elseif args.args[1] == "add_skill" then -- 特殊处理
			if not ModuleManager.BattleManager:isInBattle() then
				Logger.logHighlight("不在战斗中")
				return
			end
			local posId = tonumber(args.args[2])
			local skillElement = tonumber(args.args[3])
			local side = GConst.BattleConst.SIDE_ATK
			if args.args[4] then
				side = tonumber(args.args[4])
			end
			local controller = ModuleManager.BattleManager.battleController
			local battleData = controller.battleData
			local entity = battleData:getSkillEntityByElement(skillElement, side)
			if entity then
				battleData:getGridEnties()[posId]:setSkilId(entity:getSkillId(), false, side)
			end
			self:closeUI()
		elseif args.args[1] == "check_skill_sound" then
			self:checkSkillSoundExist()
			self:closeUI()
		elseif args.args[1] == "time" then -- 特殊处理
			local args1 = {}
			args1.args = {}
			args1.args[1] = args.args[1]
			args1.args[2] = args.args[2] .. " " .. args.args[3]
			ModuleManager.DevToolManager:dealGM(args1)
		elseif args.args[1] == "set_cur_chapter" then
			DataManager.ChapterData:setChapterId(tonumber(args.args[2]))
			DataManager.ChapterData:setDirty()
			self:closeUI()
		else
			args.args = {gmCommand}
			ModuleManager.DevToolManager:dealGM(args)
		end
	end
end

function GMToolUI:updateTime()
	local uiMap = self.root:genAllChildren()
	uiMap["gm_tool_ui.time"]:setText(Time:formatTimeYMDHMS(Time:getServerTime()))
end

function GMToolUI:dealAddBuffGm(args)
	local battleController = ModuleManager.BattleManager.battleController
	local effect = {
		["type"]=args.args[2],
		["num"]=tonumber(args.args[3]),
		["ratio"]=10000,
		["round"]=tonumber(args.args[4])
	}
	local targetUnit = battleController.atkTeam:getMainUnit()
	if tonumber(args.args[5]) == GConst.BattleConst.SIDE_DEF then
		targetUnit = battleController.defTeam:getMainUnit()
	end

	local BattleBuffEntity = require "app/userdata/battle/skill/battle_buff_entity"
	local buffEntity = BattleBuffEntity:create()
	buffEntity:init(effect, targetUnit.unitEntity)
	buffEntity:setTargetSide(targetUnit)
	targetUnit:takeEffect(buffEntity, targetUnit)
	self:closeUI()
end

function GMToolUI:dealSetSealElementGm(args)
	local battleController = ModuleManager.BattleManager.battleController
	battleController.sealElementType = {}
	local index = 2
	while true do
		if not args[index] then
			break
		end
		local elementType = tonumber(args[index])
		if not elementType then
			break
		end
		battleController.sealElementType[elementType] = true
		index = index + 1
	end
	self:closeUI()
end

function GMToolUI:addMonsterSkill(args)
	local battleController = ModuleManager.BattleManager.battleController
	battleController.defTeam:getMainUnit():addSkill(tonumber(args[2]))
	self:closeUI()
end

function GMToolUI:checkSkillSoundExist()
	local skillCfg = ConfigManager:getConfig("skill")
	local errorMap = {}
	for skillId, info in pairs(skillCfg) do
		if info.sound_hit then
			for _, id in ipairs(info.sound_hit) do
				if id > 0 and not io.open(string.format("assets/arts/sounds/sfx/battle/%s.wav", id), 'r') then
					if not errorMap[skillId]  then
						errorMap[skillId] = {}
					end
					table.insert(errorMap[skillId], id)
				end
			end
		end
	end
	Logger.logHighlight("音效遍历完成")
	Logger.printTable(errorMap)
end

return GMToolUI
