package view;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import backend.model.Questions;
import backend.service.QuestionsService;
import backend.model.enums.GlobalData;

public class QuestionsPanel extends JPanel{
    private QuestionsService questionsService = new QuestionsService();
    private static Vector<String> columNames = new Vector<>();
    private DefaultTableModel model;
    private JTable table;
    private JScrollPane scrollPane;
    private Vector<Vector<String>> tableData;
    //按钮界面
    private JButton addButton;
    private JButton deleteButton;
    private JButton editButton;
    //搜索界面
    private JComboBox frequencyComboBox;
    private JTextField keyTextField;
    private JButton queryButton;

    // 颜色常量定义
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);  // 钢蓝色
    private static final Color BACKGROUND_COLOR = new Color(248, 249, 250);  // 浅灰色背景
    private static final Color BORDER_COLOR = new Color(220, 220, 220);  // 边框颜色
    private static final Color HIGHLIGHT_COLOR = new Color(255, 255, 204);  // 高亮背景

    static {
        columNames.add("ID");
        columNames.add("题目");
        columNames.add("描述");
        columNames.add("答案");
        columNames.add("频率");
    }

    public void initListener(){
        queryButton.addActionListener(e->{
            Integer frequency = frequencyComboBox.getSelectedIndex()==0?null:frequencyComboBox.getSelectedIndex();
            String key = keyTextField.getText();
            //清楚已有数据
            model.setRowCount(0);
            //条件查询
            tableData = questionsService.getByCondition(frequency,key);
            //刷新表格
            refreshData();
        });
        deleteButton.addActionListener(e->{
            if(MainFrame.role.equals("user"))
                return;
            int row = table.getSelectedRow();
            if(row!=-1){
                int id = Integer.valueOf(tableData.get(row).get(0));
                String word = tableData.get(row).get(1);
                int option = JOptionPane.showConfirmDialog(this,"确认删除"+word+"吗？","提示",JOptionPane.YES_NO_CANCEL_OPTION);
                if(option == JOptionPane.YES_OPTION){
                    questionsService.delete(id);
                    model.removeRow(row);
                }
            }
        });
        //添加事件：打开对话框
        addButton.addActionListener(e->{
            if(MainFrame.role.equals("user"))
                return;
            new EditQuestionDialog(0,null);
        });
        editButton.addActionListener(e->{
            if(MainFrame.role.equals("user"))
                return;
            int row = table.getSelectedRow();
            if(row>=0)
                openEditDialog(row);

        });
        //双击某行弹出修改对话框
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(MainFrame.role.equals("user"))
                    return;
                if(e.getClickCount()==2){
                    int row = table.getSelectedRow();
                    openEditDialog(row);
                }
            }
        });
    }

    private void openEditDialog(int row){
        Vector<String> data = tableData.get(row);
        Questions questions = new Questions();
        questions.setId(Integer.parseInt(data.get(0)));
        questions.setName(data.get(1));
        questions.setDescription(data.get(2));
        questions.setAnswer(data.get(3));
        questions.setFrequency(GlobalData.getFrequencyByValue(data.get(4)));
        new EditQuestionDialog(1, questions);
        //修改成功后刷新并定位修改位置
        tableData = questionsService.getAll();
        refreshData();
        table.setRowSelectionInterval(row,row);
        scrollPane.getVerticalScrollBar().setValue(row*table.getRowHeight());
        scrollPane.getHorizontalScrollBar().setValue(0);
        scrollPane.revalidate();
    }

    public QuestionsPanel(){
        initView();
        initListener();
    }

    private void initView(){
        setLayout(new BorderLayout());
        setBackground(BACKGROUND_COLOR);

        // 创建顶部工具栏
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(PRIMARY_COLOR);
        topPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        JLabel titleLabel = new JLabel("题目管理");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel, BorderLayout.WEST);

        add(topPanel, BorderLayout.NORTH);

        // 创建中央内容面板
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
        centerPanel.setBackground(BACKGROUND_COLOR);
        centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 1.按钮界面
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        buttonPanel.setBackground(BACKGROUND_COLOR);
        addButton = new JButton("添加");
        deleteButton = new JButton("删除");
        editButton = new JButton("修改");

        // 设置按钮样式
        setButtonStyle(addButton);
        setButtonStyle(deleteButton);
        setButtonStyle(editButton);

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(editButton);

        centerPanel.add(buttonPanel);
        centerPanel.add(Box.createVerticalStrut(10));

        // 2.搜索界面
        JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        queryPanel.setBackground(BACKGROUND_COLOR);
        frequencyComboBox = new JComboBox<String>(new String[]{"全部","低频","中频","高频"});
        keyTextField = new JTextField(15);
        queryButton = new JButton("查询");

        // 设置查询按钮样式
        setButtonStyle(queryButton);

        queryPanel.add(new JLabel("频率:"));
        queryPanel.add(frequencyComboBox);
        queryPanel.add(new JLabel("关键词:"));
        queryPanel.add(keyTextField);
        queryPanel.add(queryButton);

        centerPanel.add(queryPanel);
        centerPanel.add(Box.createVerticalStrut(10));

        // 3.表格界面
        model = new DefaultTableModel(){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        table = new JTable(model);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.WHITE);
        table.setSelectionBackground(new Color(176, 224, 230));
        table.setRowHeight(25);

        scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(700, 400));
        scrollPane.setBorder(BorderFactory.createLineBorder(BORDER_COLOR, 1));

        centerPanel.add(scrollPane);

        add(centerPanel, BorderLayout.CENTER);

        tableData = questionsService.getAll();
        //刷新数据
        refreshData();
    }

    // 设置按钮样式
    private void setButtonStyle(JButton button) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setPreferredSize(new Dimension(80, 30));
        button.setBackground(PRIMARY_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createRaisedBevelBorder());
    }

    private void refreshData(){
        model.setDataVector(tableData,columNames);
        model.fireTableDataChanged();
    }
}
