package com.connor.ml.tcm.outfile.ML_010;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
//import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JButton;
//import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;

public class DbomTransitionToEbomSearchDialog extends AbstractAIFDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
//	private TCSession session;
	private DbomTransitionToEbomDialog parent;
	private JTable				impTable;
	private DefaultTableModel	impModel;
	private Map<String, JTextField>	searchMap;
	private JButton addBtn;
	private JButton delBtn;
	private JButton searchBtn;
	private JButton okBtn;
	private JButton cancelBtn;
	public String codeID;

	public DbomTransitionToEbomSearchDialog(TCSession session, DbomTransitionToEbomDialog parent, String[] head, String[][] tags) {
		super(parent, true);
//		this.session = session;
		this.parent = parent;
		searchMap = new LinkedHashMap<>();
		
		String[] tableHeader = new String[] { "AND/OR", "属性名称", "运算符", "搜索值" };
		int size = tableHeader.length;
		
		impModel = new DefaultTableModel(tableHeader, 0);
		impTable = new JTable() {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int row, int col) {
				if(row == 0 && col == 0)
					return false;
				return true;
			}
			@Override
			public TableCellRenderer getCellRenderer(int row, int column) {
				return super.getCellRenderer(row, column);
			}
		};
		impModel.setDataVector(tags, tableHeader);
		impTable.getTableHeader().setReorderingAllowed(false);
		impTable.setFillsViewportHeight(true);
		impTable.setEnabled(true);
//		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		impTable.setModel(impModel);
		int[] widths = { 100, 100, 80, 150 };
		TableColumnModel colModel = impTable.getColumnModel();
		for (int i = 0; i < size; i++) {
			colModel.getColumn(i).setPreferredWidth(widths[i]);
		}
		String[][] comboBoxItems = {{ "AND", "OR" }, head, { "=", "==", "!=" }, { "已勾选", "未勾选" }}; // 下拉框选项列表
		for(int i = 0; i < comboBoxItems.length; i++) {
	        TableColumn column = colModel.getColumn(i); // 获取第三列模型对象
//	        JComboBox<Object> comboBox = new JComboBox<>(comboBoxItems[i]);
//	        comboBox.setEditable(i == comboBoxItems.length - 1);
//	        column.setCellEditor(new DefaultCellEditor(comboBox));
	        column.setCellEditor(new TableCellComboBoxEditor(comboBoxItems[i], i == comboBoxItems.length - 1)); 
	        column.setCellRenderer(new DefaultTableCellRenderer());
	        // 设置编辑器到第三列模型对象上，这将允许在该列编辑时显示下拉框。如果你也想设置渲染器：
//	        column.setCellRenderer(new TableCellComboBoxRenderer(comboBoxItems[i])); 
	        // 设置渲染器到第三列模型对象上，这将允许在该列显示时显示下拉框。
		}
		impTable.setRowHeight(25);
		impTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
//		Container container = myframe.getContentPane();
		JPanel CPanel = new JPanel(new BorderLayout(10, 10));
		CPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
//		JPanel leftPanel = new JPanel(new BorderLayout(10, 10));
		JPanel msgPanel = new JPanel(new GridLayout(10,2,10,10));
		for(Entry<String, JTextField> e : searchMap.entrySet()) {
			JPanel panel = new JPanel(new BorderLayout());
			panel.add(BorderLayout.WEST, new JLabel(e.getKey()+"  "));
			panel.add(BorderLayout.EAST, e.getValue());
			msgPanel.add(panel);
		}
//		leftPanel.add(BorderLayout.NORTH, msgPanel);
		JPanel btnPanel = new JPanel(new FlowLayout());
		addBtn = new JButton("+");
		delBtn = new JButton("-");
		searchBtn = new JButton("搜索");
		okBtn = new JButton("确定");
		cancelBtn = new JButton("取消");
		btnPanel.add(addBtn);
		btnPanel.add(delBtn);
		btnPanel.add(searchBtn);
		btnPanel.add(okBtn);
		btnPanel.add(cancelBtn);
//		leftPanel.add(BorderLayout.SOUTH, btnPanel);
		JScrollPane tablePanel = new JScrollPane();
		tablePanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		tablePanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		tablePanel.setViewportView(impTable);
		CPanel.add(BorderLayout.SOUTH, btnPanel);
		CPanel.add(BorderLayout.CENTER, tablePanel);
		this.add(CPanel);
		
		addActionListener();
		
		setSize(750, 600);
		//awtContainer.setSize(730, 570);
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		setAlwaysOnTop(true);
		setVisible(true);
//		open();
	}
	
	public void run(){
		showDialog();
	}
	
	private void addActionListener() {
		addBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(impTable.getRowCount() > 0)
					impModel.addRow(new String[] { "AND" });
				else
					impModel.addRow(new String[] { "" });
			}
		});
		//final Shell dialog = shell;
		delBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(impTable.getRowCount() == 0)
					return;
				int[] rows = impTable.getSelectedRows();
				if(rows.length == 0)
					return;
				if(impTable.getCellEditor() != null)
					impTable.getCellEditor().stopCellEditing();
				for(int i = rows.length - 1; i >= 0; i--) {
					impModel.removeRow(rows[i]);
					if(rows[i] == 0 && impTable.getRowCount() > 0)
						impTable.setValueAt("", 0, 0);
				}
			}
		});
		searchBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(impTable.getCellEditor() != null)
					impTable.getCellEditor().stopCellEditing();
				ArrayList<String[]> list = new ArrayList<>();
				for(int i = 0, len = impTable.getRowCount(); i < len; i++) {
					String[] val = new String[4];
					for(int j = 0; j < 4; j++)
						val[j] = "" + impTable.getValueAt(i, j);
					list.add(val);
				}
				String[][] tags = list.toArray(new String[0][0]);
				parent.search(tags);
			}
		});
		
		okBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				/*
				int[] selected = impTable.getSelectedRows();
				if(selected==null || selected.length==0) {
					MessageBox.post(CodeIDDialog.this, "请搜索并选择零部件", "ERROR", MessageBox.ERROR);
					return;
				}
				parent.codeID = impTable.getValueAt(selected[0], codeCol).toString();
//				new Thread() {
//					public void run() {
//						combo.setText(text.replace("[CodeID]", codeID));
//					}
//				}.start();
				final String text = "[CodeID]<---->"+parent.codeID;
				final int w = new JLabel(text).getPreferredSize().width+10;
				
				Display display = Display.getDefault();
				display.asyncExec(new Runnable() {
				    public void run() {
//						String text = combo.getText().replaceAll("", "");
						combo.add(text);
						combo.setText(text);
						Rectangle r = combo.getBounds();
						combo.setBounds(r.x, r.y, w, r.height);
						combo.getParent().redraw();
						System.out.println("Text:"+combo.getText());
						parent.updateMap(false);
//						shell.getDisplay().sleep();
//						shell.close();
//						display.sleep();
				    }
				});*/
		    	dispose();
//				while (!display.isDisposed()) {
//					// Always gives a thread access error, but still calls async event: 
//					if (!display.readAndDispatch())
//						display.sleep();
//				}
			}
		});
		
		cancelBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
//				Display.getDefault().asyncExec(new Runnable() {
//				    public void run() {
//				    	parent.updateMap(false);
////						shell.getDisplay().sleep();
////						shell.close();
////						display.sleep();
//				    }
//				});
//		    	parent.updateMap(false);
		    	dispose();
//				shell.getDisplay().sleep();
			}
		});
	}

	public static TCComponentForm getItemRevisionMasterForm(TCComponentItemRevision revision) throws Exception {
		if (revision != null) {
			AIFComponentContext[] contexts = revision.getChildren("IMAN_master_form_rev");
			if (contexts != null && contexts.length > 0) {
				InterfaceAIFComponent component = contexts[0].getComponent();
				if (component instanceof TCComponentForm) {
					return (TCComponentForm) component;
				}
			}
		}
		return null;
	}
}