"""侧边面板（日志 / Local Dimming / 调试）（Step 6 重构）。"""

import traceback
import tkinter as tk
import ttkbootstrap as ttk

from app.views.pq_log_gui import PQLogGUI
from app.views.pq_debug_panel import PQDebugPanel

def create_log_panel(self):
    """创建日志面板"""
    self.log_frame = ttk.Frame(self.content_frame)
    self.log_gui = PQLogGUI(self.log_frame)
    self.log_gui.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

    # 默认隐藏日志面板
    self.log_visible = False

    # 注册到面板管理系统
    self.register_panel(
        "log", self.log_frame, None, "log_visible"
    )  # button会在后面设置


def create_local_dimming_panel(self):
    """创建 Local Dimming 测试面板 - 手动控制版"""
    self.local_dimming_frame = ttk.Frame(self.content_frame)

    # 主容器
    main_container = ttk.Frame(self.local_dimming_frame, padding=10)
    main_container.pack(fill=tk.BOTH, expand=True)

    # ==================== 1. 标题 ====================
    title_frame = ttk.Frame(main_container)
    title_frame.pack(fill=tk.X, pady=(0, 10))

    ttk.Label(
        title_frame,
        text="🔆 Local Dimming 窗口测试",
        font=("微软雅黑", 14, "bold"),
    ).pack(side=tk.LEFT)

    # ==================== 2. 窗口百分比按钮 ====================
    window_frame = ttk.LabelFrame(
        main_container, text="🔆 窗口百分比（点击发送）", padding=10
    )
    window_frame.pack(fill=tk.X, pady=(0, 10))

    # 说明文字
    ttk.Label(
        window_frame,
        text="点击按钮发送对应百分比的白色窗口（黑色背景 + 居中白色矩形）",
        font=("", 9),
        foreground="#28a745",
    ).pack(pady=(0, 8))

    # 第一行：1%, 2%, 5%, 10%, 18%
    row1 = ttk.Frame(window_frame)
    row1.pack(fill=tk.X, pady=(0, 5))

    percentages_row1 = [1, 2, 5, 10, 18]
    for p in percentages_row1:
        ttk.Button(
            row1,
            text=f"{p}%",
            command=lambda p=p: self.send_ld_window(p),
            bootstyle="success",
            width=12,
        ).pack(side=tk.LEFT, padx=3)

    # 第二行：25%, 50%, 75%, 100%
    row2 = ttk.Frame(window_frame)
    row2.pack(fill=tk.X)

    percentages_row2 = [25, 50, 75, 100]
    for p in percentages_row2:
        ttk.Button(
            row2,
            text=f"{p}%",
            command=lambda p=p: self.send_ld_window(p),
            bootstyle="success",
            width=12,
        ).pack(side=tk.LEFT, padx=3)

    # ==================== 4. CA410 采集按钮 ====================
    measure_frame = ttk.LabelFrame(main_container, text="📊 CA410 测量", padding=10)
    measure_frame.pack(fill=tk.X, pady=(0, 10))

    measure_btn_frame = ttk.Frame(measure_frame)
    measure_btn_frame.pack(fill=tk.X)

    self.ld_measure_btn = ttk.Button(
        measure_btn_frame,
        text="📏 采集当前亮度",
        command=self.measure_ld_luminance,
        bootstyle="primary",
        width=15,
    )
    self.ld_measure_btn.pack(side=tk.LEFT, padx=(0, 5))

    # 显示测量结果
    self.ld_result_label = ttk.Label(
        measure_btn_frame,
        text="亮度: -- cd/m² | x: -- | y: --",
        font=("Consolas", 10),
        foreground="#007bff",
    )
    self.ld_result_label.pack(side=tk.LEFT, padx=(10, 0))

    # ==================== 5. 测试结果表格 ====================
    result_frame = ttk.LabelFrame(main_container, text="📋 测试记录", padding=10)
    result_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))

    # Treeview
    columns = ("窗口百分比", "亮度 (cd/m²)", "x", "y", "时间")
    self.ld_tree = ttk.Treeview(
        result_frame, columns=columns, show="headings", height=10
    )

    for col in columns:
        self.ld_tree.heading(col, text=col)
        if col == "窗口百分比":
            self.ld_tree.column(col, width=100, anchor=tk.CENTER)
        elif col == "时间":
            self.ld_tree.column(col, width=120, anchor=tk.CENTER)
        else:
            self.ld_tree.column(col, width=100, anchor=tk.CENTER)

    self.ld_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    # 滚动条
    scrollbar = ttk.Scrollbar(
        result_frame, orient=tk.VERTICAL, command=self.ld_tree.yview
    )
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    self.ld_tree.configure(yscrollcommand=scrollbar.set)

    # ==================== 6. 底部操作按钮 ====================
    bottom_frame = ttk.Frame(main_container)
    bottom_frame.pack(fill=tk.X)

    self.ld_clear_btn = ttk.Button(
        bottom_frame,
        text="🗑️ 清空记录",
        command=self.clear_ld_records,
        bootstyle="danger-outline",
        width=12,
    )
    self.ld_clear_btn.pack(side=tk.LEFT, padx=(0, 5))

    self.ld_save_btn = ttk.Button(
        bottom_frame,
        text="💾 保存结果",
        command=self.save_local_dimming_results,
        bootstyle="info",
        width=12,
    )
    self.ld_save_btn.pack(side=tk.LEFT)

    # 默认隐藏
    self.local_dimming_visible = False

    # 注册到面板管理系统
    self.register_panel(
        "local_dimming",
        self.local_dimming_frame,
        None,
        "local_dimming_visible",
    )

    # 初始化当前窗口百分比（用于记录）
    self.current_ld_percentage = None


def toggle_local_dimming_panel(self):
    """切换 Local Dimming 面板显示"""
    self.show_panel("local_dimming")


def toggle_log_panel(self):
    """切换日志面板的显示状态"""
    self.show_panel("log")


def toggle_screen_debug_panel(self):
    """打开/关闭屏模组单步调试面板（独立窗口）"""
    # 如果窗口已存在且可见，关闭它
    if hasattr(self, "debug_window") and self.debug_window.winfo_exists():
        self.debug_window.destroy()
        self.screen_debug_btn.config(text="打开调试面板")
        self.log_gui.log("✓ 单步调试面板已关闭")
        return

    # 创建新窗口
    self.debug_window = ttk.Toplevel(self.root)
    self.debug_window.title("🔧 单步调试面板")
    self.debug_window.geometry("900x400")
    self.debug_window.transient(self.root)

    # 创建调试面板容器
    debug_container = ttk.Frame(self.debug_window, padding=10)
    debug_container.pack(fill=tk.BOTH, expand=True)  # ← 这个 pack 是对的

    # 创建调试面板实例
    from app.views.pq_debug_panel import PQDebugPanel

    debug_panel_instance = PQDebugPanel(debug_container, self)
    # ← 这里不应该有任何 pack 调用！

    self.log_gui.log("✓ 单步调试面板实例已创建")

    # 重新启用调试（如果有数据）
    try:
        test_type = self.config.current_test_type
        selected_items = self.get_selected_test_items()

        if test_type == "screen_module":
            if "gamma" in selected_items:
                gray_data = self.results.get_intermediate_data("shared", "gray")
                if gray_data:
                    self.log_gui.log(f"  → 加载 {len(gray_data)} 个灰阶数据点")
                    debug_panel_instance.enable_debug(
                        "screen_module", "gamma", gray_data
                    )
                    self.log_gui.log("✓ 屏模组 Gamma 单步调试已重新启用")
                else:
                    self.log_gui.log("  ✗ 没有可用的灰阶数据")

            if "gamut" in selected_items:
                rgb_data = self.results.get_intermediate_data("gamut", "rgb")
                if rgb_data:
                    self.log_gui.log(f"  → 加载 {len(rgb_data)} 个RGB数据点")
                    debug_panel_instance.enable_debug(
                        "screen_module", "rgb", rgb_data
                    )
                    self.log_gui.log("✓ 屏模组 RGB 单步调试已重新启用")

    except Exception as e:
        self.log_gui.log(f"⚠️ 加载调试数据失败: {str(e)}")
        import traceback

        self.log_gui.log(traceback.format_exc())

    # 更新按钮文字
    self.screen_debug_btn.config(text="关闭调试面板")

    # 窗口关闭时的回调
    def on_closing():
        self.screen_debug_btn.config(text="打开调试面板")
        self.debug_window.destroy()
        self.log_gui.log("✓ 单步调试窗口已关闭")

    self.debug_window.protocol("WM_DELETE_WINDOW", on_closing)
    self.debug_window.update_idletasks()

    self.log_gui.log("✓ 单步调试面板已打开（独立窗口）")


def toggle_sdr_debug_panel(self):
    """打开/关闭 SDR 单步调试面板（独立窗口）"""
    # 如果窗口已存在且可见，关闭它
    if hasattr(self, "sdr_debug_window") and self.sdr_debug_window.winfo_exists():
        self.sdr_debug_window.destroy()
        self.sdr_debug_btn.config(text="打开调试面板")
        self.log_gui.log("✓ SDR 单步调试面板已关闭")
        return

    # 创建新窗口
    self.sdr_debug_window = ttk.Toplevel(self.root)
    self.sdr_debug_window.title("🔧 SDR 单步调试面板")
    self.sdr_debug_window.geometry("900x400")
    self.sdr_debug_window.transient(self.root)

    # 创建调试面板容器
    debug_container = ttk.Frame(self.sdr_debug_window, padding=10)
    debug_container.pack(fill=tk.BOTH, expand=True)

    # ✅ 创建调试面板实例（不要对它调用 pack）
    from app.views.pq_debug_panel import PQDebugPanel

    debug_panel_instance = PQDebugPanel(debug_container, self)
    # ← 删除：debug_panel_instance.pack(...)

    self.log_gui.log("✓ SDR 单步调试面板实例已创建")

    # ✅ 重新启用调试（如果有数据）
    try:
        selected_items = self.get_selected_test_items()

        if "gamma" in selected_items:
            gray_data = self.results.get_intermediate_data("shared", "gray")
            if gray_data:
                self.log_gui.log(f"  → 加载 {len(gray_data)} 个灰阶数据点")
                debug_panel_instance.enable_debug("sdr_movie", "gamma", gray_data)
                self.log_gui.log("✓ SDR Gamma 单步调试已重新启用")

        if "accuracy" in selected_items:
            accuracy_data = self.results.get_intermediate_data(
                "accuracy", "measured"
            )
            if accuracy_data:
                self.log_gui.log(f"  → 加载 {len(accuracy_data)} 个色准数据点")
                debug_panel_instance.enable_debug(
                    "sdr_movie", "accuracy", accuracy_data
                )
                self.log_gui.log("✓ SDR 色准单步调试已重新启用")

        if "gamut" in selected_items:
            rgb_data = self.results.get_intermediate_data("gamut", "rgb")
            if rgb_data:
                self.log_gui.log(f"  → 加载 {len(rgb_data)} 个RGB数据点")
                debug_panel_instance.enable_debug("sdr_movie", "rgb", rgb_data)
                self.log_gui.log("✓ SDR RGB 单步调试已重新启用")

    except Exception as e:
        self.log_gui.log(f"⚠️ 加载 SDR 调试数据失败: {str(e)}")
        import traceback

        self.log_gui.log(traceback.format_exc())

    # 更新按钮文字
    self.sdr_debug_btn.config(text="关闭调试面板")

    # 窗口关闭时的回调
    def on_closing():
        self.sdr_debug_btn.config(text="打开调试面板")
        self.sdr_debug_window.destroy()
        self.log_gui.log("✓ SDR 单步调试窗口已关闭")

    self.sdr_debug_window.protocol("WM_DELETE_WINDOW", on_closing)
    self.sdr_debug_window.update_idletasks()

    self.log_gui.log("✓ SDR 单步调试面板已打开（独立窗口）")


def toggle_hdr_debug_panel(self):
    """打开/关闭 HDR 单步调试面板（独立窗口）"""
    # 如果窗口已存在且可见，关闭它
    if hasattr(self, "hdr_debug_window") and self.hdr_debug_window.winfo_exists():
        self.hdr_debug_window.destroy()
        self.hdr_debug_btn.config(text="打开调试面板")
        self.log_gui.log("✓ HDR 单步调试面板已关闭")
        return

    # 创建新窗口
    self.hdr_debug_window = ttk.Toplevel(self.root)
    self.hdr_debug_window.title("🔧 HDR 单步调试面板")
    self.hdr_debug_window.geometry("900x400")
    self.hdr_debug_window.transient(self.root)

    # 创建调试面板容器
    debug_container = ttk.Frame(self.hdr_debug_window, padding=10)
    debug_container.pack(fill=tk.BOTH, expand=True)

    # ✅ 创建调试面板实例（不要对它调用 pack）
    from app.views.pq_debug_panel import PQDebugPanel

    debug_panel_instance = PQDebugPanel(debug_container, self)
    # ← 删除：debug_panel_instance.pack(...)

    self.log_gui.log("✓ HDR 单步调试面板实例已创建")

    # ✅ 重新启用调试（如果有数据）
    try:
        selected_items = self.get_selected_test_items()

        if "eotf" in selected_items:
            gray_data = self.results.get_intermediate_data("shared", "gray")
            if gray_data:
                self.log_gui.log(f"  → 加载 {len(gray_data)} 个灰阶数据点")
                debug_panel_instance.enable_debug("hdr_movie", "eotf", gray_data)
                self.log_gui.log("✓ HDR EOTF 单步调试已重新启用")

        if "accuracy" in selected_items:
            accuracy_data = self.results.get_intermediate_data(
                "accuracy", "measured"
            )
            if accuracy_data:
                self.log_gui.log(f"  → 加载 {len(accuracy_data)} 个色准数据点")
                debug_panel_instance.enable_debug(
                    "hdr_movie", "accuracy", accuracy_data
                )
                self.log_gui.log("✓ HDR 色准单步调试已重新启用")

        if "gamut" in selected_items:
            rgb_data = self.results.get_intermediate_data("gamut", "rgb")
            if rgb_data:
                self.log_gui.log(f"  → 加载 {len(rgb_data)} 个RGB数据点")
                debug_panel_instance.enable_debug("hdr_movie", "rgb", rgb_data)
                self.log_gui.log("✓ HDR RGB 单步调试已重新启用")

    except Exception as e:
        self.log_gui.log(f"⚠️ 加载 HDR 调试数据失败: {str(e)}")
        import traceback

        self.log_gui.log(traceback.format_exc())

    # 更新按钮文字
    self.hdr_debug_btn.config(text="关闭调试面板")

    # 窗口关闭时的回调
    def on_closing():
        self.hdr_debug_btn.config(text="打开调试面板")
        self.hdr_debug_window.destroy()
        self.log_gui.log("✓ HDR 单步调试窗口已关闭")

    self.hdr_debug_window.protocol("WM_DELETE_WINDOW", on_closing)
    self.hdr_debug_window.update_idletasks()

    self.log_gui.log("✓ HDR 单步调试面板已打开（独立窗口）")


