/**
 * @author tyl
 * @Action  ini
 * 2011-4-13
 */
package cn.com.origin.autocode.views.itemtypeview;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.ImageIcon;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

import cn.com.origin.autocode.common.operations.ClassificationOperation;
import cn.com.origin.autocodemanager.common.AutoCodeConstants;
import cn.com.origin.autocodemanager.common.AutoCodeManagerPropertyName;
import cn.com.origin.autocodemanager.common.CacheImage;
import cn.com.origin.autocodemanager.common.operations.PackCodeNodeInfo;
import cn.com.origin.autocodemanager.common.operations.TreeAndListCodeOperation;
import cn.com.origin.autocodemanager.common.progress.ExpandProgressBar;
import cn.com.origin.autocodemanager.common.tree.AbstractTreeData;

import com.teamcenter.rac.common.create.DisplayTypeInfo;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;

public class NewItemClassificationView extends CreateClassificationView {
	private int count = 0;
	private String showItemType = "";
	private  Boolean isFilterType = false;

	public NewItemClassificationView(Composite composite, String rootName) {
		super(composite, rootName);
	}

	public NewItemClassificationView(Composite composite, String rootName,
			String showItemType) {
		super(composite, rootName);
		this.showItemType = showItemType;
	}
	public NewItemClassificationView(Composite composite, String rootName,
			String showItemType,Boolean isFilterType) {
		super(composite, rootName);
		this.showItemType = showItemType;
		this.isFilterType = isFilterType;
	}

	public void createTree(Composite parent, String rootName) {
		Composite composite = new Composite(parent, 0);
		FillLayout fillLayout = new FillLayout();
		composite.setLayout(fillLayout);
		treeViewer = new TreeViewer(composite, SWT.BORDER);
		tree = treeViewer.getTree();
		initTree(rootName);
		treeViewer.expandToLevel(1);
		tree.addTreeListener(new TreeListener() {
			public void treeCollapsed(TreeEvent treeEvent) {
			}

			public void treeExpanded(TreeEvent treeEvent) {
				// MessageBox.post("展开","INFO",MessageBox.ERROR);
				AbstractTreeData codeData = (AbstractTreeData) treeEvent.item
						.getData();
				if (codeData == null) {
					return;
				}
				TCComponent component = codeData.getPackCodeNodeInfo()
						.getNodeComponent();
				if (component != null) {
					if ((component != null)
							&& (codeData.getPackCodeNodeInfo().is_lock)) {
						codeData.setTreeAutoCodeNodeChildren(null);
						return;
					}
				}
				expandNode(codeData);
			}
		});

		tree.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				AbstractTreeData selectedData = (AbstractTreeData) e.item
						.getData();

				if (count == 0) {
					count++;
					return;
				}
				if (selectedData == null) {
					return;
				}
				if ((!treeViewOperation.isRuleRootNode(selectedData))
						&& (!selectedData
								.getPackCodeNodeInfo()
								.getNode_type()
								.equals(AutoCodeManagerPropertyName.ComponentName))) {
					return;
				}
				if (selectedData.isChildrenLoader()) {
					return;
				}

				TCComponent component = selectedData.getPackCodeNodeInfo()
						.getNodeComponent();
				if (component != null) {
					if (selectedData.getPackCodeNodeInfo().is_lock) {
						selectedData.setTreeAutoCodeNodeChildren(null);
						return;
					}
				}
				expandNode(selectedData);

			}
		});
	}

	public void expandNode(AbstractTreeData codeData) {
		if (codeData == null) {
			return;
		}
		long time1 = System.nanoTime();
		AbstractTreeData[] codeDatas = new AbstractTreeData[] { codeData };
		ExpandProgressBar expandProgressBar = new ExpandProgressBar(Display
				.getDefault().getActiveShell(), "正在打开", this, codeDatas);
		try {
			expandProgressBar.expand();
		} catch (Exception e) {
			e.printStackTrace();
		}
		long time2 = System.nanoTime();
		System.out.println("加载【"
				+ codeData.getPackCodeNodeInfo().getNode_name() + "】节点用时(ms)： "
				+ (time2 - time1) / 1000000);
	}

	public Map<String, AbstractTreeData> getItemTypeMaps(
			AbstractTreeData autoCodeData, HashMap<?, ?> hashMap) {
		Map<String, AbstractTreeData> itemTypesMap = new HashMap<String, AbstractTreeData>();
		if (hashMap != null && hashMap.size() > 0) {
			Set<?> set = hashMap.keySet();
			Object obj[] = set.toArray();
			for (int m = 0; m < obj.length; m++) {
				AbstractTreeData treeData = null;
				DisplayTypeInfo displaytypeinfo = (DisplayTypeInfo) obj[m];
				String childrenNodeName = displaytypeinfo.getDisplayTypeName();
				// ConvertibaleImageIcon s = (ConvertibaleImageIcon)
				// hashMap.get(displaytypeinfo);
				// ImageDescriptor imagedes = s.getImageDescriptor();
				// Image image = imagedes.createImage();
				System.out.println("getTypeName============="
						+ displaytypeinfo.getTypeName());
				System.out.println("getDisplayTypeName============="
						+ displaytypeinfo.getDisplayTypeName());
				System.out.println("displaytypeinfo============="
						+ displaytypeinfo);

				ImageIcon icon = (ImageIcon) hashMap.get(displaytypeinfo);
				BufferedImage bufferedImage = CacheImage.getBufferedImage(icon);
				ImageData imageData = CacheImage.getImageData(bufferedImage);
				Image image = new Image(null, imageData);

				treeData = new AbstractTreeData(autoCodeData, null, image,
						childrenNodeName, displaytypeinfo.getTypeName(),
						AutoCodeManagerPropertyName.ItemName, false);
				treeData.setChildrenLoader(true);
				itemTypesMap.put(childrenNodeName, treeData);
			}
		}
		return itemTypesMap;
	}

	private AbstractTreeData getShowItemType(AbstractTreeData parentTreeData) {
		ClassificationOperation classificationOperation = new ClassificationOperation();
		try {
			TCComponent[] tccomponents = null;
			HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
					parentTreeData.getPackCodeNodeInfo().getNode_name());
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_grant_groups,
					currentGroup.getObjectString());
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_grant_roles,
					currentRole.getObjectString());
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_grant_users,
					currentUser.getObjectString());
			tccomponents = classificationOperation
					.searchClassificationNodes(hashMap);
			if ((tccomponents == null) || (tccomponents.length == 0)) {
				return null;
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (TCException e) {
			e.printStackTrace();
		}
		return parentTreeData;
	}

	private AbstractTreeData getSegmentNode(AbstractTreeData parentTreeData) {
		ClassificationOperation classificationOperation = new ClassificationOperation();
		boolean isShow = false;
		try {
			TCComponent[] tccomponents = null;
			HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
					parentTreeData.getPackCodeNodeInfo().getNode_name());
			tccomponents = classificationOperation
					.searchClassificationSegments(hashMap);
			if (tccomponents == null) {
				return parentTreeData;
			}
			List<TCComponent> showSegments = new ArrayList<TCComponent>();
			hashMap.put(
					AutoCodeManagerPropertyName.ClassificationCodeNode_segment,
					"");
			TCComponent[] userComponents = classificationOperation
					.searchClassificationUsers(hashMap);
			TCComponentGroup paretnGroup = (TCComponentGroup) currentGroup
					.getReferenceProperty("parent");
			if (userComponents != null) {
				for (int k = 0; k < userComponents.length; k++) {
					if (userComponents[k] == null) {
						continue;
					}
					userComponents[k].refresh();
					if ((userComponents[k].equals(currentGroup))
							|| (userComponents[k].equals(currentRole))
							|| (userComponents[k].equals(currentUser))) {
						isShow = true;
						break;
					}
					if (userComponents[k].equals(paretnGroup)) {
						isShow = true;
						break;
					}
					TCComponentGroup paretnGroup2 = (TCComponentGroup) currentGroup
							.getReferenceProperty("parent");
					if (userComponents[k].equals(paretnGroup2)) {
						isShow = true;
						break;
					}
				}
			}
			if (!isShow) {
				for (int k = 0; k < tccomponents.length; k++) {
					isShow = false;
					if (tccomponents[k] == null) {
						continue;
					}
					String segmentName = tccomponents[k].getUid();
					HashMap<Object, Object> hashMap2 = new HashMap<Object, Object>();
					hashMap2.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
							parentTreeData.getPackCodeNodeInfo().getNode_name());
					hashMap2.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_segment,
							segmentName);
					TCComponent[] usertccomponents2 = classificationOperation
							.searchClassificationUsers(hashMap2);
					if (usertccomponents2 == null) {
						continue;
					}
					for (int m = 0; m < usertccomponents2.length; m++) {
						if (usertccomponents2[m] == null) {
							continue;
						}
						if ((usertccomponents2[m].equals(currentGroup))
								|| (usertccomponents2[m].equals(currentRole))
								|| (usertccomponents2[m].equals(currentUser))) {
							isShow = true;
							break;
						}
						if (usertccomponents2[m].equals(paretnGroup)) {
							isShow = true;
							break;
						}
						TCComponentGroup paretnGroup2 = (TCComponentGroup) currentGroup
								.getReferenceProperty("parent");
						if (usertccomponents2[m].equals(paretnGroup2)) {
							isShow = true;
							break;
						}
					}
					if (isShow) {
						showSegments.add(tccomponents[k]);
					}
				}
			} else {
				for (int k = 0; k < tccomponents.length; k++) {
					showSegments.add(tccomponents[k]);
				}
			}
			if (showSegments.size() == 0) {
				return parentTreeData;
			}
			AbstractTreeData autoCodeDataTCComs[] = new AbstractTreeData[showSegments
					.size()];
			for (int k = 0; k < showSegments.size(); k++) {
				PackCodeNodeInfo packCodeNodeInfo = treeAndListCodeOperation
						.getTreeAndListStringValue(
								showSegments.get(k),
								AutoCodeManagerPropertyName.searchTreeAndListCodeNodePropNames);
				autoCodeDataTCComs[k] = new AbstractTreeData(parentTreeData,
						packCodeNodeInfo);
				if (!packCodeNodeInfo.is_root) {
					autoCodeDataTCComs[k]
							.setTreeAutoCodeNodeChildren(new AbstractTreeData[] { new AbstractTreeData() });
				} else {
					setParentTreeNode(parentTreeData, autoCodeDataTCComs[k]);
				}
			}
			parentTreeData.setChildrenLoader(true);
			parentTreeData.setTreeAutoCodeNodeChildren(autoCodeDataTCComs);
			treeViewer.refresh(parentTreeData);
			tree.redraw();
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (TCException e) {
			e.printStackTrace();
		}
		return parentTreeData;
	}

	private void setParentTreeNode(AbstractTreeData parentNode, AbstractTreeData childrenNode) {
		try {
			TCComponent[] tccomponents = null;
			HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
			if (childrenNode.getPackCodeNodeInfo().getNodeComponent() != null) {
				hashMap.put(
						AutoCodeManagerPropertyName.CodeRelation_current_node,
						childrenNode.getPackCodeNodeInfo().getNodeComponent().getUid());
				TreeAndListCodeOperation treeAndListCodeOperation = new TreeAndListCodeOperation();
				tccomponents = treeAndListCodeOperation.searchParentTreeOrListNodes(hashMap);
			} else {
				tccomponents = null;
			}
			if (tccomponents != null && tccomponents.length > 0) {
				AbstractTreeData childrenNode2 = childrenNode;
				for (int k = tccomponents.length - 1; k >= 0; k--) {
					if (tccomponents[k] == null) {
						continue;
					}
					PackCodeNodeInfo packCodeNodeInfo = treeAndListCodeOperation.getTreeAndListStringValue(
							tccomponents[k], AutoCodeManagerPropertyName.searchTreeAndListCodeNodePropNames);
					AbstractTreeData treeData = new AbstractTreeData(null, packCodeNodeInfo);
					System.out.println(childrenNode2.getPackCodeNodeInfo().getNode_name()+">>1>>"+treeData.getPackCodeNodeInfo().getNode_name());
					childrenNode2.setParentTreeData(treeData);
					childrenNode2 = treeData;
				}
				System.out.println(childrenNode2.getPackCodeNodeInfo().getNode_name()+">>2>>"+parentNode.getPackCodeNodeInfo().getNode_name());
				childrenNode2.setParentTreeData(parentNode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void createOrgAutoCodeNodeChildren(AbstractTreeData[] codeDatas)
			throws Exception {
		if (codeDatas != null && codeDatas.length > 0) {
			for (int i = 0; i < codeDatas.length; i++) {
				AbstractTreeData autoCodeData = (AbstractTreeData) codeDatas[i];
				if (autoCodeData == null) {
					continue;
				}
				String nodeType = autoCodeData.getPackCodeNodeInfo()
						.getNode_type();
				if (nodeType.equals(AutoCodeManagerPropertyName.ComponentName)) {
					//

					String[] strs = Util.getCustomType(this.session);
					if (strs == null || strs.length == 0) {
						strs = AutoCodeConstants.as1;
					}
					HashMap<?, ?> hashMap = (HashMap<?, ?>) businessType
							.loadTypes(strs, AutoCodeConstants.as2);
					Map<String, AbstractTreeData> itemTypesMap = new HashMap<String, AbstractTreeData>();
					List<AbstractTreeData> typeList = new ArrayList<AbstractTreeData>();
					if ((showItemType != null)
							&& (showItemType.trim().length() > 0)) {
						if (hashMap != null && hashMap.size() > 0) {
							Set<?> set = hashMap.keySet();
							Object obj[] = set.toArray();
							for (int m = 0; m < obj.length; m++) {
								AbstractTreeData treeData = null;
								DisplayTypeInfo displaytypeinfo = (DisplayTypeInfo) obj[m];
								String childrenNodeName = displaytypeinfo
										.getDisplayTypeName();
								if(this.isFilterType){
									if (!displaytypeinfo.getTypeName().trim()
											.equals(showItemType)) {
										// ConvertibaleImageIcon s =
										// (ConvertibaleImageIcon)
										// hashMap.get(displaytypeinfo);
										// ImageDescriptor imagedes =
										// s.getImageDescriptor();
										// Image image = imagedes.createImage();

										ImageIcon icon = (ImageIcon) hashMap
												.get(displaytypeinfo);
										BufferedImage bufferedImage = CacheImage
												.getBufferedImage(icon);
										ImageData imageData = CacheImage
												.getImageData(bufferedImage);
										Image image = new Image(null, imageData);

										System.out
												.println("getTypeName============="
														+ displaytypeinfo
																.getTypeName());
										System.out
												.println("getDisplayTypeName============="
														+ displaytypeinfo
																.getDisplayTypeName());
										System.out
												.println("displaytypeinfo============="
														+ displaytypeinfo);

										treeData = new AbstractTreeData(
												autoCodeData,
												null,
												image,
												childrenNodeName,
												displaytypeinfo.getTypeName(),
												AutoCodeManagerPropertyName.ItemName,
												false);
										treeData.setChildrenLoader(true);
										itemTypesMap
												.put(childrenNodeName, treeData);
									}
								}
								else if (displaytypeinfo.getTypeName().trim()
										.equals(showItemType)) {
									// ConvertibaleImageIcon s =
									// (ConvertibaleImageIcon)
									// hashMap.get(displaytypeinfo);
									// ImageDescriptor imagedes =
									// s.getImageDescriptor();
									// Image image = imagedes.createImage();

									ImageIcon icon = (ImageIcon) hashMap
											.get(displaytypeinfo);
									BufferedImage bufferedImage = CacheImage
											.getBufferedImage(icon);
									ImageData imageData = CacheImage
											.getImageData(bufferedImage);
									Image image = new Image(null, imageData);

									System.out
											.println("getTypeName============="
													+ displaytypeinfo
															.getTypeName());
									System.out
											.println("getDisplayTypeName============="
													+ displaytypeinfo
															.getDisplayTypeName());
									System.out
											.println("displaytypeinfo============="
													+ displaytypeinfo);

									treeData = new AbstractTreeData(
											autoCodeData,
											null,
											image,
											childrenNodeName,
											displaytypeinfo.getTypeName(),
											AutoCodeManagerPropertyName.ItemName,
											false);
									treeData.setChildrenLoader(true);
									itemTypesMap
											.put(childrenNodeName, treeData);
								}
							}
						}
					} else {
						itemTypesMap = getItemTypeMaps(autoCodeData, hashMap);
					}
					Set<String> set = itemTypesMap.keySet();
					Object[] keys = (Object[]) set.toArray();
					Arrays.sort(keys);
					for (int n = 0; n < keys.length; n++) {
						String itemType = (String) keys[n];
						AbstractTreeData typeTreeNode = itemTypesMap
								.get(itemType);
						typeTreeNode = getShowItemType(typeTreeNode);
						if (typeTreeNode != null) {
							typeTreeNode
									.setTreeAutoCodeNodeChildren(new AbstractTreeData[] { new AbstractTreeData() });
							typeList.add(typeTreeNode);
						}
					}
					AbstractTreeData[] showItemTypes = new AbstractTreeData[typeList
							.size()];
					for (int k = 0; k < typeList.size(); k++) {
						showItemTypes[k] = typeList.get(k);
					}
					autoCodeData.setChildrenLoader(true);
					autoCodeData.setTreeAutoCodeNodeChildren(showItemTypes);
					treeViewer.refresh(autoCodeData);
					treeViewer.expandToLevel(autoCodeData, 1);
					if (!this.isFilterType && (showItemType != null)
							&& (showItemType.trim().length() > 0)) {
						createOrgAutoCodeNodeChildren(showItemTypes);
					}
				} else {
					if (nodeType.equals(AutoCodeManagerPropertyName.ItemName)) {
						autoCodeData = getSegmentNode(autoCodeData);
						autoCodeData.setChildrenLoader(true);
						treeViewer.refresh(autoCodeData);
						treeViewer.expandToLevel(autoCodeData, 1);
						continue;
					}
					if (!nodeType
							.equals(AutoCodeManagerPropertyName.CodeGroupName)) {
						continue;
					}

					if (autoCodeData.getParentTreeData().getPackCodeNodeInfo()
							.getNode_type()
							.equals(AutoCodeManagerPropertyName.ItemName)) {
						setParentTreeNode(autoCodeData.getParentTreeData(),
								autoCodeData);
					}

					TCComponent autoCodeDataComponent = autoCodeData
							.getPackCodeNodeInfo().getNodeComponent();
					TreeAndListCodeOperation treeAndListCodeOperation = new TreeAndListCodeOperation();
					HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

					String parentStr = "";
					parentStr = treeAndListCodeOperation.getParentStr(
							autoCodeData, parentStr);
					if (autoCodeDataComponent != null) {
						hashMap.put(
								AutoCodeManagerPropertyName.CodeRelation_current_node,
								autoCodeDataComponent.getUid());
						hashMap.put(
								AutoCodeManagerPropertyName.CodeRelation_parent_node,
								parentStr);
					} else {
						hashMap.put(
								AutoCodeManagerPropertyName.CodeRelation_parent_node,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.CodeRelation_current_node,
								"");
					}
					String parentStr2 = "";
					if (autoCodeDataComponent != null) {
						if (parentStr.trim().length() == 0) {
							parentStr2 = autoCodeDataComponent.getUid();
						} else {
							parentStr2 = parentStr + ","
									+ autoCodeDataComponent.getUid();
						}
					} else {
						parentStr2 = parentStr;
					}
					List<PackCodeNodeInfo> packCodeNodeInfos = treeAndListCodeOperation
							.searchTreeORListNodeInfos(
									hashMap,
									parentStr2,
									AutoCodeManagerPropertyName.searchTreeAndListCodeNodePropNames);
					// TODO 此时添加的获取类型

					if (packCodeNodeInfos != null
							&& packCodeNodeInfos.size() > 0) {
						AbstractTreeData autoCodeDataTCComs[] = new AbstractTreeData[packCodeNodeInfos
								.size()];
						for (int k = 0; k < packCodeNodeInfos.size(); k++) {
							if (packCodeNodeInfos.get(k).getNodeComponent() == null) {
								continue;
							}
							PackCodeNodeInfo packCodeNodeInfo = packCodeNodeInfos
									.get(k);
							// System.out.println(" REL-TYPE  ==> > > "+
							// packCodeNodeInfo.getRealTypeName());
							// MessageBox.post(" REL-TYPE  ==> > > "+
							// packCodeNodeInfo.getRealTypeName(),"INFO",MessageBox.ERROR);
							autoCodeDataTCComs[k] = new AbstractTreeData(
									autoCodeData, packCodeNodeInfo);
							if ((!packCodeNodeInfo.is_root)
									&& (!packCodeNodeInfo.is_lock)) {
								if (packCodeNodeInfo.isContainsChildren()) {
									autoCodeDataTCComs[k]
											.setTreeAutoCodeNodeChildren(new AbstractTreeData[] { new AbstractTreeData() });
								}
							}
						}
						autoCodeData
								.setTreeAutoCodeNodeChildren(autoCodeDataTCComs);
						autoCodeData.setChildrenLoader(true);
						treeViewer.refresh(autoCodeData);
						treeViewer.expandToLevel(autoCodeData, 1);
					} else {
						autoCodeData.setTreeAutoCodeNodeChildren(null);
						autoCodeData.setChildrenLoader(true);
						treeViewer.refresh(autoCodeData);
						treeViewer.expandToLevel(autoCodeData, 1);
					}
				}
			}
		}
	}
}
