extends UIPage # 继承自我们之前创建的 UIPage

@onready var platform_page_path = $platform
@onready var gameplay_page_path: Control = $gameplay
@onready var theme_page_path: Control = $theme
@onready var strategy_page_path: Control = $strategy
@onready var notice_path: Control = $notice
@onready var dialogue_secretary: Control = $dialogue_secretary


# Part_2: 预算
@onready var budget_button: Button = $BG/Part_2/HBoxContainer/Button

# Part_3: 选择列表中的按钮
@onready var platform_select_button: Button = $"BG/Part_3/Select_List/1_right/Button"
@onready var gameplay_select_button: Button = $"BG/Part_3/Select_List/2_right/Button"
@onready var theme_select_button: Button = $"BG/Part_3/Select_List/3_right/Button"
@onready var strategy_select_button: Button = $"BG/Part_3/Select_List/4_right/Button"

# 确认按钮
@onready var confirm_button: Button = $BG/Confirm

func _ready():
	super._ready() # 调用父类的 _ready() (如果 UIPage 中有 _ready() 逻辑)
	if platform_select_button:
		platform_select_button.pressed.connect(_on_platform_select_button_pressed)
	if gameplay_select_button:
		gameplay_select_button.pressed.connect(_on_gameplay_select_button_pressed)
	if theme_select_button:
		theme_select_button.pressed.connect(_on_theme_select_button_pressed)
	if strategy_select_button:
		strategy_select_button.pressed.connect(_on_strategy_select_button_pressed)

	if confirm_button:
		confirm_button.pressed.connect(_on_confirm_button_pressed)

func _on_page_activated():
	super._on_page_activated() # 调用父类的激活逻辑
	
	if GameState.get_value("is_on_task"):
		self.show()
		go_to_child_page(dialogue_secretary)
		return
	
	print(name + " 页面已激活")
	# 当从其它页面退回到当前页面的时候，money恢复show_up起始值
	if get_main_data("original_money") > GameState.get_value("money"):
		GameState.set_value("money",get_main_data("original_money"))
	
	_calculate_and_update_budget()
	# 从 MainController 加载并显示数据
	# 例如，加载项目预算
	var current_budget = get_main_data("预算", 0) # 假设默认预算为500
	if budget_button:
		budget_button.text = str(current_budget)

	# 加载并显示已选的平台、玩法、题材、开发策略
	# 这些值可能在其他子页面选择后被设置到 shared_workflow_data 中，
	# 或者在此页面有默认值/初始值。
	var selected_platform = get_main_data("平台", "") # 默认值来自场景
	if platform_select_button:
		platform_select_button.text = selected_platform

	var selected_gameplay = get_main_data("玩法", "") # 默认值来自场景
	if gameplay_select_button:
		gameplay_select_button.text = selected_gameplay

	var selected_theme = get_main_data("题材", "") # 默认值来自场景
	if theme_select_button:
		theme_select_button.text = selected_theme
	
	var selected_strategy = get_main_data("开发策略", "") # 默认值来自场景
	if strategy_select_button:
		strategy_select_button.text = selected_strategy
	
	# 可以在这里根据条件设置按钮是否可用等
	# 例如： if some_condition: confirm_button.disabled = true

func _on_page_deactivated():
	super._on_page_deactivated() # 调用父类的停用逻辑
	print(name + " 页面已停用")
	# 可以在这里保存任何未提交的临时数据
	# 例如： set_main_data("temp_project_name", project_name_line_edit.text)


# 辅助函数：安全地从嵌套字典中获取值
# source_dict: 要从中查找的源字典
# path_keys: 一个包含路径中各个键的数组 (e.g., ["platforms", "Switch", "Cost"])
# default_value: 如果路径无效或键未找到，则返回此值
func _get_nested_value_from_dict(source_dict: Dictionary, path_keys: Array, default_value = null):
	var current_item = source_dict
	for key_part in path_keys:
		if not (current_item is Dictionary and current_item.has(key_part)):
			#printerr("Debug: Key '", key_part, "' not found or item not a dict at path: ", path_keys)
			return default_value
		current_item = current_item[key_part]
	return current_item

# 根据选择计算并更新预算的函数
func _calculate_and_update_budget() -> void:
	# 1. 从 shared_workflow_data 获取当前的选择
	var selected_platform = get_main_data("平台", "")
	var selected_gameplay = get_main_data("玩法", "")
	var selected_theme = get_main_data("题材", "")
	var selected_strategy = get_main_data("开发策略", "")

	var platform_cost: float = 0.0
	var gameplay_cost: float = 0.0
	var theme_cost: float = 0.0
	var strategy_cost_multiplier: float = 0.0 # 注意：策略的 "Cost" 是一个成本系数

	# 2. 从 GameState 获取 "task_development" 数据
	# 注意：根据提供的 GameState.gd，get_value() 仅获取顶层键。
	var task_dev_data = GameState.get_value("task_development")

	if not (task_dev_data is Dictionary):
		printerr("MainPage: 'task_development' key not found in GameState or is not a Dictionary.")
		if budget_button:
			budget_button.text = "错误: 数据缺失"
		set_main_data("预算", 0.0) # 在共享数据中将预算设为0
		return

	# 3. 获取各项成本
	# 平台成本
	if not selected_platform.is_empty():
		var cost_val = _get_nested_value_from_dict(task_dev_data, ["platforms", selected_platform, "Cost"])
		if cost_val != null:
			platform_cost = float(cost_val)
		else:
			printerr("MainPage: 平台 '", selected_platform, "' 的成本未找到或路径无效。使用 0.0。")
			platform_cost = 0.0 # 确保为 float
	
	# 玩法成本
	if not selected_gameplay.is_empty():
		var cost_val = _get_nested_value_from_dict(task_dev_data, ["gameplays", selected_gameplay, "Cost"])
		if cost_val != null:
			gameplay_cost = float(cost_val)
		else:
			printerr("MainPage: 玩法 '", selected_gameplay, "' 的成本未找到或路径无效。使用 0.0。")
			gameplay_cost = 0.0
			
	# 题材成本
	if not selected_theme.is_empty():
		var cost_val = _get_nested_value_from_dict(task_dev_data, ["themes", selected_theme, "Cost"])
		if cost_val != null:
			theme_cost = float(cost_val)
		else:
			printerr("MainPage: 题材 '", selected_theme, "' 的成本未找到或路径无效。使用 0.0。")
			theme_cost = 0.0
			
	# 开发策略成本系数
	if not selected_strategy.is_empty():
		var cost_val = _get_nested_value_from_dict(task_dev_data, ["strategies", selected_strategy, "Cost"])
		if cost_val != null:
			strategy_cost_multiplier = float(cost_val)
		else:
			printerr("MainPage: 开发策略 '", selected_strategy, "' 的成本系数未找到或路径无效。使用 0.0。")
			strategy_cost_multiplier = 0.0

	# 4. 计算预算
	# 公式: (平台成本 + 玩法成本 + 题材成本) * (1 + 策略成本系数)
	var base_cost = platform_cost + gameplay_cost + theme_cost
	var calculated_budget = base_cost * (1.0 + strategy_cost_multiplier)

	# 5. 更新预算按钮的文本和共享数据中的预算值
	if budget_button:
		budget_button.text = "¥" + str(snapped(calculated_budget, 0.01)) # 显示为货币格式，保留两位小数
	
	set_main_data("预算", int(calculated_budget)) # 将计算得到的预算存回 shared_workflow_data
	
	print("MainPage: 计算得到的预算: ", calculated_budget, 
		  " (平台:", platform_cost, " 玩法:", gameplay_cost, " 题材:", theme_cost, " 策略系数:", strategy_cost_multiplier, ")")

# --- 信号处理函数 ---
func _on_platform_select_button_pressed():
	go_to_child_page(platform_page_path)

func _on_gameplay_select_button_pressed():
	go_to_child_page(gameplay_page_path)

func _on_theme_select_button_pressed():
	go_to_child_page(theme_page_path)

func _on_strategy_select_button_pressed():
	go_to_child_page(strategy_page_path)

func _on_confirm_button_pressed():
	# 导航到下一个页面或结束工作流
	if GameState.get_value("money") < get_main_data("预算"):
		go_to_child_page(notice_path)
		return
	else:
		next_ui_node_path = "../product_focus"
		var new_money = GameState.get_value("money")-get_main_data("预算")
		GameState.set_value("money",new_money)
		go_next()
