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

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTextField;

import com.teamcenter.rac.aifrcp.AifrcpPlugin;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentICO;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.ics.ICSKeyLov;
import com.teamcenter.rac.kernel.ics.ICSPropertyDescription;
import com.teamcenter.rac.kernel.ics.ICSView;
import com.teamcenter.rac.util.MessageBox;

import cn.com.origin.autocode.common.operations.SendToIcsOperation;
import cn.com.origin.autocode.newitem.generatcode.PackClassificationInfos;
import cn.com.origin.autocodemanager.common.tree.AbstractTreeData;

public class ORCreateICOObject {
	private TCSession session;
	private String rootICSID = "ICM";
	private String parentICSName = "";
	private String parentICSID = "";

	public ORCreateICOObject() {
		session = getSession();
	}

	public TCSession getSession() {
		if (session == null)
			session = (TCSession) AifrcpPlugin.getSessionService().getDefaultSession();
		return session;
	}

	private String getClassificationNode(AbstractTreeData treeData, String icsID) {
		AbstractTreeData parentNode = treeData.getParentTreeData();
		System.out.println(treeData.getPackCodeNodeInfo().getNode_name()+">>>>"+parentNode.getPackCodeNodeInfo().getNode_name());
		System.out.println("icsID=="+icsID);
		if ((parentNode != null) && (parentNode.getPackCodeNodeInfo().getNodeComponent() != null)) {
			System.out.println("parentNode!=null");
			icsID = getClassificationNode(parentNode, icsID);
			icsID = searchClassification(parentNode.getPackCodeNodeInfo().getNode_name(), icsID);
		}
		System.out.println("icsID>>"+icsID);
		return icsID;
	}

	private String getParentClassificationNode(AbstractTreeData treeData, String icsID) {
		String parentICSID = getClassificationNode(treeData, icsID);
		icsID = searchClassification(treeData.getPackCodeNodeInfo().getNode_name(), parentICSID);
		return icsID;
	}

	public void createTreeNodeICObject(AbstractTreeData parentTreeData, AbstractTreeData treeData, TCComponentItem item, Map<String, String> icoPropertyMap) {
		long time1 = System.nanoTime();
		System.out.println("当前层："+parentTreeData.getPackCodeNodeInfo().getNode_name());
//		String parentICSID = getParentClassificationNode(parentTreeData, rootICSID);
//		String icsID = searchClassification(treeData.getPackCodeNodeInfo().getNode_name(), parentICSID);
		String icsID = treeData.getPackCodeNodeInfo().getNode_desc();
		long time2 = System.nanoTime();
		System.out.println("查询分类ID用时(ms)： " + (time2 - time1) / 1000000);
		if (icsID.trim().length() == 0) {
			MessageBox.post("物料创建成功,但没有找到特征码为：【" + treeData.getPackCodeNodeInfo().getNode_name() + "】的分类", "提示",
					MessageBox.INFORMATION);
			return;
		}
		createICObject(treeData.getPackCodeNodeInfo().getNode_name(), icsID, item, icoPropertyMap);
	}

	public void createListNodeICObject(AbstractTreeData parentTreeData, String firstICOName, String currentICSName,
			TCComponentItem item, Map<String, String> icoPropertyMap) {
		long time1 = System.nanoTime();
		System.out.println("rootICSID:" + rootICSID);
		System.out.println("当前层："+parentTreeData.getPackCodeNodeInfo().getNode_name());
		String parentICSID = getParentClassificationNode(parentTreeData, rootICSID);
		System.out.println("parentICSID:" + parentICSID);
//		parentICSID="ICM0302";
		String icsID = searchClassification(firstICOName.trim(), parentICSID);
		long time2 = System.nanoTime();
		System.out.println("查询分类ID用时(ms)： " + (time2 - time1) / 1000000);
		if (icsID.trim().length() == 0) {
			MessageBox.post("物料创建成功,但没有找到特征码为：【" + currentICSName + "】的分类", "提示", MessageBox.INFORMATION);
			return;
		}
		createICObject(firstICOName, icsID, item, icoPropertyMap);
	}

	public void createICObject(ICSView icsView, PackClassificationInfos classificationInfos, TCComponent item) {
		long time1 = System.nanoTime();
		if (classificationInfos == null) {
			return;
		}

		if (classificationInfos.getIcsID().trim().length() == 0) {
			return;
		}

		HashMap<String, JComponent> propHashMap = classificationInfos.getPropertyMaps();
		HashMap<String, String> propValueHashMap = new HashMap<String, String>();
		String icsId = classificationInfos.getIcsID();
		if ((icsId == null) || (icsId.trim().length() == 0)) {
			MessageBox.post("物料创建成功,未找到对应分类节点!", "提示", MessageBox.INFORMATION);
			return;
		}
		if (propHashMap != null) {
			Set<String> propSet = propHashMap.keySet();
			Object[] keys = propSet.toArray();
			for (int i = 0; i < keys.length; i++) {
				if ((keys[i] != null) && (keys[i].toString().trim().length() > 0)) {
					Object propComponent = propHashMap.get(keys[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[0];
						}
					} else {
						if (propComponent instanceof String) {
							value = (String) propComponent;
						}
					}
					propValueHashMap.put((String) keys[i], value);
				}
			}
		}

		// System.out.println("icsId==============="+icsId);
		try {
			if ((propValueHashMap == null) || (propValueHashMap.size() == 0)) {
				String[] names = new String[] {};
				String[] values = new String[] {};
				new SendToIcsOperation().sendItemToClassification((TCComponentItem) item, icsId, names, values);
			} else {
				Set<String> set = propValueHashMap.keySet();
				Object[] names = set.toArray();
				String[] values = new String[names.length];
				for (int i = 0; i < names.length; i++) {
					values[i] = (String) propValueHashMap.get(names[i]);
				}
				boolean flag = new SendToIcsOperation().sendItemToClassification((TCComponentItem) item, icsId, names,
						values);

				if (flag) {
					TCComponentICO[] icos = item.getClassificationObjects();
					if ((icos != null) && (icos.length > 0)) {
						Map attMap = item.getClassificationAttributes();
						TCComponentICO ico1 = icos[0];
						StringBuffer sb = new StringBuffer();

						ICSPropertyDescription[] icsDs = ico1.getICSPropertyDescriptors();
						int length = icsDs.length;
						for (int m = 0; m < length; m++) {
							String attValue = (String) attMap.get(icsDs[m].getDisplayName());
							// System.out.println("attValue=== " + attValue);
							// System.out.println("icsDs[m].getDisplayName()=== " +
							// icsDs[m].getDisplayName());

							if ((attValue != null) && (attValue.length() > 0)) {
								ICSKeyLov keylov = icsDs[m].getFormat().getKeyLov();
								if (keylov != null) {
									int len = icsDs[m].getFormat().getKeyLov().getDisplayValues().length;
									if (len > 0) {
										for (int k = 0; k < len; k++) {
											// System.out.println("keylov.getKeys()[k]== " +
											// keylov.getKeys()[k].toString());
											// System.out.println("keylov.getValueOfKey()[k]== " +
											// keylov.getValueOfKey(keylov.getKeys()[k]).toString());
											if (attValue.equals(keylov.getKeys()[k].toString())) {
												attValue = keylov.getValueOfKey(keylov.getKeys()[k]).toString();
												break;
											}
										}
									}
								}
							}

							if ((attValue != null) && (((String) attValue).trim().length() > 0)) {
								if (sb.toString().length() > 0) {
									sb.append("_");
								}
								sb.append(attValue);
							}
						}
						TCComponent child = ((TCComponentItem) item).getLatestItemRevision()
								.getRelatedComponent("IMAN_master_form_rev");
						TCComponentForm form = (TCComponentForm) child;
						form.setProperty("z9PI_MATERIALTXT", sb.toString());
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		long time2 = System.nanoTime();
		System.out.println("发送到分类用时(ms)： " + (time2 - time1) / 1000000);
	}

	public void createICObject(String currentICSName, String icsId, TCComponent item, Map<String, String> icoPropertyMap) {
		long time1 = System.nanoTime();
		try {
			if ((icoPropertyMap.size() == 0) || (icoPropertyMap == null)) {
				String[] names = new String[] {};
				String[] values = new String[] {};
				System.out.println("icoPropertyMap == null");
				new SendToIcsOperation().sendItemToClassification((TCComponentItem) item, icsId, names, values);
			} else {
				Set<String> set = icoPropertyMap.keySet();
				Object[] names = set.toArray();
				String[] values = new String[names.length];
				for (int i = 0; i < names.length; i++) {
					values[i] = icoPropertyMap.get(names[i]);
				}
				System.out.println("icoPropertyMap:"+Arrays.toString(names)+"=="+Arrays.toString(values));
				new SendToIcsOperation().sendItemToClassification((TCComponentItem) item, icsId, names, values);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			MessageBox.post("物料创建成功，但对象发送到分类失败!", "提示", MessageBox.INFORMATION);
		}
		long time2 = System.nanoTime();
		System.out.println("发送到分类用时(ms)： " + (time2 - time1) / 1000000);
	}

	public String searchClassification(String icsName, String rootId) {
		String icsId = new SendToIcsOperation().getClassificationByName(rootId, icsName);
		
		System.out.println("icsId:" + icsId);
		System.out.println("icsName:"+icsName);
		if ((parentICSName.equals(icsName)) && (icsId.trim().length() == 0)) {
			icsId = parentICSID;
		}
		parentICSName = icsName;
		parentICSID = icsId;
		return icsId;
	}
}