package cn.com.origin.autocode.newitem.system;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.TitledBorder;

import org.eclipse.swt.widgets.Display;

import cn.com.origin.autocode.classification.ClassificationPropertyNames;
import cn.com.origin.autocode.classification.panels.CreateClassificationPanel;
import cn.com.origin.autocode.newitem.generatcode.NewCodeItemDialog;
import cn.com.origin.autocode.newitem.generatcode.PackClassificationInfos;
import cn.com.origin.autocodemanager.common.TCPreferenceUitl;

import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.commands.newitem.AbstractNewItemPanel;
import com.teamcenter.rac.commands.newitem.ItemInfoPanel;
import com.teamcenter.rac.commands.revise.RevisionNamingRuleHelper;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.Separator;
import com.teamcenter.rac.util.VerticalLayout;
import com.teamcenter.services.rac.core.DataManagementService;

public class ORItemInfoPanel extends ItemInfoPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String newItemID = "";
	private String newItemRev = "";
	private String newItemName = "";
	private JSplitPane classificationPanel;
	private JScrollPane tclassificationScrollPane;
	private String origin_newItemMustClassificationTypes = "origin_newItemMustClassificationTypes";
	private String origin_newItemRevCanEditTypes = "origin_newItemRevCanEditTypes";

	public String getNewItemID() {
		return newItemID;
	}

	public void setNewItemID(String newItemID) {
		this.newItemID = newItemID;
	}

	public String getNewItemRev() {
		return newItemRev;
	}

	public void setNewItemRev(String newItemRev) {
		this.newItemRev = newItemRev;
	}

	public String getNewItemName() {
		return newItemName;
	}

	public void setNewItemName(String newItemName) {
		this.newItemName = newItemName;
	}

	public ORItemInfoPanel(TCSession arg0, AbstractNewItemPanel arg1) {
		super(arg0, arg1);
	}

	public ORItemInfoPanel(Frame arg0, TCSession arg1, AbstractNewItemPanel arg2) {
		super(arg0, arg1, arg2);
	}

	public ORItemInfoPanel(Frame arg0, TCSession arg1, AbstractNewItemPanel arg2, boolean arg3) {
		super(arg0, arg1, arg2, arg3);
	}

	public ORItemInfoPanel(Frame arg0, TCSession arg1, AbstractNewItemPanel arg2, boolean arg3, boolean arg4, boolean arg5) {
		super(arg0, arg1, arg2, arg3, arg4, arg5);
	}

	public void initPanel() {
		getPreferenceSettings();
		setLayout(new VerticalLayout(5, 2, 2, 2, 2));
		infoLabel = new JLabel(getPageTitle(), getPageIcon(), 2);
		infoLabel.setForeground(Color.BLUE);
		buildBaseItemInfoPanel();
		otherPropertyPanel = buildStaticPropertiesPanel();
		nonPropertiesPanel = buildNonPropertiesPanel();
		add("top.bind.left.top", infoLabel);
		add("top.bind", new Separator());
		add("top.bind.left.top", namingAndNumberingPanel);
		add("top.bind.left.top", itemInfoPanel);
		add("top.bind.left.top", otherPropertyPanel);
		add("bottom.nobind.right.top", nonPropertiesPanel);

		classificationPanel = buildItemClassficationPanel();

		tclassificationScrollPane = new JScrollPane();
		tclassificationScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		tclassificationScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		tclassificationScrollPane.getViewport().setView(classificationPanel);
		Dimension dimension = classificationPanel.getPreferredSize();
		tclassificationScrollPane.setPreferredSize(new Dimension(dimension.width, dimension.height));
		add("top.bind.left.top", tclassificationScrollPane);

		if (itemPanel.getDialog().isAutoExposureForCreateEnabled()) {
			applyMetaModelSettings(itemPanel.getCreateDefinition());
		}
		setOptions();
		setFocus();
	}

	private boolean validateClassification(PackClassificationInfos classificationInfos) {
		HashMap<String, JComponent> propHashMap = classificationInfos.getPropertyMaps();
		List icsPropList = classificationInfos.getIcsPropList();
//		System.out.println("propHashMap==============" + propHashMap);
//		System.out.println("icsPropList==============" + icsPropList);
		if (propHashMap != null) {
//			Set<String> propSet = propHashMap.keySet();
			StringBuffer sb = new StringBuffer();
			// Object[] keys = propSet.toArray();
			for (int i = 0; i < icsPropList.size(); i++) {
				// for (int i = 0; i < keys.length; i++) {
				// if ((keys[i] != null) && (keys[i].toString().trim().length() > 0)) {
				if ((icsPropList.get(i) != null) && (icsPropList.get(i).toString().trim().length() > 0)) {

					Object propComponent = propHashMap.get(icsPropList.get(i));

					String value = "";
					if (propComponent instanceof JTextField) {
						value = ((JTextField) propComponent).getText();
					} else if (propComponent instanceof JComboBox) {
						Object value1 = ((JComboBox) propComponent).getSelectedItem();
						if (value1 == null) {
							continue;
						}
						value = value1.toString();
						String[] values = value.trim().split(" ");
						if (values.length == 3) {
							value = values[1];
						}

					} else {
						if (propComponent instanceof String) {
							value = (String) propComponent;
						}
					}
					if ((value != null) && (((String) value).trim().length() > 0)) {
						if (sb.toString().length() > 0) {
							sb.append("_");
						}
						sb.append(value);
					}
				}
			}
			try {
				if (!"".equals(sb.toString())) {
					TCTextService textService = session.getTextService();
					String key[] = new String[] { textService.getTextValue("z9PI_MATERIALTXT") };
					String value[] = new String[] { sb.toString() };
					TCComponent[] items = query(session, itemPanel.selectedItemType, key, value);
					for (int i = 0; i < items.length; i++) {
						if (!((TCComponentItem) items[i]).getProperty("item_id").equals(idTextField.getText().trim())) {
							MessageBox.post("对象长描述已经存在，不能重复,请重新修改分类！", "INFO", MessageBox.ERROR);
							return false;
						}
					}
				}
			} catch (TCException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public TCComponent[] query(TCSession session, String query_name, String[] arg1, String[] arg2) {
		TCComponentContextList imancomponentcontextlist = null;
		TCComponent[] component = (TCComponent[]) null;
		try {
			TCComponentQueryType imancomponentquerytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			TCComponentQuery imancomponentquery = (TCComponentQuery) imancomponentquerytype.find(query_name);
			TCTextService imantextservice = session.getTextService();
			String[] queryAttribute = new String[arg1.length];
			for (int i = 0; i < arg1.length; ++i)
				queryAttribute[i] = imantextservice.getTextValue(arg1[i]);
			String[] queryValues = new String[arg2.length];
			for (int i = 0; i < arg2.length; ++i)
				queryValues[i] = arg2[i];
			imancomponentcontextlist = imancomponentquery.getExecuteResultsList(queryAttribute, queryValues);
			component = imancomponentcontextlist.toTCComponentArray();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return component;
	}

	public boolean validateId() {
		String name = nameTextField.getText();
		if ((name != null) && (name.length() > 40)) {
			MessageBox.post("名称长度超过40个字，请修改！", "INFO", MessageBox.WARNING);
			itemPanel.finishPanel.controlWizardPanel.setPanel(1);
			return false;
		}
		boolean isValidate = super.validateId();
		if (TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, origin_newItemMustClassificationTypes, this.itemPanel.dialog.getItemType())) {
			PackClassificationInfos classificationInfos = ((ORNewItemDialog) this.itemPanel.getDialog()).getClassificationInfos();
			if (classificationInfos == null) {
				MessageBox.post("该类型必须选择分类才可以创建!", "INFO", MessageBox.WARNING);
				return false;
			}
			String icsID = classificationInfos.getIcsID();
			if ((icsID.equals("")) || (classificationInfos.equals(null))) {
				MessageBox.post("该类型必须选择分类才可以创建!", "INFO", MessageBox.WARNING);
				return false;
			}
			if (icsID.equals("Abstract")) {
				MessageBox.post("您选择的分类节点为抽象类，请选择实例类!", "INFO", MessageBox.WARNING);
				return false;
			}

			if (!validateClassification(classificationInfos)) {
				return false;
			}

		}

		List<Object> notNullClassificationPropTextField = ((ORNewItemDialog) this.itemPanel.getDialog()).getNotNullClassificationPropTextField();
		if (notNullClassificationPropTextField != null) {
			for (int i = 0; i < notNullClassificationPropTextField.size(); i++) {
				Object jtextField = notNullClassificationPropTextField.get(i);
				if (jtextField instanceof JTextField) {
					JTextField textField = (JTextField) jtextField;
					String text = textField.getText();
					if ((text == null) || (text.trim().length() == 0)) {
						MessageBox.post("分类属性中含有(*)的为必填项，必须填写！", "INFO", MessageBox.WARNING);
						return false;
					}
				} else if (jtextField instanceof JComboBox) {
					JComboBox comboBox = (JComboBox) jtextField;
					int index = comboBox.getSelectedIndex();
					if (index == -1) {
						MessageBox.post("分类属性中含有(*)的为必填项，必须填写！", "INFO", MessageBox.WARNING);
						return false;
					}
				}
			}
		}
		return isValidate;
	}

	public void addNotify() {
		super.addNotify();
		setButtons();

		String origin_newItemShowClassificationTypes = "origin_newItemShowClassificationTypes";
		String[] types = TCPreferenceUitl.getListPreference(session, 4, origin_newItemShowClassificationTypes);
		if ((types.length > 0) && (types != null)) {
			if (TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, origin_newItemShowClassificationTypes, itemPanel.selectedItemType.trim())) {
				// add("top.bind.left.top", classificationPanel);
				tclassificationScrollPane.setVisible(true);
				this.validate();
				this.repaint();
			} else {
				// this.remove(classificationPanel);
				tclassificationScrollPane.setVisible(false);
				this.validate();
				this.repaint();
			}
		} else {
			String origin_isNewItemShowClassification = "origin_isNewItemShowClassification";
			if (TCPreferenceUitl.isTrueTCPreferenceValue(session, origin_isNewItemShowClassification)) {
				// add("top.bind.left.top", classificationPanel);
				tclassificationScrollPane.setVisible(true);
				this.validate();
				this.repaint();
			} else {
				// this.remove(classificationPanel);
				tclassificationScrollPane.setVisible(false);
				this.validate();
				this.repaint();
			}
		}
	}

	public JSplitPane buildItemClassficationPanel() {
		JSplitPane jsp = new JSplitPane();
		CreateClassificationPanel createClassificationPanel = new CreateClassificationPanel(this.itemPanel.dialog);
		try {
			// JScrollPane treePanel =
			// createClassificationPanel.CreateClassificationInfoPanel("ICM",
			// "Classification root", ClassificationPropertyNames.icsGroupType);
			JScrollPane treePanel = createClassificationPanel.CreateRootClassificationInfoPanel("ICM", "Classification root", ClassificationPropertyNames.icsGroupType);
			JScrollPane propertyPanel = createClassificationPanel.createPropertyInfoPanel();
			// jsp.setPreferredSize(new Dimension(400, 350));
			jsp.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), "请选择分类"));
			jsp.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
			jsp.setDividerLocation(0.5);
			jsp.setDividerSize(7);
			jsp.setLeftComponent(treePanel);
			jsp.setRightComponent(propertyPanel);
			jsp.setAutoscrolls(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsp;
	}

	public void getAssignedIds() {
		try {
			// SwingUtilities.invokeLater(new Runnable(){
			// public synchronized void run() {
			// }
			// });
			String origin_assignIDNeedCodeTypes = "origin_assignIDNeedCodeTypes";
			if (TCPreferenceUitl.getListPreference(session, 4, origin_assignIDNeedCodeTypes).length > 0) {
				if (!TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, origin_assignIDNeedCodeTypes, itemPanel.selectedItemType)) {
					super.getAssignedIds();
					return;
				}
			}

			// Display.getDefault().syncExec(new Runnable() {

			Display.getDefault().syncExec(new Runnable() {
				public void run() {

					String itemType = itemPanel.selectedItemType;
					new NewCodeItemDialog(ORItemInfoPanel.this, AIFDesktop.getActiveDesktop().getShell(), itemType).open();
					if ((newItemID.trim().length() > 0) || (newItemRev.trim().length() > 0)) {
						idTextField.setText(newItemID);

						int ai[] = RevisionNamingRuleHelper.getInstance().getRevisionNamingRuleFormats();
						int i = ai[0];
						int j = ai[1];
						String s = null;
						Object obj1;
						DataManagementService datamanagementservice = DataManagementService.getService(session);
						com.teamcenter.services.rac.core._2006_03.DataManagement.GenerateItemIdsAndInitialRevisionIdsProperties agenerateitemidsandinitialrevisionidsproperties[] = new com.teamcenter.services.rac.core._2006_03.DataManagement.GenerateItemIdsAndInitialRevisionIdsProperties[1];
						agenerateitemidsandinitialrevisionidsproperties[0] = new com.teamcenter.services.rac.core._2006_03.DataManagement.GenerateItemIdsAndInitialRevisionIdsProperties();
						agenerateitemidsandinitialrevisionidsproperties[0].item = null;
						agenerateitemidsandinitialrevisionidsproperties[0].itemType = itemPanel.selectedItemType;
						agenerateitemidsandinitialrevisionidsproperties[0].count = 1;
						obj1 = datamanagementservice.generateItemIdsAndInitialRevisionIds(agenerateitemidsandinitialrevisionidsproperties);

						Map map = ((com.teamcenter.services.rac.core._2006_03.DataManagement.GenerateItemIdsAndInitialRevisionIdsResponse) (obj1)).outputItemIdsAndInitialRevisionIds;
						Iterator iterator = map.entrySet().iterator();
						if (iterator.hasNext()) {
							java.util.Map.Entry entry = (java.util.Map.Entry) iterator.next();
							com.teamcenter.services.rac.core._2006_03.DataManagement.ItemIdsAndInitialRevisionIds aitemidsandinitialrevisionids[] = (com.teamcenter.services.rac.core._2006_03.DataManagement.ItemIdsAndInitialRevisionIds[]) (com.teamcenter.services.rac.core._2006_03.DataManagement.ItemIdsAndInitialRevisionIds[]) entry
									.getValue();
							com.teamcenter.services.rac.core._2006_03.DataManagement.ItemIdsAndInitialRevisionIds itemidsandinitialrevisionids = aitemidsandinitialrevisionids[0];
							s = itemidsandinitialrevisionids.newItemId;
							if (i != 0) {
								if (j == 0)
									assignRevIdWithRevisionRule();
							} else {
								String s1 = itemidsandinitialrevisionids.newRevId;
								revTextField.setText(s1);
							}
						}

						// revTextField.setText(newItemRev);
						nameTextField.setText(newItemName);
						nameTextField.requestFocusInWindow();
					} else {
						try {
							// TCComponentItemType localTCComponentItemType;
							// localTCComponentItemType = (TCComponentItemType)
							// session.getTypeComponent(itemPanel.selectedItemType);
							// String newItemID =
							// localTCComponentItemType.getNewID();
							// idTextField.setText(newItemID);
							// revTextField.setText(localTCComponentItemType.getNewRev(null));
							idTextField.setText("");
							revTextField.setText("");
							nameTextField.requestFocusInWindow();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					idTextField.setEditable(false);
					if (TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, origin_newItemRevCanEditTypes, itemPanel.selectedItemType)) {
						revTextField.setEditable(true);
					} else {
						revTextField.setEditable(false);
					}
					return;

				}
			});

			// Display.getDefault().syncExec(new Runnable() {
			// public void run() {}
			// });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
