package gui;

import model.ApprovalStatus;
import model.LeaveRequest;
import service.LeaveRequestService;
import service.ServiceFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.List;

public class TeacherMainFrame extends JFrame {
    private final LeaveRequestService leaveRequestService;
    private JTable requestTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JComboBox<String> statusFilter;
    private int currentPage = 1;
    private static final int PAGE_SIZE = 10;

    public TeacherMainFrame() {
        leaveRequestService = ServiceFactory.getLeaveRequestService();
        initComponents();
        loadLeaveRequests();
    }

    private void initComponents() {
        setTitle("平安校园 - 日常出校申请");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 600);
        setLocationRelativeTo(null);

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 标题
        JLabel titleLabel = new JLabel("日常出校申请", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        topPanel.add(titleLabel, BorderLayout.CENTER);

        // 状态过滤器
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        String[] statuses = {"全部", ApprovalStatus.PENDING.getDescription(), 
                                   ApprovalStatus.APPROVED.getDescription(), 
                                   ApprovalStatus.REJECTED.getDescription()};
        statusFilter = new JComboBox<>(statuses);
        statusFilter.addActionListener(e -> loadLeaveRequests());
        filterPanel.add(statusFilter);

        // 搜索框
        searchField = new JTextField(15);
        JButton searchButton = new JButton("筛选");
        searchPanel.add(new JLabel("请输入学号或姓名："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        
        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(filterPanel, BorderLayout.SOUTH);

        // 表格
        String[] columnNames = {"ID", "姓名", "班级", "状态", "申请时间", "外出事由"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        requestTable = new JTable(tableModel);
        requestTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 设置表格样式
        requestTable.setRowHeight(30);
        requestTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 12));
        requestTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 设置列宽
        TableColumnModel columnModel = requestTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(40);  // ID
        columnModel.getColumn(1).setPreferredWidth(50);  // 姓名
        columnModel.getColumn(2).setPreferredWidth(90);  // 班级
        columnModel.getColumn(3).setPreferredWidth(50);  // 状态
        columnModel.getColumn(4).setPreferredWidth(100); // 申请时间
        columnModel.getColumn(5).setPreferredWidth(60);  // 外出事由

        // 分页控制
        JPanel pagePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        JLabel pageLabel = new JLabel("1/1");
        pagePanel.add(prevButton);
        pagePanel.add(pageLabel);
        pagePanel.add(nextButton);

        // 操作按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton approveButton = new JButton("通过");
        JButton rejectButton = new JButton("驳回");
        
        approveButton.setPreferredSize(new Dimension(80, 30));
        rejectButton.setPreferredSize(new Dimension(80, 30));
        
        // 设置按钮颜色
        approveButton.setBackground(new Color(39, 174, 96));
        approveButton.setForeground(Color.WHITE);
        rejectButton.setBackground(new Color(231, 76, 60));
        rejectButton.setForeground(Color.WHITE);
        
        buttonPanel.add(approveButton);
        buttonPanel.add(rejectButton);
        
        // 默认禁用按钮
        approveButton.setEnabled(false);
        rejectButton.setEnabled(false);

        // 表格选择监听器
        requestTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting() && requestTable.getSelectedRow() != -1) {
                String statusText = (String) tableModel.getValueAt(requestTable.getSelectedRow(), 3);
                boolean isPending = false;
                for (ApprovalStatus s : ApprovalStatus.values()) {
                    if (s.getDescription().equals(statusText)) {
                        isPending = (s == ApprovalStatus.PENDING);
                        break;
                    }
                }
                approveButton.setEnabled(isPending);
                rejectButton.setEnabled(isPending);
            }
        });

        // 按钮点击事件
        approveButton.addActionListener(e -> {
            if (requestTable.getSelectedRow() != -1) {
                showRequestDetails(requestTable.getSelectedRow());
            }
        });

        rejectButton.addActionListener(e -> {
            if (requestTable.getSelectedRow() != -1) {
                showRequestDetails(requestTable.getSelectedRow());
            }
        });

        // 添加到主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(requestTable), BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        mainPanel.add(pagePanel, BorderLayout.SOUTH);

        // 添加事件监听
        searchButton.addActionListener(e -> loadLeaveRequests());
        
        // 使用鼠标监听器替代选择监听器，实现双击打开详情
        requestTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 && requestTable.getSelectedRow() != -1) {
                    showRequestDetails(requestTable.getSelectedRow());
                }
            }
        });

        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                loadLeaveRequests();
            }
        });

        nextButton.addActionListener(e -> {
            currentPage++;
            loadLeaveRequests();
        });

        add(mainPanel);
    }

    private void loadLeaveRequests() {
        tableModel.setRowCount(0);
        String searchText = searchField.getText().trim();
        String statusText = (String) statusFilter.getSelectedItem();
        
        List<LeaveRequest> requests;
        if ("全部".equals(statusText)) {
            requests = leaveRequestService.getAllLeaveRequests();
        } else {
            ApprovalStatus status = null;
            for (ApprovalStatus s : ApprovalStatus.values()) {
                if (s.getDescription().equals(statusText)) {
                    status = s;
                    break;
                }
            }
            requests = leaveRequestService.getLeaveRequestsByStatus(status);
        }

        // 过滤搜索结果
        if (!searchText.isEmpty()) {
            requests.removeIf(request -> 
                !request.getStudent().getName().contains(searchText) &&
                !request.getStudent().getStudentId().contains(searchText));
        }

        // 添加到表格
        for (LeaveRequest request : requests) {
            Object[] row = {
                request.getId(),
                request.getStudent().getName(),
                request.getStudent().getClassName(),
                request.getStatus().getDescription(),
                new SimpleDateFormat("MM-dd HH:mm").format(request.getRequestTime()),
                request.getReasonType()
            };
            tableModel.addRow(row);
        }
    }

    private void showRequestDetails(int row) {
        // 创建详情对话框
        RequestDetailDialog dialog = new RequestDetailDialog(
            this, 
            ((Number)tableModel.getValueAt(row, 0)).intValue(),  // 获取ID
            () -> loadLeaveRequests(),  // 添加刷新列表的回调
            false  // 教师视角
        );
        dialog.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(() -> {
            TeacherMainFrame frame = new TeacherMainFrame();
            frame.setVisible(true);
        });
    }
}
