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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.fieldassist.ComboContentAdapter;
import org.eclipse.jface.fieldassist.ContentProposal;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.SimpleContentProposalProvider;
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.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;
import cn.com.origin.autocodemanager.common.AutoCodeManagerPropertyName;
import cn.com.origin.autocodemanager.common.operations.PackCodeNodeInfo;
import cn.com.origin.autocodemanager.common.operations.TreeAndListCodeOperation;
import cn.com.origin.autocodemanager.common.tree.AbstractTreeData;

import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;

public class NewItemListCodeView extends CreateListCodeView {

	public Label[] propertyLabel;
	public Combo[] propertyComb;
	boolean isSetName = true;
	private String icoName = "";
	public String codeName = "";
	public StringBuffer pattern = new StringBuffer();
	public StringBuffer codeDesc = new StringBuffer();
	private Map<String, String> icoPropertyMap;
	private String splitString = "<---->";
	//
	private String productCode = "";

	public NewItemListCodeView(Composite composite, String rootName, ViewPart viewPart) {
		super(composite, rootName, viewPart);
	}

	public void createTree(Composite parent, String rootName) {
		Composite composite = parent;
		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) {
				AbstractTreeData codeData = (AbstractTreeData) treeEvent.item.getData();
				if (codeData == null) {
					return;
				}
				if (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 (selectedData == null) {
					return;
				}
				if (selectedData.getParentTreeData() == null) {
					expandNode(selectedData);
				}
			}
		});
	}

	public void getListPropertyValue(AbstractTreeData segmentNode) {
		initPropertyValue();
		try {
			if ((segmentNode != null) && (segmentNode.getPackCodeNodeInfo().getNodeComponent() != null)) {
				String firstNodeName = segmentNode.getPackCodeNodeInfo().getNode_name();
				String firstNodeValue = segmentNode.getPackCodeNodeInfo().getNode_value();
				if (firstNodeValue.trim().length() > 0) {
					codeDesc.append(firstNodeValue + "::" + firstNodeName);
					codeDesc.append("\n");
					pattern.append(firstNodeValue);
					pattern.append(" ");
				}
			}
			if (propertyComb != null && propertyComb.length > 0) {
				for (int i = 0; i < propertyComb.length; i++) {
					if (propertyComb[i] == null) {
						continue;
					}
					if (propertyComb[i].getText().length() == 0) {
						return;
					}
					String codeListValue = propertyComb[i].getText();
					String name = propertyLabel[i].getText().trim();
					codeName = name.substring(0, name.length() - 1).toString();
					if (codeListValue != null && !"".equals(codeListValue)) {
						if (codeListValue.contains(splitString)) {
							String temp[] = codeListValue.split(splitString);
							if (temp.length > 0) {
								icoPropertyMap.put(codeName.trim(), temp[1].trim());
								codeDesc.append(replaceSpecialValue(temp[0].trim()) + "::" + temp[1].trim());
								codeDesc.append("\n");
								pattern.append(replaceSpecialValue(temp[0].trim()));
								pattern.append(" ");
							}
						} else {
							icoPropertyMap.put(codeName.trim(), codeListValue);
							codeDesc.append(replaceSpecialValue(codeListValue) + "::" + "手写");
							codeDesc.append("\n");
							pattern.append(replaceSpecialValue(codeListValue));
							pattern.append(" ");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String replaceSpecialValue(String value) {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = formatter.format(date);
		// System.out.println("dateStr:::::" + dateStr);
		String temps[] = dateStr.split("-");
		if (value.contains(AutoCodeManagerPropertyName.Code_year4)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_year4, temps[0]);
			value = value + " ";
		}
		if (value.contains(AutoCodeManagerPropertyName.Code_year2)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_year2, temps[0].substring(2));
			value = value + " ";
		}
		if (value.contains(AutoCodeManagerPropertyName.Code_mouth1)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_mouth1, temps[1]);
			value = value + " ";
		}
		if (value.contains(AutoCodeManagerPropertyName.Code_mouth2)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_mouth2, temps[1]);
			value = value + " ";
		}

		if (value.contains(AutoCodeManagerPropertyName.Code_date1)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_date1, temps[2]);
			value = value + " ";
		}
		if (value.contains(AutoCodeManagerPropertyName.Code_date2)) {
			value = value.replace(AutoCodeManagerPropertyName.Code_date2, temps[2]);
			value = value + " ";
		}
		return value;
	}

	/**
	 * @return the icoPropertyMap
	 */
	public Map<String, String> getIcoPropertyMap() {
		return icoPropertyMap;
	}

	/**
	 * @param icoPropertyMap
	 *            the icoPropertyMap to set
	 */
	public void setIcoPropertyMap(Map<String, String> icoPropertyMap) {
		this.icoPropertyMap = icoPropertyMap;
	}

	private void initPropertyValue() {
		icoName = "";
		codeName = "";
		icoPropertyMap = new HashMap<String, String>();
		pattern = new StringBuffer();
		codeDesc = new StringBuffer();
	}

	public String getFirstComboName() {
		String value = "";
		if (isSetName) {
			if (propertyComb != null && propertyComb.length > 0) {
				for (int i = 0; i < propertyComb.length; i++) {
					if (propertyComb[i] == null) {
						continue;
					}
					String codeListValue = propertyComb[i].getText();
					if (codeListValue != null && !"".equals(codeListValue)) {
						if (codeListValue.contains(splitString)) {
							String temp[] = codeListValue.split(splitString);
							if (temp.length > 0) {
								// value = temp[0].trim();
								value = temp[1].trim();
							}
						} else {
							value = "";
						}
					}
					break;
				}
			}
		}
		return value;
	}

	public List<PackCodeNodeInfo> lp_packCodeNodeInfos;

	public void createCombox(Composite composite, AbstractTreeData segmentTreeData) {
		try {
			TCComponent segmentComponent = segmentTreeData.getPackCodeNodeInfo().getNodeComponent();
			composite.setLayout(new GridLayout(2, false));
			initPropertyValue();
			TreeAndListCodeOperation treeAndListCodeOperation = new TreeAndListCodeOperation();
			HashMap<Object, Object> hashMap11 = new HashMap<Object, Object>();
			String parentStr11 = "";
			parentStr11 = treeAndListCodeOperation.getParentStr(segmentTreeData, parentStr11);
			if (segmentTreeData.getPackCodeNodeInfo().getNodeComponent() != null) {
				hashMap11.put(AutoCodeManagerPropertyName.CodeRelation_current_node, segmentComponent.getUid());
				hashMap11.put(AutoCodeManagerPropertyName.CodeRelation_parent_node, parentStr11);
			} else {
				hashMap11.put(AutoCodeManagerPropertyName.CodeRelation_parent_node, "");
				hashMap11.put(AutoCodeManagerPropertyName.CodeRelation_current_node, "");
			}
			String parentStr12 = "";
			if (segmentComponent != null) {
				if (parentStr11.trim().length() == 0) {
					parentStr12 = segmentComponent.getUid();
				} else {
					parentStr12 = parentStr11 + "," + segmentComponent.getUid();
				}
			} else {
				parentStr12 = parentStr11;
			}
			List<PackCodeNodeInfo> packCodeNodeInfos = treeAndListCodeOperation.searchTreeORListNodeInfos(hashMap11, parentStr12, AutoCodeManagerPropertyName.searchTreeAndListCodeNodePropNames);
			if ((packCodeNodeInfos == null) || (packCodeNodeInfos.size() == 0)) {
				return;
			}

			propertyLabel = new Label[packCodeNodeInfos.size()];
			propertyComb = new Combo[packCodeNodeInfos.size()];
			for (int i = 0; i < packCodeNodeInfos.size(); i++) {
				if (packCodeNodeInfos.get(i).getNodeComponent() == null) {
					continue;
				}
				PackCodeNodeInfo packCodeNodeInfo = packCodeNodeInfos.get(i);

				GridData gridDataLabel = new GridData();
				gridDataLabel.horizontalSpan = 1;
				GridData gridDataLabeCombo = new GridData();
				gridDataLabeCombo.horizontalSpan = 1;

				String labelText = packCodeNodeInfo.getNode_name();
				propertyLabel[i] = new Label(composite, SWT.NONE);
				propertyLabel[i].setText(labelText + ":");
				propertyLabel[i].setLayoutData(gridDataLabel);
				if (packCodeNodeInfo.is_lock) {
					propertyComb[i].setItems(new String[] { "<--已锁定-->" });
					continue;
				}
				HashMap<String, String> hashMap21 = new HashMap<String, String>();
				String parentStr21 = "";
				String parentStr22 = "";
				parentStr21 = treeAndListCodeOperation.getParentStr(segmentTreeData, parentStr21);
				if (parentStr21.trim().length() > 0) {
					parentStr21 = parentStr21 + "," + segmentComponent.getUid();
				} else {
					parentStr21 = segmentComponent.getUid();
				}
				hashMap21.put(AutoCodeManagerPropertyName.CodeRelation_parent_node, parentStr21);
				hashMap21.put(AutoCodeManagerPropertyName.CodeRelation_current_node, packCodeNodeInfo.getNodeComponent().getUid());

				List<PackCodeNodeInfo> packCodeNodeInfos2 = treeAndListCodeOperation.searchTreeORListNodeInfos(hashMap21, parentStr22, AutoCodeManagerPropertyName.searchTreeAndListCodeNodePropNames);
				if ((packCodeNodeInfos2 != null) && (packCodeNodeInfos2.size() > 0)) {

//					System.out.println("20181019 labelText >>" + labelText);
					if (labelText != null && labelText.equals("文件类型")) {
						lp_packCodeNodeInfos = packCodeNodeInfos2;
						System.out.println("not READ_ONLY");
						propertyComb[i] = new Combo(composite, SWT.NONE);
					} else {
						propertyComb[i] = new Combo(composite, SWT.NONE | SWT.READ_ONLY);
					}

					propertyComb[i].setLayoutData(gridDataLabeCombo);
					String items[] = new String[packCodeNodeInfos2.size()];
					String selectValue = "";

					for (int k = 0; k < packCodeNodeInfos2.size(); k++) {
						PackCodeNodeInfo packCodeNodeInfo2 = packCodeNodeInfos2.get(k);
						if (packCodeNodeInfo2.is_lock) {
							items[k] = "<--已锁定-->";
							continue;
						}
						String key = packCodeNodeInfo2.getNode_name();
						String value = packCodeNodeInfo2.getNode_value();
						items[k] = value + "<---->" + key;
						boolean isSelected = packCodeNodeInfo2.isDefaultSelected;
						if (isSelected) {
							selectValue = items[k];
						}
					}
					propertyComb[i].setItems(items);

					if (selectValue.length() > 0) {
						propertyComb[i].setText(selectValue);
					}
					int itemCount = propertyComb[i].getItemCount();
					if (itemCount < 15) {
						propertyComb[i].setVisibleItemCount(itemCount);
					} else {
						propertyComb[i].setVisibleItemCount(15);
					}

					if (labelText != null && labelText.equals("文件类型")) {
						System.out.println("not READ_ONLY 222");
						ComboContentAdapter comboContentAdapter = new ComboContentAdapter();
						// new AutoCompleteField(combo, comboContentAdapter,items);
						MySimpleContentProposalProvider proposalProvider;
						proposalProvider = new MySimpleContentProposalProvider(items);
						proposalProvider.setFiltering(true);
						ContentProposalAdapter adapter = new ContentProposalAdapter(propertyComb[i], comboContentAdapter, proposalProvider, null, null);
						adapter.setPropagateKeys(true);
						adapter.setProposalAcceptanceStyle(2);

					}

				} else {
					if (isSetName) {
						isSetName = false;
					}
					propertyComb[i] = new Combo(composite, SWT.NONE);

					// ===============20210628============
					if (productCode.trim().length() > 0) {
						String s1 = propertyLabel[i].getText();
						if (s1.substring(0, s1.length() - 1).equals("产品代号")) {
							String codeInfo = productCode + "<---->产品代号";
							propertyComb[i].setItems(new String[] { codeInfo });
							propertyComb[i].setText(codeInfo);
							int itemCount = propertyComb[i].getItemCount();
							if (itemCount < 15) {
								propertyComb[i].setVisibleItemCount(itemCount);
							} else {
								propertyComb[i].setVisibleItemCount(15);
							}
						} else if (s1.substring(0, s1.length() - 1).equals("结构件图样编号")) {
							String codeInfo = productCode + "<---->结构件图样编号";
							propertyComb[i].setItems(new String[] { codeInfo });
							propertyComb[i].setText(codeInfo);
							int itemCount = propertyComb[i].getItemCount();
							if (itemCount < 15) {
								propertyComb[i].setVisibleItemCount(itemCount);
							} else {
								propertyComb[i].setVisibleItemCount(15);
							}
						}
					}
					// ===============20210628============
					propertyComb[i].setLayoutData(gridDataLabeCombo);
				}
				composite.redraw();
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (TCException e) {
			e.printStackTrace();
		}
		composite.redraw();
	}

	/**
	 * @return the propertyLabel
	 */
	public Label[] getPropertyLabel() {
		return propertyLabel;
	}

	/**
	 * @param propertyLabel
	 *            the propertyLabel to set
	 */
	public void setPropertyLabel(Label[] propertyLabel) {
		this.propertyLabel = propertyLabel;
	}

	/**
	 * @return the propertyComb
	 */
	public Combo[] getPropertyComb() {
		return propertyComb;
	}

	/**
	 * @param propertyComb
	 *            the propertyComb to set
	 */
	public void setPropertyComb(Combo[] propertyComb) {
		this.propertyComb = propertyComb;
	}

	/**
	 * 
	 */
	public NewItemListCodeView() {
	}

	public NewItemListCodeView(String productCode) {
		this.productCode = productCode;
	}

	/**
	 * @return the newSeq
	 */
	// public String getNewSeq() {
	// return newSeq;
	// }
	//
	// /**
	// * @param newSeq
	// * the newSeq to set
	// */
	// public void setNewSeq(String newSeq) {
	// this.newSeq = newSeq;
	// }
	/**
	 * @return the icoName
	 */
	public String getIcoName() {
		return icoName;
	}

	/**
	 * @param icoName
	 *            the icoName to set
	 */
	public void setIcoName(String icoName) {
		this.icoName = icoName;
	}

	/**
	 * @return the codeStyle
	 */
	// public String getCodeStyle() {
	// return codeStyle;
	// }
	//
	// /**
	// * @param codeStyle
	// * the codeStyle to set
	// */
	// public void setCodeStyle(String codeStyle) {
	// this.codeStyle = codeStyle;
	// }
	/**
	 * @return the pattern
	 */
	public StringBuffer getPattern() {
		return pattern;
	}

	/**
	 * @param pattern
	 *            the pattern to set
	 */
	public void setPattern(StringBuffer pattern) {
		this.pattern = pattern;
	}

	/**
	 * @return the codeDesc
	 */
	public StringBuffer getCodeDesc() {
		return codeDesc;
	}

	/**
	 * @param codeDesc
	 *            the codeDesc to set
	 */
	public void setCodeDesc(StringBuffer codeDesc) {
		this.codeDesc = codeDesc;
	}

	/**
	 * @return the codeName
	 */
	public String getCodeName() {
		return codeName;
	}

	/**
	 * @param codeName
	 *            the codeName to set
	 */
	public void setCodeName(String codeName) {
		this.codeName = codeName;
	}

	private class MySimpleContentProposalProvider extends SimpleContentProposalProvider {
		private String proposals[];
		private IContentProposal contentProposals[];
		private boolean filterProposals;

		public MySimpleContentProposalProvider(String[] proposals) {
			super(proposals);
			filterProposals = true;
			this.proposals = proposals;
		}

		public IContentProposal[] getProposals(String contents, int position) {
			if (filterProposals) {
				ArrayList list = new ArrayList();
				for (int i = 0; i < proposals.length; i++) {
					if (proposals[i].length() >= contents.length() && proposals[i].toUpperCase().contains(contents.toUpperCase())) {
						list.add(new ContentProposal(proposals[i]));
					}
				}

				return (IContentProposal[]) list.toArray(new IContentProposal[list.size()]);
			}
			if (contentProposals == null) {
				contentProposals = new IContentProposal[proposals.length];
				for (int i = 0; i < proposals.length; i++)
					contentProposals[i] = new ContentProposal(proposals[i]);
			}
			return contentProposals;
		}
	}
}
