import ttkbootstrap as ttk
import tkinter as tk
from src.gui.styles import *
# 新增：导入Matplotlib字体配置和刻度模块
import matplotlib
import matplotlib.ticker as ticker  # 关键：用于设置刻度间隔
matplotlib.rcParams["font.family"] = ["SimHei", "Microsoft YaHei", "DejaVu Sans"]  # 优先中文字体
matplotlib.rcParams["axes.unicode_minus"] = False  # 解决负号显示为方块的问题

class CustomButton(ttk.Button):
    """自定义按钮组件"""
    def __init__(self, parent, text, command=None, style="Primary.TButton", **kwargs):
        super().__init__(
            parent,
            text=text,
            command=command,
            style=style,
            width=BUTTON_WIDTH,** kwargs
        )

class ResultDisplay(ttk.Label):
    """点名结果展示标签"""
    def __init__(self, parent):
        super().__init__(
            parent,
            text="等待点名...",
            style="Result.TLabel",
            anchor="center",
            justify="center"
        )

class StudentTable(ttk.Treeview):
    """学生名单表格"""
    def __init__(self, parent):
        super().__init__(parent, show="headings")
        # 定义列
        self["columns"] = ("学号", "姓名", "专业", "总积分", "随机点名次数")
        # 设置列标题和宽度
        for col in self["columns"]:
            self.heading(col, text=col)
            self.column(col, width=100, anchor="center")
        # 滚动条
        scroll_y = ttk.Scrollbar(parent, orient="vertical", command=self.yview)
        self.configure(yscrollcommand=scroll_y.set)
        scroll_y.pack(side="right", fill="y")
        self.pack(fill="both", expand=True)

    def refresh_data(self, data):
        """刷新表格数据"""
        # 清空原有数据
        for item in self.get_children():
            self.delete(item)
        # 添加新数据
        for row in data:
            self.insert("", "end", values=row)

class VisualizationFrame(ttk.Frame):
    """可视化图表容器（简易版，结合matplotlib）"""
    def __init__(self, parent):
        super().__init__(parent)
        self.canvas = None

    def show_chart(self, students):
        """显示积分和点名次数图表（优化折线图纵轴刻度+数据读取）"""
        from matplotlib.figure import Figure
        from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
        import json
        import os  # 新增：处理路径
        
        # 修复配置文件路径（沿用之前的绝对路径逻辑，避免相对路径错误）
        current_file = os.path.abspath(__file__)
        utils_dir = os.path.dirname(os.path.dirname(current_file))  # 上级目录
        project_root = os.path.dirname(utils_dir)
        config_path = os.path.join(project_root, "config", "settings.json")
        
        with open(config_path, "r", encoding="utf-8") as f:
            vis_config = json.load(f)["visualization"]
        
        # 创建图表
        fig = Figure(figsize=vis_config["fig_size"], dpi=100)
        fig.suptitle("学生积分与点名次数可视化", fontsize=12)
        
        # 过滤有效数据（确保至少包含5个字段，避免索引错误）
        valid_students = [s for s in students if len(s)>=5]
        # 提取可视化数据（仅取TOP-N，适配配置）
        top_n = vis_config["top_n"]
        show_students = valid_students[:top_n] if len(valid_students)>=top_n else valid_students
        names = [s[1] for s in show_students]
        scores = [s[3] for s in show_students]
        call_nums = [s[4] for s in show_students]

        # 子图1：积分柱形图
        ax1 = fig.add_subplot(121)
        if names:  # 有数据才绘制
            ax1.bar(names, scores, color=COLOR_PRIMARY)
        else:
            ax1.text(0.5, 0.5, "暂无学生数据", ha="center", va="center", transform=ax1.transAxes)
        ax1.set_title(f"TOP{vis_config['top_n']}积分排名")
        ax1.set_xlabel("姓名")
        ax1.set_ylabel("总积分")
        ax1.tick_params(axis="x", rotation=45)
        
        # 子图2：点名次数折线图（核心优化：纵轴从0开始+刻度为1）
        ax2 = fig.add_subplot(122)
        if names:  # 有数据才绘制
            ax2.plot(names, call_nums, marker="o", color=COLOR_SECONDARY, linestyle="-", linewidth=2, markersize=6)
            # 强制纵轴从0开始
            ax2.set_ylim(bottom=0)
            # 设置纵轴刻度间隔为1
            ax2.yaxis.set_major_locator(ticker.MultipleLocator(1))
            # 可选：显示网格，方便查看刻度
            ax2.grid(axis="y", linestyle="--", alpha=0.7)
        else:
            ax2.text(0.5, 0.5, "暂无点名数据", ha="center", va="center", transform=ax2.transAxes)
        ax2.set_title(f"TOP{vis_config['top_n']}随机点名次数")
        ax2.set_xlabel("姓名")
        ax2.set_ylabel("点名次数")
        ax2.tick_params(axis="x", rotation=45)
        
        # 调整子图间距，避免标题/标签重叠
        fig.tight_layout()
        
        # 嵌入Tkinter
        if self.canvas:
            self.canvas.get_tk_widget().destroy()
        self.canvas = FigureCanvasTkAgg(fig, master=self)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(fill="both", expand=True)