package gui;

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

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class StudentMainFrame extends JFrame {
    private final LeaveRequestService leaveRequestService;
    private final Student currentStudent;
    private JTable requestTable;
    private DefaultTableModel tableModel;
    private int currentPage = 1;
    private static final int PAGE_SIZE = 10;

    public StudentMainFrame(Student student) {
        this.currentStudent = student;
        leaveRequestService = ServiceFactory.getLeaveRequestService();
        initComponents();
        loadLeaveRequests();
    }

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

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

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

        // 学生信息和申请按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 20, 5));
        
        // 添加学生信息
        JLabel studentInfoLabel = new JLabel(String.format("%s - %s", currentStudent.getClassName(), currentStudent.getName()));
        studentInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        buttonPanel.add(studentInfoLabel);

        // 申请按钮
        JButton newRequestButton = new JButton("日常出校申请");
        newRequestButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        newRequestButton.setBackground(new Color(52, 152, 219));
        // newRequestButton.setForeground(Color.WHITE);
        newRequestButton.setFocusPainted(false);
        newRequestButton.addActionListener(e -> showNewRequestDialog());
        
        buttonPanel.add(newRequestButton);
        topPanel.add(buttonPanel, BorderLayout.NORTH);

        // 表格
        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(60);   // 状态
        columnModel.getColumn(2).setPreferredWidth(100);  // 申请时间
        columnModel.getColumn(3).setPreferredWidth(100);  // 开始时间
        columnModel.getColumn(4).setPreferredWidth(100);  // 结束时间
        columnModel.getColumn(5).setPreferredWidth(100);  // 外出事由

        // 添加表格点击事件
        requestTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int row = requestTable.getSelectedRow();
                    if (row != -1) {
                        showRequestDetails(row);
                    }
                }
            }
        });

        // 分页控制
        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);

        // 分页按钮事件
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                loadLeaveRequests();
            }
        });
        
        nextButton.addActionListener(e -> {
            List<LeaveRequest> requests = leaveRequestService.getStudentLeaveRequests(currentStudent.getId());
            int totalPages = (requests.size() + PAGE_SIZE - 1) / PAGE_SIZE;
            if (currentPage < totalPages) {
                currentPage++;
                loadLeaveRequests();
            }
        });

        // 布局
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(requestTable), BorderLayout.CENTER);
        mainPanel.add(pagePanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void showNewRequestDialog() {
        JDialog dialog = new JDialog(this, "新建日常出校申请", true);
        dialog.setSize(400, 500);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // 开始时间
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("开始时间:"), gbc);

        gbc.gridx = 1;
        SpinnerDateModel startModel = new SpinnerDateModel();
        JSpinner startTimeSpinner = new JSpinner(startModel);
        startTimeSpinner.setEditor(new JSpinner.DateEditor(startTimeSpinner, "yyyy-MM-dd HH:mm"));
        panel.add(startTimeSpinner, gbc);

        // 结束时间
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("结束时间:"), gbc);

        gbc.gridx = 1;
        SpinnerDateModel endModel = new SpinnerDateModel();
        JSpinner endTimeSpinner = new JSpinner(endModel);
        endTimeSpinner.setEditor(new JSpinner.DateEditor(endTimeSpinner, "yyyy-MM-dd HH:mm"));
        panel.add(endTimeSpinner, gbc);

        // 外出地址
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("外出地址:"), gbc);

        gbc.gridx = 1;
        JTextField locationField = new JTextField(20);
        panel.add(locationField, gbc);

        // 事由类型
        gbc.gridx = 0;
        gbc.gridy = 3;
        panel.add(new JLabel("事由类型:"), gbc);

        gbc.gridx = 1;
        String[] reasonTypes = {"学习", "就医", "办事", "活动", "返乡", "实习", "其他"};
        JComboBox<String> reasonTypeCombo = new JComboBox<>(reasonTypes);
        panel.add(reasonTypeCombo, gbc);

        // 详细事由
        gbc.gridx = 0;
        gbc.gridy = 4;
        panel.add(new JLabel("详细事由:"), gbc);

        gbc.gridx = 1;
        JTextArea reasonArea = new JTextArea(4, 20);
        reasonArea.setLineWrap(true);
        reasonArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(reasonArea);
        panel.add(scrollPane, gbc);

        // 是否离津
        gbc.gridx = 0;
        gbc.gridy = 5;
        panel.add(new JLabel("是否离津:"), gbc);

        gbc.gridx = 1;
        JCheckBox leavingCityCheckBox = new JCheckBox();
        panel.add(leavingCityCheckBox, gbc);

        // 按钮面板
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton submitButton = new JButton("提交");
        JButton cancelButton = new JButton("取消");

        submitButton.addActionListener(e -> {
            Date startTime = (Date) startTimeSpinner.getValue();
            Date endTime = (Date) endTimeSpinner.getValue();
            String location = locationField.getText().trim();
            String reasonType = (String) reasonTypeCombo.getSelectedItem();
            String reasonDetail = reasonArea.getText().trim();
            boolean isLeavingCity = leavingCityCheckBox.isSelected();

            if (location.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写外出地址", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (reasonDetail.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写详细事由", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (startTime.after(endTime)) {
                JOptionPane.showMessageDialog(dialog, "开始时间不能晚于结束时间", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            LeaveRequest request = new LeaveRequest();
            request.setStudent(currentStudent);
            request.setStartTime(startTime);
            request.setEndTime(endTime);
            request.setLocation(location);
            request.setReasonType(reasonType);
            request.setReasonDetail(reasonDetail);
            request.setLeavingCity(isLeavingCity);
            request.setStatus(ApprovalStatus.PENDING);
            request.setRequestTime(new Date());

            // 计算请假时长（小时）
            double duration = (endTime.getTime() - startTime.getTime()) / (1000.0 * 60 * 60);
            request.setDuration(duration);

            if (leaveRequestService.submitLeaveRequest(request)) {
                loadLeaveRequests();
                dialog.dispose();
                JOptionPane.showMessageDialog(this, "申请提交成功", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "申请提交失败，请稍后重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(submitButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showRequestDetails(int row) {
        Long requestId = (Long) tableModel.getValueAt(row, 0);
        RequestDetailDialog dialog = new RequestDetailDialog(this, requestId.intValue(), this::loadLeaveRequests, true);
        dialog.setVisible(true);
    }

    private void loadLeaveRequests() {
        tableModel.setRowCount(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        
        List<LeaveRequest> requests = leaveRequestService.getStudentLeaveRequests(currentStudent.getId());
        
        // Calculate total pages
        int totalRequests = requests.size();
        int totalPages = (totalRequests + PAGE_SIZE - 1) / PAGE_SIZE;
        
        // Update page label
        Component[] components = getContentPane().getComponents();
        for (Component comp : components) {
            if (comp instanceof JPanel) {
                JPanel panel = (JPanel) comp;
                for (Component innerComp : panel.getComponents()) {
                    if (innerComp instanceof JPanel && ((JPanel) innerComp).getComponentCount() == 3) {
                        JPanel pagePanel = (JPanel) innerComp;
                        JLabel pageLabel = (JLabel) pagePanel.getComponent(1);
                        pageLabel.setText(currentPage + "/" + totalPages);
                        break;
                    }
                }
            }
        }
        
        // Get current page's requests
        int fromIndex = (currentPage - 1) * PAGE_SIZE;
        int toIndex = Math.min(fromIndex + PAGE_SIZE, totalRequests);
        List<LeaveRequest> pageRequests = fromIndex < totalRequests ? requests.subList(fromIndex, toIndex) : requests;
        
        for (LeaveRequest request : pageRequests) {
            tableModel.addRow(new Object[]{
                Long.valueOf(request.getId()),  
                request.getStatus().getDescription(),
                sdf.format(request.getRequestTime()),
                sdf.format(request.getStartTime()),
                sdf.format(request.getEndTime()),
                request.getReasonDetail()
            });
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                // 使用实际学生数据
                Student student = ServiceFactory.getStudentService().login("2023208145", "123456");
                if (student != null) {
                    new StudentMainFrame(student).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "无法加载学生信息", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "系统错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
}
