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

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

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

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.TCProperty;
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.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.util.OptionItem;
import cn.net.connor.std.processedit.util.TwoColumnRenderer;

public class PrefComponent {
	
	private static final int INPUT_FIELD_WIDTH = 200; // 像素
	private static final int INPUT_FIELD_HEIGHT = 30;
	private static final int TEXT_AREA_ROWS = 8;
	private static final int TEXT_AREA_COLS = 38; // 约等于 300px 宽度
	public boolean isLovParent = false;
	public boolean isLovChild = false;
	
	
	public String lovName;
	
	public JTextField bigJtf;
	public static final String REQUIRE = "*";
	public static final String READONLY = "#";
	public static final String INVISIBLE = "@";
	public static final String TEXTAREA = "$";
	public static final Registry REG = Registry.getRegistry(PrefComponent.class);
	public boolean isTextArea = false;
	public JPanel panel;
	public String configStr;
	public boolean require = false;
	public boolean readonly = false;
	public boolean invisible = false;
	public String title;
	public String propConfig;
	public String fromPropConfig;
	public String[] additional;
	public String[] lov;
	public String[] displayLov;
	public String[] descriptions;
	public iTextField textField;
	private iTextArea textArea;
	public JComboBox comboBox;
	  public ArrayList<String> list = new ArrayList<String>();
	private int textLength = -1;
	public TCComponentItemRevision rev;
	public HashMap<String,OptionItem> opHashMap = new HashMap<String, OptionItem>();
	public HashMap<String,String> lovDisRealMap = new HashMap<String, String>();
	public PrefComponent(String pref, TCComponentItemRevision targetRev) {
		this.configStr = pref;
		this.rev = targetRev;
	}

	public boolean init(TCSession session) throws Exception{
		System.out.println("configStr==="+configStr);
		if (KUtil.isEmpty(configStr)) {
			return false;
		}
		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(INVISIBLE)) {
			configStr = configStr.substring(1);
			this.invisible = 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.fromPropConfig = split[2];
		}
		if (len > 3 && !KUtil.isEmpty(split[3])) {
			this.lov = split[3].split(";");
		}
		if (len > 4 && !KUtil.isEmpty(split[4])) {
			try {
				this.textLength = Integer.parseInt(split[4].trim());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (KUtil.isEmpty(title)) {
			return false;
		}
		if ("object_type".equals(propConfig)) {
			int lovCnt = KUtil.getLen(lov);
			displayLov = new String[lovCnt];
			descriptions = new String[lovCnt];
			additional = new String[lovCnt];
			for (int i = 0; i < lovCnt; i++) {
				String typeName = lov[i];
				String relName = "";
				int ind = typeName.indexOf('-');
				if(ind>0) {
					relName = typeName.substring(ind+1);
					typeName = typeName.substring(0,ind);
				}
				lov[i]=typeName;
				displayLov[i] = KUtil.getTypeName(session, typeName);
				descriptions[i] = "";
				additional[i] = relName;
				lovDisRealMap.put(displayLov[i], lov[i]);
				
			}
		} else if(lov!=null && lov.length==1) {//TODO
			lovName = lov[0];
			if(lov[0].contains("^A")) {
				lovName = lovName.split("\\^")[0];
				isLovParent = true;
				
				
//				TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues");
//				TCComponentListOfValues[] lovs = lovType.find(lov[0]);
//				if(lovs==null || lovs.length==0) {
//					throw new Exception(String.format(REG.getString("lovnotfound.ERROR1"), lov[0]));
//				}
//				displayLov = getDynamicLOV(lovs[0]);
			
				//TODO 

				
				TCComponentListOfValues lovComp = KUtil.getLov(session, lovName);
				
				if (lovComp == null) {
					throw new Exception(String.format(REG.getString("lovnotfound.ERROR1"), lovName));
				}
				
				
				initLovTree(lovComp,session);
				System.out.println("lovList==="+listLov.toString());
				
				
				
				List<LovValue> vals = lovComp.getListOfValues().getValues();
				int lovCnt = vals == null ? 0 : vals.size();
				
//				
//				Map<String, String[]> lovTWO = getLovTWO(session,lov[0]);
//				
//				System.out.println("lovTWO======"+lovTWO.toString());
//				
//				Map<String, String> lovTh = getLovThreeRealValue(session,lov[0]);
//				
//				System.out.println("lovTh======"+lovTh.toString());
				
				
				initLovTree(lovComp,session);
				System.out.println("lovList==="+list.toString());
				
				
				ListOfValuesInfo listOfValues = lovComp.getListOfValues();
				System.out.println("lovCnt=="+lovCnt);
				if (lovCnt>0) {
					descriptions = listOfValues.getDispDescription();//lov描述
					System.out.println("getListOfValues:"+lovName+lovCnt);
					this.lov = new String[lovCnt];
					this.displayLov = 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]);
					}
				}
			
			
			}else if(lovName.contains("^B")) {
				lovName = lovName.split("\\^")[0];
				isLovChild = true;
			}else {
//				TCComponentListOfValuesType lovType = (TCComponentListOfValuesType)session.getTypeComponent("ListOfValues");
//				TCComponentListOfValues[] lovs = lovType.find(lov[0]);
//				if(lovs==null || lovs.length==0) {
//					throw new Exception(String.format(REG.getString("lovnotfound.ERROR1"), lov[0]));
//				}
//				displayLov = getDynamicLOV(lovs[0]);
				lovName = lov[0];
				//TODO 
				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();
				
//				
//				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==="+list.toString());
				
				
				ListOfValuesInfo listOfValues = lovComp.getListOfValues();
				System.out.println("lovCnt=="+lovCnt);
				if (lovCnt>0) {
					descriptions = listOfValues.getDispDescription();//lov描述
					System.out.println("getListOfValues:"+lovName+lovCnt);
					this.lov = new String[lovCnt];
					this.displayLov = 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]);
					}
				}
			
			
			}
			

		
		} else {
			displayLov = lov;
		}
		initPanel();
		initComponent();
		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(rev!=null&&!KUtil.isEmpty(fromPropConfig)) {
			String value = getConfigPropValue(rev,fromPropConfig);
			System.out.println(">> Load Property: "+fromPropConfig+" = "+value);
			if(textField!=null) {
				textField.setText(value);
			}
			if(comboBox!=null) {
				comboBox.setSelectedItem(value);
			}
		}
	}
	
	public static String getConfigPropValue(TCComponentItemRevision rev, String propConfigStr) throws Exception {
		if (rev == null || KUtil.isEmpty(propConfigStr)) {
			return "";
		}
		StringBuilder res = new StringBuilder();
		String[] propConfigSplit = propConfigStr.split("\\+");
		int len = KUtil.getLen(propConfigSplit);
		for (int i = 0; i < len; i++) {
			String propConfig = propConfigSplit[i];
			String propFrom = null, propName = null;
			String[] split = propConfig.split("\\.");
			if (KUtil.getLen(split) == 2) {
				propFrom = split[0].trim().toUpperCase();
				propName = split[1].trim();
			}
			if (KUtil.isEmpty(propFrom) || KUtil.isEmpty(propName)) {
				res.append(propConfig);
				continue;
			}
			TCComponent target = null;
			if ("ITEM".equals(propFrom)) {
				target = rev.getItem();
			} else if ("REV".equals(propFrom)) {
				target = rev;
			} else if ("IRELA".equals(propFrom)) {
				TCComponent[] targets = rev.getRelatedComponents("Ac5_Processroute_Irela");
				int targetCnt = KUtil.getLen(targets);
				for(int k=0;k<targetCnt;k++) {
					if("Ac5_Processroute_FM".equals(targets[k].getType())) {
						target = targets[k];
						break;
					}
				}
			} else if ("ITEMMASTER".equals(propFrom)) {
				target = rev.getItem().getRelatedComponent("IMAN_master_form");
			} else if ("REVMASTER".equals(propFrom)) {
				target = rev.getRelatedComponent("IMAN_master_form_rev");
			} else {
				throw new Exception(String.format(REG.getString("proplocationnotdefined.ERROR1"), propFrom));
			}
			if(target !=null) {
				TCProperty prop = target.getTCProperty(propName.trim());
				if (prop == null) {
					throw new Exception(String.format(REG.getString("propnotdefinedintype.ERROR2"), target.getType(), propName));
				}
				res.append(prop.getStringValue());
			}
		}
		return res.toString();
	}

	

	
	
	private void initPanel() {
	    this.panel = new JPanel(new GridBagLayout());
	    // 不再硬编码尺寸，让布局自动适应内容
	    // this.panel.setPreferredSize(new Dimension(260, 40));

	    GridBagConstraints gbc = new GridBagConstraints();
	    gbc.insets = new Insets(6, 6, 6, 6); // 与 initMEPropPanel 一致
	    gbc.fill = GridBagConstraints.HORIZONTAL;
	    gbc.weightx = 1.0;
	    gbc.weighty = 0; // 不抢占垂直空间

	    
	    if(isLovChild) {
		    // 构建 label
		    String labelText = "<html>" + title;
		    if (require) {
		        labelText += "<font color='red'>*</font>";
		    }
		    labelText += "</html>";
		    JLabel label = new JLabel(labelText);

		    // === 开始新行：label 是第一个组件 ===
		    KUtil.newRow(panel, label, gbc, 1);

			
			
	        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();
				}
			});
	        
	        
	        
	        
	        
	        

	        KUtil.addCol(panel, comboBox, gbc, 1, 1);

	    

				
	    }else {
		    int len = KUtil.getLen(displayLov);

		    // 构建 label
		    String labelText = "<html>" + title;
		    if (len > 0 && require) {
		        labelText += "<font color='red'>*</font>";
		    }
		    labelText += "</html>";
		    JLabel label = new JLabel(labelText);

		    // === 开始新行：label 是第一个组件 ===
		    KUtil.newRow(panel, label, gbc, 1);

		    // === 添加输入控件到同一行 ===
		    if (len > 0) {
		        comboBox = new JComboBox();
		        comboBox.setRenderer(new TwoColumnRenderer());
		        comboBox.insertItemAt(null, 0);
		       comboBox.setSelectedIndex(0);
				comboBox.setEditable(true);
				comboBox.setPreferredSize(new Dimension(INPUT_FIELD_WIDTH, INPUT_FIELD_HEIGHT));
				comboBox.setMaximumSize(new Dimension(INPUT_FIELD_WIDTH, INPUT_FIELD_HEIGHT * 2)); // 防止过高
		        
		        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());
				 bigJtf.setPreferredSize(new Dimension(INPUT_FIELD_WIDTH - 20,
				 INPUT_FIELD_HEIGHT - 4)); 
			    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();
					}
				});
		        
		        
		        
		        
		        
		        

		        KUtil.addCol(panel, comboBox, gbc, 1, 1);

		    } else {
		        if (isTextArea) {
		        	textArea = new iTextArea(TEXT_AREA_ROWS, TEXT_AREA_COLS);
		            textArea.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		            textArea.setLineWrap(true);
		            textArea.setWrapStyleWord(true);
		            
		        	textArea.setPreferredSize(new Dimension(INPUT_FIELD_WIDTH, 
			        	    TEXT_AREA_ROWS * INPUT_FIELD_HEIGHT + 10)); // 留点边距

		            
		            textArea.addFocusListener(new FocusAdapter() {
		                public void focusGained(FocusEvent e) {
		                    SwingTextContextActivator.instance().activateContext();
		                }
		                public void focusLost(FocusEvent e) {
		                    super.focusLost(e);
		                    SwingTextContextActivator.instance().deactivateContext();
		                }
		            });
		            // textArea 占据控件位置（第1列），不跨行
		            KUtil.addCol(panel, textArea, gbc, 1, 1);

		        } else {
		            textField = new iTextField(textLength > 0 ? textLength : 12);
		            textField.setPreferredSize(new Dimension(INPUT_FIELD_WIDTH, INPUT_FIELD_HEIGHT));
		            KUtil.addCol(panel, textField, gbc, 1, 1);
		        }

		        // 如果需要额外按钮（类似 initMEPropPanel 中的逻辑），可在此添加
		        // 例如：
		        // if ("some_prop".equals(propConfig)) {
		        //     KUtil.addCol(panel, new JButton("..."), gbc, 1, 0);
		        // }
		    }

		    // 可选：如果 textLength > 0 需要占位符（但通常不需要）
		    // if (textLength > 0 && !isTextArea) {
		    //     KUtil.addCol(panel, new JLabel(""), gbc, 1, 1);
		    // }
	    }
	    
	    
	    
	    

	}
	
	
	


	public Component getPanel() {
		return panel;
	}
	
	public boolean isInvisible() {
		return invisible;
	}

	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 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(">>");
		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();
			}
		}

	}
	
	
	
	
	
}
