package cn.net.connor.std.processedit.util;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.Map.Entry;

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

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.ListOfValuesInfo;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentListOfValuesType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPropertyDescriptor;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.treetable.SwingTextContextActivator;
import com.teamcenter.rac.util.Registry;
import com.teamcenter.rac.util.iTextArea;
import com.teamcenter.rac.util.iTextField;
import com.teamcenter.rac.util.combobox.iComboBox;
import com.teamcenter.services.rac.core.LOVService;
import com.teamcenter.services.rac.core._2013_05.LOV.InitialLovData;
import com.teamcenter.services.rac.core._2013_05.LOV.LOVSearchResults;
import com.teamcenter.services.rac.core._2013_05.LOV.LOVValueRow;
import com.teamcenter.services.rac.core._2013_05.LOV.LovFilterData;
import com.teamcenter.soa.client.model.LovValue;

import cn.net.connor.std.aifrcp.util.KUtil;
import cn.net.connor.std.processedit.choose.ChooseDialog;
import cn.net.connor.std.processedit.choose.ChooseDialogController;
import cn.net.connor.std.processedit.choosefromsql.ChooseFromSqlDialog;

public class PrefComponent {
	
	
	public boolean isLovParent = false;
	public boolean isLovChild = false;
	
	public JTextField bigJtf;
	 public ArrayList<String> list = new ArrayList<String>();
	 public HashMap<String,OptionItem> opHashMap = new HashMap<String, OptionItem>();
	 public HashMap<String,String> lovDisRealMap = new HashMap<String, String>();
	public static final String REQUIRE = "*";
	public static final String READONLY = "#";
	public static final String TEXTAREA = "$";
	public static final String PREF_PREFIX_EXCEL = "Connor_AVIC_MEOPEXCEL_";
	public static final String PREF_PREFIX_DATABASE = "Connor_AVIC_MEOPSQL_";
	public static final String PREF_REL_LOV = "Connor_AVIC_MEOP_LOV_";
	private static final Registry REG = Registry.getRegistry(PrefComponent.class);

	private String configStr;
	protected boolean require = false;
	protected boolean readonly = false;
	public String title;
	public String propConfig;
	public String lovName;
	private String[] additional;
	private String[] lov;
	private String[] displayLov;
	private String[] descriptions;
	public iTextField textField;
	private iTextArea textArea;
	public JComboBox comboBox;
	public JLabel label;
	private String[] chooseFromExcel;
	// private Map<String, ChooseDialog> chooseDialogMap = new HashMap<String,
	// ChooseDialog>();
	protected boolean isTextArea = false;
	private String savedValue;
	private String fromProcess;
	private String fromProcessValue;
	private String propName;
	private String displayCondition;
	private List<JComponent> additionalComps = new ArrayList<JComponent>();
	private String[] chooseFromDatabase;
	private String typeName;
	public String[] getExcelConfig() {
		return this.chooseFromExcel;
	}

	public String[] getSqlConfig() {
		return this.chooseFromDatabase;
	}

	public String getTitle() {
		return title;
	}

	public boolean canDisplay(TCComponentItemRevision rev) throws Exception {
		if (KUtil.isEmpty(displayCondition) || rev == null) {
			return true;
		}
		System.out.println("Check Property Display: " + rev + " -> " + displayCondition);
		int ind = displayCondition.lastIndexOf(':');
		if (ind < 0) {
			return true;
		}
		String propStr = displayCondition.substring(0, ind);
		String checkValue = displayCondition.substring(ind + 1);
		String propValue = KUtil.getConfigPropValue(rev, propStr);
		System.out.println("Prop Value: " + propValue);
		return checkValue.equals(propValue);
	}

	public String getPropConfig() {
		return propConfig;
	}

	public PrefComponent(String pref, String type) {
		this.configStr = pref;
		this.typeName = type;
	}

	public boolean init(TCSession session) throws Exception {
		return init(session, null, null);
	}

	public boolean init(TCSession session, TCComponentItemRevision targetRev, List<PrefComponent> prefComponents) throws Exception {
		if (KUtil.isEmpty(configStr)) {
			return false;
		}
		System.out.println("111111111======"+configStr);
		if (configStr.startsWith(REQUIRE)) {
			configStr = configStr.substring(1);
			this.require = true;
		}
		if (configStr.startsWith(READONLY)) {
			configStr = configStr.substring(1);
			this.readonly = true;
		}
		if (configStr.startsWith(TEXTAREA)) {
			configStr = configStr.substring(1);
			this.isTextArea = true;
		}
		String[] split = configStr.split("=", -1);
		int len = KUtil.getLen(split);
		if (len > 0) {
			this.title = split[0];
		}
		if (len > 1) {
			this.propConfig = split[1];
		}
		if (len > 2) {
			this.lovName = split[2];
		}
		if (len > 3) {
			this.fromProcess = split[3];
		}
		if (len > 4) {
			displayCondition = split[4];
		}
		if (KUtil.isEmpty(title)) {
			return false;
		}
		if (!KUtil.isEmpty(fromProcess)) {
			this.fromProcessValue = KUtil.getConfigPropValue(targetRev, fromProcess);
		}
		if (!KUtil.isEmpty(lovName)) {
			int ind = lovName.indexOf(';');
			if (ind > 0) {
				
				String[] lovValues = lovName.split(";");
				int lovCnt = KUtil.getLen(lovValues);
				this.lov = new String[lovCnt];
				this.displayLov = new String[lovCnt];
				descriptions = new String[lovCnt];
				for (int i = 0; i < lovCnt; i++) {
					String realValue = lovValues[i];
					String disValue = lovValues[i];
					lov[i] = realValue;
					displayLov[i] = disValue;
					descriptions[i] = "";
					additional[i] = realValue;
					lovDisRealMap.put(displayLov[i], lov[i]);
				}
			} else {//TODO 
				
				
				
				if(lovName.contains("^A")) {
					lovName = lovName.split("\\^")[0];
					isLovParent = true;
					
					
					

					
					
					TCComponentListOfValues lovComp = KUtil.getLov(session, lovName);
					
//					Map<String, String[]> lovTWO = getLovTWO(session,lovName);
//					
//					System.out.println("lovTWO======"+lovTWO.toString());
//					
//					Map<String, String> lovTh = getLovThreeRealValue(session,lovName);
//					
//					System.out.println("lovTh======"+lovTh.toString());
					
					
					initLovTree(lovComp,session);
					System.out.println("lovList==="+listLov.toString());
					
					if (lovComp == null) {
						throw new Exception(String.format(REG.getString("lovnotfound.ERROR1"), lovName));
					}
					List<LovValue> vals = lovComp.getListOfValues().getValues();
					int lovCnt = vals == null ? 0 : vals.size();
					ListOfValuesInfo listOfValues = lovComp.getListOfValues();
					if (lovCnt>0) {
						System.out.println("getListOfValues:"+lovName+lovCnt);
						descriptions = listOfValues.getDispDescription();//lov描述
						this.lov = new String[lovCnt];
						this.displayLov = new String[lovCnt];
						additional = new String[lovCnt];
						for (int i = 0; i < lovCnt; i++) {
							LovValue lovValue = vals.get(i);
							String realValue = lovValue.getValue() == null ? "" : lovValue.getValue().toString();
							String disValue = lovValue.getDisplayValue();
							lov[i] = realValue;
							displayLov[i] = disValue;
							lovDisRealMap.put(displayLov[i], lov[i]);
						}
					}else {
						System.out.println("getDynamicLOV:"+lovName);
						String[] lovValues = getDynamicLOV(lovComp);
						System.out.println("lovValues---"+lovValues.length);
						lovCnt = KUtil.getLen(lovValues);
						this.lov = new String[lovCnt];
						this.displayLov = new String[lovCnt];
						for (int i = 0; i < lovCnt; i++) {
							String realValue = lovValues[i];
							String disValue = lovValues[i];
							lov[i] = realValue;
							displayLov[i] = disValue;
							lovDisRealMap.put(displayLov[i], lov[i]);
						}
					}
				
					
					
					
				}else if(lovName.contains("^B")) {
					lovName = lovName.split("\\^")[0];
					isLovChild = true;
				}else {
					
					
					TCComponentListOfValues lovComp = KUtil.getLov(session, lovName);

					
					if (lovComp == null) {
						throw new Exception(String.format(REG.getString("lovnotfound.ERROR1"), lovName));
					}
					List<LovValue> vals = lovComp.getListOfValues().getValues();
					int lovCnt = vals == null ? 0 : vals.size();
					ListOfValuesInfo listOfValues = lovComp.getListOfValues();
					if (lovCnt>0) {
						System.out.println("getListOfValues:"+lovName+lovCnt);
						descriptions = listOfValues.getDispDescription();//lov描述
						this.lov = new String[lovCnt];
						this.displayLov = new String[lovCnt];
						additional = new String[lovCnt];
						for (int i = 0; i < lovCnt; i++) {
							LovValue lovValue = vals.get(i);
							String realValue = lovValue.getValue() == null ? "" : lovValue.getValue().toString();
							String disValue = lovValue.getDisplayValue();
							lov[i] = realValue;
							displayLov[i] = disValue;
							lovDisRealMap.put(displayLov[i], lov[i]);
						}
					}else {
						System.out.println("getDynamicLOV:"+lovName);
						String[] lovValues = getDynamicLOV(lovComp);
						lovCnt = KUtil.getLen(lovValues);
						this.lov = new String[lovCnt];
						this.displayLov = new String[lovCnt];
						for (int i = 0; i < lovCnt; i++) {
							String realValue = lovValues[i];
							String disValue = lovValues[i];
							lov[i] = realValue;
							displayLov[i] = disValue;
							lovDisRealMap.put(displayLov[i], lov[i]);
						}
					}
				}
				

			}
		}
		if (!KUtil.isEmpty(propConfig)) {
			this.propName = propConfig;
			int ind = propConfig.indexOf('.');// only use name as suffix
			if (ind > 0) {
				propName = propConfig.substring(ind + 1);
			}
//			if (!KUtil.isEmpty(propName)) {
//				this.chooseFromExcel = session.getPreferenceService().getStringValues(PREF_PREFIX_EXCEL + propName);
//				this.chooseFromDatabase = session.getPreferenceService().getStringValues(PREF_PREFIX_DATABASE + typeName + "_" + propName);
//			}
		}
		initPanel();
		initComponent();
		checkLovRelatedProp(session, prefComponents);
		if (this.fromProcessValue != null) {
			setValue(this.fromProcessValue);
		}
		return true;
	}

	private void initComponent() throws Exception {
		if (readonly) {
			if (textField != null) {
				textField.setEditable(false);
			}
			if (textArea != null) {
				textArea.setEditable(false);
			}
			if (comboBox != null) {
				comboBox.setEditable(false);
				comboBox.setEnabled(false);
			}
		}
		if (require) {
			if (textField != null) {
				textField.setRequired(true);
			}
			if (textArea != null) {
				textArea.setRequired(true);
			}
			if (comboBox != null) {
				//comboBox.setEditable(true);
				comboBox.setEnabled(true);
			}
		}
	}

	private void checkLovRelatedProp(TCSession session, List<PrefComponent> prefComponents) throws Exception {
		if (comboBox == null) {
			return;
		}
		Map<String, Map<String, String>> relateValueMap = new HashMap<String, Map<String, String>>();
		String prefName = PREF_REL_LOV + propName;
		String[] prefs = session.getPreferenceService().getStringValues(prefName);
		System.out.println(prefName + " >> " + Arrays.toString(prefs));
		int prefLen = KUtil.getLen(prefs);
		for (int i = 0; i < prefLen; i++) {
			String pref = prefs[i];
			int ind = pref.indexOf(':');
			if (ind < 0) {
				continue;
			}
			String realValue = pref.substring(0, ind);
			String[] relateValues = pref.substring(ind + 1).split(";");
			int relateLen = KUtil.getLen(relateValues);
			for (int j = 0; j < relateLen; j++) {
				String relateValue = relateValues[j];
				ind = relateValue.indexOf('=');
				if (ind <= 0) {
					continue;
				}
				String relateProp = relateValue.substring(0, ind).trim();
				if (this.propName.equals(relateProp)) {
					continue;
				}
				relateValue = relateValue.substring(ind + 1);
				if (KUtil.isEmpty(relateProp)) {
					continue;
				}
				Map<String, String> subMap;
				if (relateValueMap.containsKey(realValue)) {
					subMap = relateValueMap.get(realValue);
				} else {
					subMap = new HashMap<String, String>();
					relateValueMap.put(realValue, subMap);
				}
				subMap.put(relateProp, relateValue);
			}
		}
		if (relateValueMap.size() > 0) {
			comboBox.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					String item = getValue();
					System.out.println("Select: " + item);
					if (item == null) {
						item = "";
					}
					if (relateValueMap.containsKey(item)) {
						Map<String, String> subMap = relateValueMap.get(item);
						for (PrefComponent comp : prefComponents) {
							if (subMap.containsKey(comp.propName)) {
								comp.setValue(subMap.get(comp.propName));
							}
						}
					}
				}
			});

			
		}
	}

	private void initPanel() {
		// this.panel = new JPanel(new GridBagLayout());
		// this.panel.setPreferredSize(new Dimension(260, 40));
		// GridBagConstraints s = new GridBagConstraints(0, 0, 1, 1, 0, 0,
		// GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 5, 0, 0),
		// 0, 0);
		
		if(isLovChild) {
			
			
	
	        String labelText = "<html>" + title;
	        if (require) {
	            labelText += "<font color='red'>*</font>";
	        }
	        labelText += "</html>";

			
			this.label = new JLabel(labelText, JLabel.RIGHT);
			
			
			
	        comboBox = new JComboBox();
	        comboBox.setRenderer(new TwoColumnRenderer());
	        comboBox.insertItemAt(null, 0);
	        comboBox.setSelectedIndex(0);
			comboBox.setEditable(true);
			
						
	    	this.bigJtf = ((JTextField)this.comboBox.getEditor().getEditorComponent());
		    this.bigJtf.addKeyListener(new KeyListener()
		    {
		      public void keyTyped(KeyEvent e) {}
		      
		      public void keyReleased(KeyEvent e)
		      {
		        Object obj = e.getSource();
		  
		        if ((e.getKeyCode() == 10) && 
		          (obj == bigJtf))
		        {
		          String key = bigJtf.getText();
		          comboBox.removeAllItems();
		         // System.out.println("key==="+key);
		        //  System.out.println("opHashMap==="+opHashMap.toString());
		          for (String item : list) {
		        	  System.out.println("item==="+item);
		        	  if(item.isEmpty()) {
		        		  for (Entry<String, OptionItem> optionItem : opHashMap.entrySet()) {
		        			  comboBox.addItem(optionItem);
						}
		        	  }else {
		        		  if (item.contains(key)) {
				            	OptionItem optionItem = opHashMap.get(item);
				            	 
				            	comboBox.addItem(optionItem);
				            }
		        	  }
		            
		          }
		          bigJtf.setText(key);
		        }
		      }
		      
		      public void keyPressed(KeyEvent e) {}
		    });
		    
		    
			//iComboBox iComboBox = new iComboBox();
		    bigJtf.addFocusListener(new FocusAdapter() {
				public void focusGained(FocusEvent param1FocusEvent) {
					SwingTextContextActivator.instance().activateContext();
				}

				public void focusLost(FocusEvent param1FocusEvent) {
					super.focusLost(param1FocusEvent);
					SwingTextContextActivator.instance().deactivateContext();
				}
			});

				
			
			
		}else {
			int len = KUtil.getLen(displayLov);
	        String labelText = "<html>" + title;
	        if (len > 0 && require) {
	            labelText += "<font color='red'>*</font>";
	        }
	        labelText += "</html>";

			
			this.label = new JLabel(labelText, JLabel.RIGHT);
			// KUtil.newRow(panel, label, s, 1);
		
			if (len > 0) {
		        comboBox = new JComboBox();
		        comboBox.setRenderer(new TwoColumnRenderer());
		        comboBox.insertItemAt(null, 0);
		        comboBox.setSelectedIndex(0);
				comboBox.setEditable(true);
		        for (int i = 0; i < len; i++) {
		            OptionItem optionItem = new OptionItem(displayLov[i], descriptions[i]);
		            comboBox.addItem(optionItem);
		            opHashMap.put(displayLov[i], optionItem);
		            list.add(displayLov[i]);
		        }
				
		    	this.bigJtf = ((JTextField)this.comboBox.getEditor().getEditorComponent());
			    this.bigJtf.addKeyListener(new KeyListener()
			    {
			      public void keyTyped(KeyEvent e) {}
			      
			      public void keyReleased(KeyEvent e)
			      {
			        Object obj = e.getSource();
			  
			        if ((e.getKeyCode() == 10) && 
			          (obj == bigJtf))
			        {
			          String key = bigJtf.getText();
			          comboBox.removeAllItems();
			         // System.out.println("key==="+key);
			        //  System.out.println("opHashMap==="+opHashMap.toString());
			          for (String item : list) {
			        	  System.out.println("item==="+item);
			        	  if(item.isEmpty()) {
			        		  for (Entry<String, OptionItem> optionItem : opHashMap.entrySet()) {
			        			  comboBox.addItem(optionItem);
							}
			        	  }else {
			        		  if (item.contains(key)) {
					            	OptionItem optionItem = opHashMap.get(item);
					            	 
					            	comboBox.addItem(optionItem);
					            }
			        	  }
			            
			          }
			          bigJtf.setText(key);
			        }
			      }
			      
			      public void keyPressed(KeyEvent e) {}
			    });
			    
			    
				//iComboBox iComboBox = new iComboBox();
			    bigJtf.addFocusListener(new FocusAdapter() {
					public void focusGained(FocusEvent param1FocusEvent) {
						SwingTextContextActivator.instance().activateContext();
					}

					public void focusLost(FocusEvent param1FocusEvent) {
						super.focusLost(param1FocusEvent);
						SwingTextContextActivator.instance().deactivateContext();
					}
				});

				
			
			} else {
				if (isTextArea) {
					textArea = new iTextArea(8, 18);
					 textArea.setBorder(BorderFactory.createLineBorder(Color.GRAY));
					textArea.setLineWrap(true);
					textArea.addFocusListener(new FocusAdapter() {
						public void focusGained(FocusEvent param1FocusEvent) {
							SwingTextContextActivator.instance().activateContext();
						}

						public void focusLost(FocusEvent param1FocusEvent) {
							super.focusLost(param1FocusEvent);
							SwingTextContextActivator.instance().deactivateContext();
						}
					});
				} else {
					textField = new iTextField(18);
					textField.addFocusListener(new FocusAdapter() {
						public void focusGained(FocusEvent param1FocusEvent) {
							SwingTextContextActivator.instance().activateContext();
						}

						public void focusLost(FocusEvent param1FocusEvent) {
							super.focusLost(param1FocusEvent);
							SwingTextContextActivator.instance().deactivateContext();
						}
					});
				}
				// KUtil.addCol(panel, textField, s, 1, 1);
			}
			
		}
	}

	// public Component getPanel() {
	// return panel;
	// }

	public JComponent getValueComp() {
		return textField == null ? (textArea == null ? comboBox : textArea) : textField;
	}

	public JLabel getLabel() {
		return this.label;
	}

	public void setValue(String value) {
		if (textField != null) {
			textField.setText(value);
		} else if (textArea != null) {
			textArea.setText(value);
		} else if (comboBox != null) {
			if (value == null) {
				comboBox.setSelectedItem(null);
			} else {
				int ind = KUtil.inArray(value, lov);
				if (ind < 0) {
					ind = KUtil.inArray(value, displayLov);
				}
				if (ind < 0) {
					comboBox.setSelectedItem(null);
				} else {
					comboBox.setSelectedIndex(ind+1);
				}
			}
		}
	}

	public void setValueAndSave(String value) {
		this.savedValue = value;
		if (textField != null) {
			textField.setText(value);
		} else if (textArea != null) {
			textArea.setText(value);
		} else if (comboBox != null) {
			if (value == null) {
				this.savedValue = "";
				comboBox.setSelectedItem(null);
			} else {
				int ind = KUtil.inArray(value, lov);
				if (ind < 0) {
					ind = KUtil.inArray(value, displayLov);
				}
				if (ind < 0) {
					this.savedValue = "";
					comboBox.setSelectedItem(null);
				} else {
					this.savedValue = lov[ind];
					comboBox.setSelectedIndex(ind+1);
				}
			}
		}
	}

	public boolean isModified() {
		String val = getValue();
		if (val == null) {
			val = "";
		}
		if (savedValue == null) {
			return !"".equals(val);
		} else {
			return !savedValue.equals(val);
		}
	}

	public String getProperty(TCComponent comp) throws Exception {
		if (comp == null) {
			return "";
		}
		TCPropertyDescriptor desc = comp.getTypeComponent().getPropDesc(propName);
		System.out.println("propName:"+propName+"=="+desc+"=="+comp);
		if(desc==null)
			throw new Exception(comp+"对象上未找到属性"+propName);
		if (desc.getType() == TCPropertyDescriptor.SERVER_PROP_double) {
			if (KUtil.isEmpty(comp.getProperty(propName))) {
				return "";
			}
			return ProcessUtil.DF.format(comp.getDoubleProperty(propName));
		} else if (desc.getType() == TCPropertyDescriptor.SERVER_PROP_logical) {
			return comp.getLogicalProperty(propName) ? "Y" : "N";
		}
		return comp.getProperty(propName);
	}

	public String getValue() {
		String value = null;
		if(textField!=null) {
			value = textField.getText();
		}  else if (textArea != null) {
			value = textArea.getText();
		} else if(comboBox!=null) {
			String text = bigJtf.getText();
			value = lovDisRealMap.get(text);
		}
		//System.out.println("value==="+value);
		return value;
	}
	
	public String getAddtionalValue() {
		String value = null;
		if(textField!=null) {
			value = textField.getText();
		} else if (textArea != null) {
			value = textArea.getText();
		} else if(comboBox!=null) {
			int ind = comboBox.getSelectedIndex();
			ind = ind -1 ;
			if(ind>=0&&ind<KUtil.getLen(lov)) {
				value = additional[ind];
			}
		}
		return value;
	}


	public boolean checkRequire() {
		if (!require) {
			return true;
		}
		String val = getValue();
		return val != null && !"".equals(val);
	}

	public boolean checkCombox() {
		if(comboBox!=null) {
			String selectedItem = bigJtf.getText();
			System.out.println("selectedItem=="+selectedItem);
			if(selectedItem.isEmpty()) {
				return true;
			}
  		  for (Entry<String, OptionItem> optionItem : opHashMap.entrySet()) {
  			OptionItem value = optionItem.getValue();
  			if(value.getValue().equals(selectedItem)) {
  				return true;
  			}
		}
		}else {
			return true;
		}
       return false;
	}
	
	
	
	
	public void performChoose(AbstractAIFDialog dialog, String type, AbstractAIFApplication app, List<PrefComponent> prefComponents) {
		ChooseDialog chooseDialog = new ChooseDialog(dialog, new ChooseDialogController(app, type, this, prefComponents));
		if (!chooseDialog.initDialog()) {
			chooseDialog = null;
		}
		chooseDialog.showDialog();
		// ChooseDialog chooseDialog = null;
		// if (chooseDialogMap.containsKey(type)) {
		// chooseDialog = chooseDialogMap.get(type);
		// chooseDialog.showDialog();
		// return;
		// }
		// if (chooseDialog == null) {
		// chooseDialog = new ChooseDialog(dialog, new ChooseDialogController(app, type,
		// this, prefComponents));
		// if (!chooseDialog.initDialog()) {
		// chooseDialog = null;
		// }
		// }
		// if (chooseDialog != null) {
		// chooseDialog.showDialog();
		// chooseDialogMap.put(type, chooseDialog);
		// }
	}

	public void performChooseFromSql(AbstractAIFDialog dialog, AbstractAIFApplication app, List<PrefComponent> prefComponents, Map<String, TCComponent> revChildren) {
		ChooseFromSqlDialog chooseDialog = new ChooseFromSqlDialog(this, prefComponents, revChildren);
		if (chooseDialog.initDialog()) {
			chooseDialog.showDialog();
		}
	}

	/**
	 * 记录额外的控件，用于控制显示/隐藏
	 * 
	 * @param comp
	 */
	public void addAdditionalComp(JComponent comp) {
		this.additionalComps.add(comp);
	}

	/**
	 * 设置相关控件的显示/隐藏
	 * 
	 * @param visible
	 */
	public void setVisible(boolean visible) {
		label.setVisible(visible);
		getValueComp().setVisible(visible);
		for (JComponent c : additionalComps) {
			c.setVisible(visible);
		}
	}
	public String[] getDynamicLOV(TCComponentListOfValues lov) throws Exception {
		Vector<String> lovDisplayValueList = new Vector<>();
		Vector<String> lovDescValueList = new Vector<>();
//		lovDisplayValueList.add("");
//		Vector<String> lovValueList = new Vector<>();
		LOVService lovService = LOVService.getService((TCSession) AIFUtility.getCurrentApplication().getSession());
		InitialLovData input = new InitialLovData();
		LovFilterData filter = new LovFilterData();
		filter.sortPropertyName = "object_name";
		filter.order = 1;
		filter.numberToReturn = 1000;
		filter.maxResults = 1000;

		input.lov = lov;
		input.filterData = filter;
		LOVSearchResults result = lovService.getInitialLOVValues(input);
//		StringBuffer sb = new StringBuffer();
//		sb.append(">>");
		System.out.println("result.lovValues===="+result.lovValues.length);
		for (LOVValueRow row : result.lovValues) {
			Map<String, String[]> map = row.propDisplayValues;
//			Map<String, String[]> realmap = row.propInternalValues;
			for (String key : map.keySet()) {
				
				
				if(key.equals("object_desc")) {
					
					String[] v = map.get(key);
			
					lovDescValueList.add(v[0]);
				}
				
				if(!key.equals("object_name"))
					continue;
//				sb.append("UID:" + row.uid + ",key:" + key + "，value:" + map.get(key)[0]);
//				sb.append("\n");
				String[] v = map.get(key);
				lovDisplayValueList.add(v[0]);
//				lovValueList.add(realmap.get(key)[0]);
//				System.out.println("key:"+key+"=="+v.length+">>"+v[0]);
			}
		}
//		System.out.println("StringBuffer:"+sb.toString());
		descriptions = lovDescValueList.toArray(new String[lovDescValueList.size()]);
		return lovDisplayValueList.toArray(new String[lovDisplayValueList.size()]);
	}


	    
		public LinkedHashMap<String, ArrayList<String>>  listLov = new LinkedHashMap<String, ArrayList<String>>();
	    
		private void initLovTree(TCComponentListOfValues lov,TCSession session) {

			if (lov != null) {
				try {
					ListOfValuesInfo info = lov.getListOfValues();
					String[] valuesList = info.getStringListOfValues();
					System.out.println("initLovTree");

					if(valuesList != null && valuesList.length != 0) {
						System.out.println("valuesList======"+valuesList.length);
						for (String v : valuesList) {
							String disPlayv = info.getDisplayableValue(v);

							ArrayList<String> childLov = new ArrayList<String>();
							TCComponentListOfValues cLov = lov
									.getListOfFilterOfValue(v);
							AIFComponentContext[] children = lov.getChildren();
							if(children.length > 0) {
								InterfaceAIFComponent component = children[0].getComponent();
								String type = component.getType();
							}
							System.out.println("cLov======"+cLov);
							if(cLov != null) {
								String lovName = cLov.toString();
								TCComponentListOfValues lov111 = TCComponentListOfValuesType.findLOVByName(lovName);
								if ("Fnd0ListOfValuesDynamic".equals(lov111.getProperty("lov_type"))) {
									System.out.println("动态lovName=" + lovName);
									LOVService lovService = LOVService.getService(session);
									InitialLovData input = new InitialLovData();
									LovFilterData filter = new LovFilterData();
									if ("LD6_TecDoc_TypeLOV".equals(lovName)) {
										filter.sortPropertyName = "fnd0StringValues"; // lov的后台值
									} else {
										filter.sortPropertyName = "object_name"; // lov的后台值
									}

									filter.order = 1;
									filter.numberToReturn = 2000;
									filter.maxResults = 2000;

									input.lov = lov111;
									input.filterData = filter;
									LOVSearchResults result = lovService.getInitialLOVValues(input);
									// System.out.println("111==="+result.toString());

									for (LOVValueRow row : result.lovValues) {
										Map<String, String[]> map = row.propDisplayValues;
										Map<String, String[]> realmap = row.propInternalValues;
//										for (String key : map.keySet()) {
//											System.out.println("key=" + key + ",value=" + map.get(key)[0]);
//										}
//										for (String key : realmap.keySet()) {
//											System.out.println("key2=" + key + ",value2=" + map.get(key)[0]);
//										}
										String disval = "";
										String val = "";
										String key1 = "object_name";// 真实值 显示值第一列
										if ("LD6_TecDoc_TypeLOV".equals(lovName)) {
											key1 = "fnd0StringValues"; // lov的后台值
										}
										// String key2 = "object_desc";// 显示值第二列
										if (map.containsKey(key1)) {
											val = realmap.get(key1)[0];
											disval = map.get(key1)[0];
										}
										if (!val.equals("")) {
											childLov.add(disval);
										}

									}
									listLov.put(disPlayv, childLov);
								}else {
									List<LovValue> vals = lov111.getListOfValues().getValues();
													//descriptions = listOfValues.getDispDescription();//lov描述
												System.out.println("vals===="+vals.size());
													for (int i = 0; i < vals.size(); i++) {
														LovValue lovValue = vals.get(i);
														String realValue = lovValue.getValue() == null ? "" : lovValue.getValue().toString();
														//String disValue = lovValue.getDisplayValue();
														childLov.add(realValue);
													}
													
													listLov.put(disPlayv, childLov);
								}
							}

						}
					}
					
				} catch (TCException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		}
}
