package gui;

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

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;

public class RequestDetailDialog extends JDialog {
    private final LeaveRequestService leaveRequestService;
    private LeaveRequest currentRequest;
    private Runnable onApprovalComplete;  // 添加回调接口
    private boolean isStudent;  // 添加标识是否为学生

    public RequestDetailDialog(JFrame parent, int requestId, Runnable onApprovalComplete, boolean isStudent) {
        super(parent, "请假详情", true);
        this.leaveRequestService = ServiceFactory.getLeaveRequestService();
        this.onApprovalComplete = onApprovalComplete;
        this.isStudent = isStudent;
        
        // 根据ID获取请假信息
        this.currentRequest = leaveRequestService.getLeaveRequestById(requestId);
        
        if (currentRequest == null) {
            JOptionPane.showMessageDialog(parent, "未找到请假信息！", "错误", JOptionPane.ERROR_MESSAGE);
            dispose();
            return;
        }
        
        setSize(350, 550);
        setLocationRelativeTo(parent);
        setResizable(false);
        
        initComponents();
    }

    private void initComponents() {
        // 主面板使用GridBagLayout
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 10, 5, 10);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 学生基本信息
        addInfoField(mainPanel, gbc, "学院：", currentRequest.getStudent().getCollege());
        addInfoField(mainPanel, gbc, "专业：", currentRequest.getStudent().getMajor());
        addInfoField(mainPanel, gbc, "班级：", currentRequest.getStudent().getClassName());
        addInfoField(mainPanel, gbc, "姓名：", currentRequest.getStudent().getName());
        addInfoField(mainPanel, gbc, "学号：", currentRequest.getStudent().getStudentId());

        // 请假信息
        addInfoField(mainPanel, gbc, "申请外出时间：", dateFormat.format(currentRequest.getStartTime()));
        addInfoField(mainPanel, gbc, "预计返校时间：", dateFormat.format(currentRequest.getEndTime()));
        addInfoField(mainPanel, gbc, "时长：", String.format("%.2f", currentRequest.getDuration()));
        addInfoField(mainPanel, gbc, "外出地址：", currentRequest.getLocation());
        addInfoField(mainPanel, gbc, "外出事由：", currentRequest.getReasonType());
        addInfoField(mainPanel, gbc, "详细事由：", currentRequest.getReasonDetail());
        addInfoField(mainPanel, gbc, "是否离津：", currentRequest.isLeavingCity() ? "是" : "否");
        addInfoField(mainPanel, gbc, "发起时间：", dateFormat.format(currentRequest.getRequestTime()));
        addInfoField(mainPanel, gbc, "审批状态：", currentRequest.getStatus().getDescription());

        // 如果已经审批过，显示审批信息
        if (currentRequest.getStatus() != ApprovalStatus.PENDING) {
            if (currentRequest.getApprovalComment() != null) {
                addInfoField(mainPanel, gbc, "审批意见：", currentRequest.getApprovalComment());
            }
            if (currentRequest.getApprovalTime() != null) {
                addInfoField(mainPanel, gbc, "审批时间：", dateFormat.format(currentRequest.getApprovalTime()));
            }
        }

        // 审批按钮
        JPanel actionButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        
        if (isStudent) {
            // 学生只能看到撤销按钮，且仅在待审批状态下可用
            if (currentRequest.getStatus() == ApprovalStatus.PENDING) {
                JButton cancelButton = new JButton("撤销申请");
                cancelButton.setPreferredSize(new Dimension(100, 30));
                cancelButton.setBackground(new Color(231, 76, 60));
                cancelButton.addActionListener(e -> {
                    int confirm = JOptionPane.showConfirmDialog(
                        this,
                        "确定要撤销这条请假申请吗？",
                        "确认撤销",
                        JOptionPane.YES_NO_OPTION
                    );
                    if (confirm == JOptionPane.YES_OPTION) {
                        leaveRequestService.cancelLeaveRequest(currentRequest.getId());
                        dispose();
                        if (onApprovalComplete != null) {
                            onApprovalComplete.run();
                        }
                        JOptionPane.showMessageDialog(getParent(), "申请已撤销", "提示", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                actionButtonPanel.add(cancelButton);
            }
        } else {
            // 教师可以看到通过和驳回按钮
            JButton approveButton = new JButton("通过");
            JButton rejectButton = new JButton("驳回");
            
            // 如果已经审批过，禁用按钮
            if (currentRequest.getStatus() != ApprovalStatus.PENDING) {
                approveButton.setEnabled(false);
                rejectButton.setEnabled(false);
            }
            
            approveButton.setPreferredSize(new Dimension(100, 30));
            rejectButton.setPreferredSize(new Dimension(100, 30));
            
            // 设置按钮样式
            approveButton.setBackground(new Color(39, 174, 96));
            rejectButton.setBackground(new Color(231, 76, 60));
            
            actionButtonPanel.add(approveButton);
            actionButtonPanel.add(rejectButton);

            // 添加教师审批按钮的事件监听
            approveButton.addActionListener(e -> {
                // 创建一个自定义对话框
                JDialog approveDialog = new JDialog(this, "审批意见", true);
                approveDialog.setLayout(new BorderLayout());
                approveDialog.setSize(300, 200);
                approveDialog.setLocationRelativeTo(this);

                JPanel inputPanel = new JPanel(new BorderLayout(10, 10));
                inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

                JLabel label = new JLabel("请输入审批意见：");
                JTextArea commentArea = new JTextArea(4, 20);
                commentArea.setLineWrap(true);
                commentArea.setWrapStyleWord(true);
                commentArea.setText("同意");

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确定");
                JButton cancelButton = new JButton("取消");

                confirmButton.addActionListener(event -> {
                    String comment = commentArea.getText().trim();
                    if (!comment.isEmpty()) {
                        leaveRequestService.approveLeaveRequest(
                            currentRequest.getId(),
                            ApprovalStatus.APPROVED,
                            comment
                        );
                        approveDialog.dispose();
                        dispose();
                        if (onApprovalComplete != null) {
                            onApprovalComplete.run();
                        }
                    }
                });

                cancelButton.addActionListener(event -> approveDialog.dispose());

                buttonPanel.add(confirmButton);
                buttonPanel.add(cancelButton);

                inputPanel.add(label, BorderLayout.NORTH);
                inputPanel.add(new JScrollPane(commentArea), BorderLayout.CENTER);
                inputPanel.add(buttonPanel, BorderLayout.SOUTH);

                approveDialog.add(inputPanel);
                approveDialog.setVisible(true);
            });

            rejectButton.addActionListener(e -> {
                // 创建一个自定义对话框
                JDialog rejectDialog = new JDialog(this, "驳回原因", true);
                rejectDialog.setLayout(new BorderLayout());
                rejectDialog.setSize(300, 200);
                rejectDialog.setLocationRelativeTo(this);

                JPanel inputPanel = new JPanel(new BorderLayout(10, 10));
                inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

                JLabel label = new JLabel("请输入驳回原因：");
                JTextArea commentArea = new JTextArea(4, 20);
                commentArea.setLineWrap(true);
                commentArea.setWrapStyleWord(true);

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确定");
                JButton cancelButton = new JButton("取消");

                confirmButton.addActionListener(event -> {
                    String comment = commentArea.getText().trim();
                    if (!comment.isEmpty()) {
                        leaveRequestService.approveLeaveRequest(
                            currentRequest.getId(),
                            ApprovalStatus.REJECTED,
                            comment
                        );
                        rejectDialog.dispose();
                        dispose();
                        if (onApprovalComplete != null) {
                            onApprovalComplete.run();
                        }
                    }
                });

                cancelButton.addActionListener(event -> rejectDialog.dispose());

                buttonPanel.add(confirmButton);
                buttonPanel.add(cancelButton);

                inputPanel.add(label, BorderLayout.NORTH);
                inputPanel.add(new JScrollPane(commentArea), BorderLayout.CENTER);
                inputPanel.add(buttonPanel, BorderLayout.SOUTH);

                rejectDialog.add(inputPanel);
                rejectDialog.setVisible(true);
            });
        }

        // 添加按钮面板
        gbc.insets = new Insets(20, 10, 10, 10);
        mainPanel.add(actionButtonPanel, gbc);

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(mainPanel);
        scrollPane.setBorder(null);
        add(scrollPane);
    }

    private void addInfoField(JPanel panel, GridBagConstraints gbc, String label, String value) {
        JPanel fieldPanel = new JPanel(new BorderLayout(10, 0));
        
        JLabel labelComponent = new JLabel(label);
        labelComponent.setFont(new Font("微软雅黑", Font.BOLD, 12));
        
        JLabel valueComponent = new JLabel(value);
        valueComponent.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        fieldPanel.add(labelComponent, BorderLayout.WEST);
        fieldPanel.add(valueComponent, BorderLayout.CENTER);
        
        panel.add(fieldPanel, gbc);
    }
}
