"""
学生管理组件
"""
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem, QPushButton,
                             QFileDialog, QMessageBox, QHeaderView, QLabel)
from PyQt5.QtCore import Qt
from frontend.utils.api_client import APIClient


class StudentManagementWidget(QWidget):
    """学生管理界面"""

    def __init__(self, api_client: APIClient, parent=None):
        super().__init__(parent)
        self.api_client = api_client
        self.init_ui()
        self.load_students()

    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout()

        # 标题
        title = QLabel("学生管理")
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)

        # 按钮栏
        button_layout = QHBoxLayout()

        self.import_btn = QPushButton("导入Excel")
        self.import_btn.clicked.connect(self.import_excel)
        button_layout.addWidget(self.import_btn)

        self.refresh_btn = QPushButton("刷新")
        self.refresh_btn.clicked.connect(self.load_students)
        button_layout.addWidget(self.refresh_btn)

        self.delete_btn = QPushButton("删除选中")
        self.delete_btn.clicked.connect(self.delete_selected)
        button_layout.addWidget(self.delete_btn)

        button_layout.addStretch()
        layout.addLayout(button_layout)

        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["ID", "学号", "姓名", "专业", "总积分"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        layout.addWidget(self.table)

        self.setLayout(layout)

    def load_students(self):
        """加载学生列表"""
        try:
            students = self.api_client.get_students()
            self.table.setRowCount(len(students))

            for row, student in enumerate(students):
                self.table.setItem(row, 0, QTableWidgetItem(str(student['id'])))
                self.table.setItem(row, 1, QTableWidgetItem(student['student_id']))
                self.table.setItem(row, 2, QTableWidgetItem(student['name']))
                self.table.setItem(row, 3, QTableWidgetItem(student.get('major', '')))
                self.table.setItem(row, 4, QTableWidgetItem(str(student['total_score'])))

            QMessageBox.information(self, "成功", f"已加载{len(students)}名学生")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载学生列表失败: {str(e)}")

    def import_excel(self):
        """导入Excel文件"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xlsx *.xls)")

        if not file_path:
            return

        try:
            result = self.api_client.import_students_from_excel(file_path)
            QMessageBox.information(
                self, "导入成功", f"{result['message']}\n成功: {result['imported_count']}, 失败: {result['failed_count']}")
            self.load_students()
        except Exception as e:
            QMessageBox.critical(self, "导入失败", f"导入Excel文件失败: {str(e)}")

    def delete_selected(self):
        """删除选中的学生"""
        current_row = self.table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "提示", "请先选择要删除的学生")
            return

        student_id = int(self.table.item(current_row, 0).text())
        student_name = self.table.item(current_row, 2).text()

        reply = QMessageBox.question(self, "确认删除", f"确定要删除学生 {student_name} 吗？", QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            try:
                self.api_client.delete_student(student_id)
                QMessageBox.information(self, "成功", "删除成功")
                self.load_students()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败: {str(e)}")
