package cn.net.connor.createTempDrawings.utils;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;

public class JTreeComboBox extends JComboBox<Object> {
    private JTree tree;
    private DefaultTreeModel treeModel;
    private boolean suppressEvents = false;

    public JTreeComboBox(DefaultMutableTreeNode root) {
    	System.out.println("JTreeComboBox构造函数被调用，root是否为null: " + (root == null));
        
        
        // 初始化树模型
        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);
        System.out.println("树对象已初始化: " + (tree != null));
        
        // 设置自定义UI
        setUI(new TreeComboBoxUI());
        System.out.println("自定义UI已设置");
        
        // 设置树属性
        tree.setRootVisible(true);
        tree.setShowsRootHandles(true);
        tree.setCellRenderer(new TreeCellRenderer());
        
        // 添加选择监听器
        tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                if (!suppressEvents) {
                    System.out.println("更新选中项！");
                    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                    if (selectedNode != null) {
                        System.out.println("选中的节点：" + selectedNode.getUserObject());
                        setSelectedItem(selectedNode);
                        hidePopup();
                    }
                    DefaultMutableTreeNode ss1 = (DefaultMutableTreeNode)getSelectedItem();
                    if (ss1 == null) {
						System.out.println("ss1 = null");
					}else {
						System.out.println("ss1 != null");
					}
                    
                }
            }
        });
        
        // 处理鼠标点击事件
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path != null) {
                    tree.setSelectionPath(path);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                    if (node != null) {
                        if (tree.isExpanded(path)) {
                            tree.collapsePath(path);
                        } else {
                            tree.expandPath(path);
                        }
                    }
                }
            }
        });
        
        // 处理键盘事件
        tree.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER) {
                    TreePath selectionPath = tree.getSelectionPath();
                    if (selectionPath != null) {
                        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
                        if (selectedNode != null) {
                            setSelectedItem(selectedNode);
                            hidePopup();
                            e.consume();
                        }
                    }
                } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    hidePopup();
                    e.consume();
                }
            }
        });
        
        // 设置整个 JComboBox 的 renderer
        this.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof DefaultMutableTreeNode) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                    value = node.getUserObject(); // 使用节点的用户对象作为显示内容
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        
        // 初始选择根节点
        setSelectedItem(root);
        
        System.out.println("JTreeComboBox初始化完成");

        
    }
    
    @Override
    public Object getSelectedItem() {
//        Object selected = super.getSelectedItem();
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
//        System.out.println("重写的getSelectedItem方法返回值: " + selected);
        return selectedNode;
    }
    
    
    
    @Override
    public void setSelectedItem(Object anObject) {
        System.out.println("设置选中项: " + anObject);
        suppressEvents = true;
        super.setSelectedItem(anObject);
        suppressEvents = false;
        
        // 更新树的选择状态
        System.out.println("选中项类型 = "+anObject.getClass().getTypeName());
        if (anObject instanceof DefaultMutableTreeNode) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) anObject;
            TreePath path = new TreePath(node.getPath());
            tree.setSelectionPath(path);
        }else {
            System.out.println("选中项:"+anObject+"不是DefaultMutableTreeNode类型，设置选中项失败！");
        }
        revalidate(); // 触发布局更新
        repaint();    // 触发重绘
    }
    
    public JTree getTree() {
        return tree;
    }
    
    private class TreeComboBoxUI extends BasicComboBoxUI {
        @Override
        protected ComboPopup createPopup() {
        	System.out.println("创建弹出框，树对象是否为null: " + (tree == null));
            return new TreeComboPopup(comboBox, tree);
        }
        
        @Override
        protected ListCellRenderer<Object> createRenderer() {
            return new ListCellRenderer<Object>() {
                private final DefaultListCellRenderer renderer = new DefaultListCellRenderer();
                
                @Override
                public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    if (value instanceof DefaultMutableTreeNode) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                        value = node.getUserObject();
                    }
                    return renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            };
        }
    }
    
    private static class TreeComboPopup extends BasicComboPopup {
        private JTree tree;
        
        public TreeComboPopup(JComboBox<?> comboBox, JTree tree) {
            super(comboBox);
            this.tree = tree;
            System.out.println("TreeComboPopup构造函数被调用，树对象是否为null: " + (tree == null));
            removeAll();
            setLayout(new BorderLayout());
            
            // 添加滚动面板包含树
            JScrollPane scrollPane = new JScrollPane(tree);
            scrollPane.setBorder(null);
            add(scrollPane, BorderLayout.CENTER);
            
            // 设置弹出框大小
            Dimension preferredSize = tree.getPreferredSize();
            preferredSize.width = Math.max(preferredSize.width, 200);
            preferredSize.height = Math.min(preferredSize.height, 200);
            preferredSize.height = 150;
            setPreferredSize(preferredSize);
        }
        
        @Override
        protected void configureList() {
            // 不使用默认的列表
        }
        
        @Override
        public void show() {
            super.show();
            // 展开根节点
            tree.expandPath(new TreePath(((DefaultMutableTreeNode) tree.getModel().getRoot()).getPath()));
        }
    }
    
    private static class TreeCellRenderer extends DefaultTreeCellRenderer {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                value = node.getUserObject();
            }
            return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        }
    }
}