/**
 * @author tyl
 * @Action  ini
 * 2011-3-16
 */
package cn.com.origin.autocode.views.groupview;

import java.util.HashMap;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.part.ViewPart;

import cn.com.origin.autocode.common.operations.ClassificationOperation;
import cn.com.origin.autocode.views.AutoCodeItemTypeView;
import cn.com.origin.autocodemanager.common.AutoCodeConstants;
import cn.com.origin.autocodemanager.common.AutoCodeManagerPropertyName;
import cn.com.origin.autocodemanager.common.progress.ExpandProgressBar;
import cn.com.origin.autocodemanager.common.tree.AbstractCreateTreeView;
import cn.com.origin.autocodemanager.common.tree.AbstractTreeData;
import cn.com.origin.autocodemanager.common.tree.ORTreeContentProvider;
import cn.com.origin.autocodemanager.common.tree.ORTreeLabelProvider;

import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCComponentRole;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;

public class CreateGoupView extends AbstractCreateTreeView {

	public AutoCodeItemTypeView itemTypeView;

	public String users = "";
	public String groups = "";
	public String roles = "";

	public CreateGoupView(Composite composite, String rootName,
			ViewPart viewPart) {
		super(composite, rootName, viewPart);
		itemTypeView = (AutoCodeItemTypeView) viewPart.getSite().getPage()
				.findView(AutoCodeConstants.AutoCodeItemTypeView_ID);
	}

	public CreateGoupView() {
	}

	public void addRightKeyAction() {
		final Tree tree = treeViewer.getTree();
		tree.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent e) {
				if (e.button == 3) {
					// 鼠标单击右键，3D鼠标
					// 检查是否点到了具体的节点
					GroupViewRightKey rightAction = new GroupViewRightKey(
							CreateGoupView.this);
					// TreeItem treeItem = tree.getItem(new Point(e.x, e.y));
					rightAction.fillContextMenu();
					// 没有点到具体结点
				} else if (e.button == 1) {
					// 鼠标单击，左键，对应的代码
				}
			}
		});
	}

	public void expandNode(AbstractTreeData codeData) {
		if (codeData == null) {
			return;
		}
		AbstractTreeData[] codeDatas = new AbstractTreeData[] { codeData };
		if (codeData.isChildrenLoader()) {
			codeDatas = codeData.getChildrenDatas();
		}
		ExpandProgressBar expandProgressBar = new ExpandProgressBar(Display
				.getDefault().getActiveShell(), "正在打开", this, codeDatas);
		try {
			expandProgressBar.expand();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void initTree(String rootName) {
		treeViewer.setLabelProvider(new ORTreeLabelProvider());
		treeViewer.setContentProvider(new ORTreeContentProvider());
		AbstractTreeData treeData = new AbstractTreeData(null, null, rootName,
				AutoCodeManagerPropertyName.OrganizationName, false);
		treeViewer.setInput((new Object[] { treeData }));
	}

	public void addMouseAction() {
		treeViewer.getTree().addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent e) {
				TreeItem[] treeItems = ((Tree) e.getSource()).getSelection();
				TreeItem[] items = itemTypeView.getCreateView().treeViewer
						.getTree().getSelection();
				for (int i = 0; i < items.length; i++) {
					TreeItem parentItem = items[i];
					for (int m = 0; m < treeItems.length; m++) {
						TreeItem childrenItem = treeItems[m];
						AbstractTreeData childrenData = (AbstractTreeData) childrenItem
								.getData();
						addOrganizationNode(
								itemTypeView.getCreateView().treeViewer,
								(AbstractTreeData) parentItem.getData(),
								childrenData);
					}
				}
			}
		});
	}

	public void getAllUser(AbstractTreeData parentData) {
		users = "";
		groups = "";
		roles = "";
		AbstractTreeData[] childrens = parentData.getChildrenDatas();
		if (childrens == null) {
			return;
		}
		for (int i = 0; i < childrens.length; i++) {
			TCComponent children = childrens[i].getPackCodeNodeInfo()
					.getNodeComponent();
			if (children instanceof TCComponentUser) {
				users = users + children.getUid() + ",";
			} else if (children instanceof TCComponentRole) {
				roles = roles + children.getUid() + ",";
			} else if (children instanceof TCComponentGroup) {
				groups = groups + children.getUid() + ",";
			}
		}
		if (users.endsWith(",")) {
			users = users.substring(0, users.length() - 1);
		}
		if (roles.endsWith(",")) {
			roles = roles.substring(0, roles.length() - 1);
		}
		if (groups.endsWith(",")) {
			groups = groups.substring(0, groups.length() - 1);
		}
	}

	public void addOrganizationNode(TreeViewer treeViewer,
			AbstractTreeData parentData, AbstractTreeData sourceChildrenData) {
		try {
			if (sourceChildrenData.getPackCodeNodeInfo().getNode_type()
					.equals(AutoCodeManagerPropertyName.OrganizationName)) {
				MessageBox.post("请选择组织,角色或人员!", "INFO", MessageBox.WARNING);
				return;
			}
			TCComponent updateComponent = null;
			ClassificationOperation classificationOperation = new ClassificationOperation();
			AbstractTreeData childrenData = new AbstractTreeData(
					parentData,
					sourceChildrenData.getPackCodeNodeInfo().getNodeComponent(),
					sourceChildrenData.getPackCodeNodeInfo().getNode_name(),
					sourceChildrenData.getPackCodeNodeInfo().getNode_type(),
					false);
			String nodeType = parentData.getPackCodeNodeInfo().getNode_type();
			if ((nodeType.equals(AutoCodeManagerPropertyName.ItemName))
					|| (treeViewOperation.isRuleRootNode(parentData))
					|| (nodeType
							.equals(AutoCodeManagerPropertyName.CodeGroupName))) {
				boolean isContain = treeViewOperation.appendChildrenData(
						treeViewer, parentData, childrenData);
				if (isContain) {
					return;
				}
				if (!parentData.getPackCodeNodeInfo().getNode_type()
						.equals(AutoCodeManagerPropertyName.ItemName)) {
					String segmentName = parentData.getPackCodeNodeInfo()
							.getNodeComponent().getUid().trim();
					String classificationName = parentData.getParentTreeData()
							.getPackCodeNodeInfo().getNode_name().trim();
					HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>();
					hashMap1.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
							classificationName);
					hashMap1.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_segment,
							segmentName);

					TCComponent[] components = classificationOperation
							.searchClassificationNodes(hashMap1);
					if ((components != null) && (components.length > 0)) {
						updateComponent = components[0];
					}
					if (updateComponent == null) {
						return;
					}
					getAllUser(parentData);

					HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
					hashMap.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_grant_groups,
							groups);
					hashMap.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_grant_roles,
							roles);
					hashMap.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_grant_users,
							users);
					hashMap.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_date,
							"");
					hashMap.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_user,
							"");
					classificationOperation.updateClassificationNode(
							updateComponent, hashMap);
				} else {
					getAllUser(parentData);
					String classificationName = parentData
							.getPackCodeNodeInfo().getNode_name();
					HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>();
					hashMap1.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
							classificationName);
					hashMap1.put(
							AutoCodeManagerPropertyName.ClassificationCodeNode_segment,
							"");
					TCComponent[] components = classificationOperation
							.searchClassificationNodes(hashMap1);
					if ((components != null) && (components.length > 0)) {
						updateComponent = components[0];
					}
					if (updateComponent == null) {
						HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_node_index,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_segment,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_node_name,
								classificationName);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_create_date,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_date,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_create_user,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_user,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_groups,
								groups);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_roles,
								roles);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_users,
								users);
						classificationOperation
								.createNewClassificationNode(hashMap);
					} else {
						HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_groups,
								groups);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_roles,
								roles);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_grant_users,
								users);
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_date,
								"");
						hashMap.put(
								AutoCodeManagerPropertyName.ClassificationCodeNode_last_revise_user,
								"");
						classificationOperation.updateClassificationNode(
								updateComponent, hashMap);
					}
				}
			} else {
				MessageBox.post("请选择编码规则或分类!", "INFO", MessageBox.WARNING);
				return;
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param codeDatas
	 * @throws Exception
	 */
	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;
				}
				TCComponent[] tccomponents = null;
				TCComponent autoCodeDataComponent = autoCodeData
						.getPackCodeNodeInfo().getNodeComponent();
				String nodeName = autoCodeData.getPackCodeNodeInfo()
						.getNode_type();
				if (nodeName
						.equals(AutoCodeManagerPropertyName.OrganizationName)) {
					tccomponents = businessType.getRootGroups();
				} else {
					if (autoCodeDataComponent instanceof TCComponentUser) {
						break;
					}
					if (autoCodeDataComponent instanceof TCComponentRole) {
						tccomponents = businessType.getRoleUsers(
								(TCComponentGroup) autoCodeData
										.getParentTreeData()
										.getPackCodeNodeInfo()
										.getNodeComponent(),
								(TCComponentRole) autoCodeDataComponent);
					} else {
						if (autoCodeDataComponent instanceof TCComponentGroup) {
							tccomponents = businessType
									.getGroupRoles((TCComponentGroup) autoCodeDataComponent);
						}
					}
				}
				if (tccomponents != null && tccomponents.length > 0) {
					AbstractTreeData autoCodeDataTCComs[] = new AbstractTreeData[tccomponents.length];
					for (int k = 0; k < tccomponents.length; k++) {
						String object_name = "";
						if (tccomponents[k] instanceof TCComponentRole) {
							TCComponentRole role = (TCComponentRole) tccomponents[k];
							object_name = role.getProperty("object_name");
						} else if (tccomponents[k] instanceof TCComponentGroup) {
							TCComponentGroup group = (TCComponentGroup) tccomponents[k];
							object_name = group.getProperty("name");
						} else if (tccomponents[k] instanceof TCComponentUser) {
							TCComponentUser user = (TCComponentUser) tccomponents[k];
							object_name = user.toString();
						}
						autoCodeDataTCComs[k] = new AbstractTreeData(
								autoCodeData, tccomponents[k], object_name,
								tccomponents[k].getType(), false);
					}
					autoCodeData.setChildrenLoader(true);
					autoCodeData
							.setTreeAutoCodeNodeChildren(autoCodeDataTCComs);
					treeViewer.refresh(autoCodeData);
					if (nodeName
							.equals(AutoCodeManagerPropertyName.OrganizationName)) {
						treeViewer.expandToLevel(autoCodeData, 1);
					}
					if (autoCodeDataTCComs.length > 0) {
						createOrgAutoCodeNodeChildren(autoCodeDataTCComs);
					}
				} else {
					continue;
				}
			}
		}
	}
}
