package com.connor.processAttributeModification;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.connor.jingdiao.handlers.StandardDialog;
import com.connor.jingdiao.handlers.StandardDialog.TextAreaRenderer;
import com.connor.jingdiao.util.TCUtil;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.ListOfValuesInfo;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentActionHandler;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentListOfValues;
import com.teamcenter.rac.kernel.TCComponentListOfValuesType;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentTaskTemplate;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCHandlerType;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

public class ProcessAttriChangeDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	
	private TCSession session;
	private TCComponent[] modelsF;
	private TCComponentTask taskF;
	private LinkedHashMap<String, String[]> ruleOpsMapF;
	private int[] colsF;
	private JButton remarkBtn;
	private JButton exportBtn;
	private JButton closeBtn;
	private JTable impTable;
	private DefaultTableModel impModel;
	private ArrayList<TCComponentItemRevision> revlist;
	/**
	 * 内容：[rev,object_name] 即：对象类型，对象属性
	 */
	private String[] mark;
	private int mrow = -1;
	/**
	 * 存放标题行字段
	 */
	private List<String> tableHeaderList = new ArrayList<>();

	/**
	 * 配置的流程参数:key为属性真实值(object_name)，value为显示在看板上的名称(姓名)
	 */
	private Map<String, String> argMap = new HashMap<String, String>();
	/**
	 * 存储流程参数:key为属性真实值(object_name)，value为输入框对象(用于获取和设置输入值)
	 */
	private Map<String, Object> textAreaMap = new HashMap<>(); // 用于保存JTextArea的引用
	
	private Map<String, Object> testAnySR = new HashMap<String, Object>();
	/**
	 * 当前选中的table行对应的版本对象
	 */
	private TCComponentItemRevision targetRevision = null;

	private JPanel topPanel = null;
	/**
	 * 表格选中行的行数
	 */
	private int chooseRow = -1;

	/**
	 *
	 * @param session 会话对象
	 * @param models
	 * @param task 任务节点
	 * @param ruleOpsMap key为列名(名称)；value为一个String[]数组，String["item/rev","object_name"]
	 * @param cols
	 * @throws Exception
	 */
	public ProcessAttriChangeDialog(TCSession session, TCComponent[] models, TCComponentTask task, LinkedHashMap<String, String[]> ruleOpsMap, int[] cols)
			throws Exception {
		super(AIFUtility.getActiveDesktop());
		this.session = session;
		this.modelsF = models;
		this.taskF = task;
		this.ruleOpsMapF = ruleOpsMap;
		this.colsF = cols;
		this.argMap = getHandlerArgs(task);
		initUi( modelsF, taskF, ruleOpsMapF, colsF);
	}

	/**
	 * 初始化看板界面
	 * @param session
	 * @param models
	 * @param task
	 * @param ruleOpsMap key为列名(名称)；value为一个String[]数组，String["item/rev","object_name"]
	 * @param cols
	 * @throws Exception 
	 */
	private void initUi(TCComponent[] models, TCComponentTask task, LinkedHashMap<String, String[]> ruleOpsMap, int[] cols) throws Exception {
		System.out.println("开始初始化/刷新面板···");
		setTitle("编辑节点属性");
		remarkBtn = new JButton("修改属性");
		exportBtn = new JButton("导出Excel");
		closeBtn = new JButton("关闭");
		JPanel btnPanel = new JPanel(new FlowLayout());
		btnPanel.add(remarkBtn);
		btnPanel.add(exportBtn);
		btnPanel.add(closeBtn);

//		JPanel topPanel = new JPanel(new BorderLayout());
		if (topPanel == null) {
			topPanel = new JPanel(new BorderLayout());

		} else {
			topPanel.removeAll();
		}

		//TODO 重构属性设置面板
		if (this.argMap.isEmpty()){
			MessageBox.post(ProcessAttriChangeDialog.this, "获取Handler配置信息失败，请检查配置！", "ERROR", MessageBox.ERROR);
			return;
		}
		// 创建属性面板
		JPanel propertyPanel = new JPanel(new PropertyLayout());
		int k = 0;
		for (String key : this.argMap.keySet()) {//将流程配置的属性逐个渲染到看板上
			k++;
			String value = this.argMap.get(key);//属性显示名称
			System.out.println("流程配置信息Key: " + key + ", Value: " + value);
			String labLocation = String.valueOf(k)+".1.left.top";
			String fieldLocation = String.valueOf(k)+".2.left.top";
			propertyPanel.add(labLocation,new JLabel(value));

			//TODO 逻辑重构：根据不同属性类型，渲染不同的输入框
			String[] attrs = ruleOpsMap.get(value);
			String currentAttributeValue = null;//当前属性的值，用于渲染到看板输入框中
			if (this.targetRevision != null){
				System.out.println("info：已选中对象，开始根据选中对象的属性类型渲染组件···");
				TCComponentItem targetItem = this.targetRevision.getItem();
				//根据属性名称获取属性所属对象类型：item/rev
				String itemType = attrs[0];//item/rev
				String propertyName = attrs[1];//属性名称
				if (itemType.equals("item")){
					currentAttributeValue = targetItem.getProperty(propertyName);//获取当前属性的值

				}else {
					currentAttributeValue = targetRevision.getProperty(propertyName);//获取当前属性的值

				}
				//
				if (isLovType(propertyName)){
					System.out.println("属性【"+propertyName+"】类型为：LOV");

					Map<String, String> lovList = getUnitValue_display(session,propertyName);
					// 创建下拉列表组件
					JComboBox<String> comboBox = new JComboBox<>();

					// 将lovList中的value值添加到下拉列表
					for (String lovValue : lovList.values()) {
						comboBox.addItem(lovValue);
					}
					// 设置默认显示值（假设defaultValue是您希望默认显示的选项）
					comboBox.setSelectedItem(currentAttributeValue);
					propertyPanel.add(fieldLocation, comboBox);
					this.textAreaMap.put(propertyName, comboBox); //
				}else {//
					System.out.println("属性【"+ propertyName+"】类型非LOV	");

					JTextArea textArea = new JTextArea(); // 创建JTextArea
					textArea.setColumns(20); // 设置输入框宽度
					textArea.setLineWrap(true); // 启用自动换行
					textArea.setWrapStyleWord(true); // 按单词换行
					JScrollPane scrollPane = new JScrollPane(textArea);
					System.out.println("KUMA属性=" + value);
					if (value != null && (value.trim().contains("备注") || "备注".equals(value.trim()))){//备注特殊处理：加高度
						System.out.println("KUMA:特殊字段特殊处理！");
						scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
						textArea.setRows(3);
						scrollPane.setPreferredSize(scrollPane.getPreferredSize()); // 设置 JScrollPane 的首选尺寸
					}
					//赋值到textArea输入框中
					textArea.setText(currentAttributeValue);
					propertyPanel.add(fieldLocation, scrollPane);
					this.textAreaMap.put(key, textArea); // 将JTextArea保存到Map中
				}

			}else {
				System.out.println("info：未选中任何行，无法获取选中对象！渲染默认组件···");
				//渲染默认组件
				JTextArea textArea = new JTextArea(); // 创建JTextArea
				textArea.setColumns(20); // 设置输入框宽度
				textArea.setLineWrap(true); // 启用自动换行
				textArea.setWrapStyleWord(true); // 按单词换行
				propertyPanel.add(fieldLocation, new JScrollPane(textArea));
				this.textAreaMap.put(key, textArea); // 将JTextArea保存到Map中
			}
		}
		// 将属性面板放置在中心位置，btnPanel 放置在南边（底部）
		topPanel.add(propertyPanel, BorderLayout.CENTER);
		topPanel.add(btnPanel, BorderLayout.SOUTH);

		topPanel.revalidate();
		topPanel.repaint();
		
		String[] tableHeader = new String[ruleOpsMap.size() + 1];
		tableHeader[0] = "序号";
		int h = 1;
		for (String s : ruleOpsMap.keySet()) {
			tableHeader[h] = s;
//			if(s.equals("标准化备注")) {
				mark = ruleOpsMap.get(s);
//				mrow = h;
//			}
			h++;
		}
		//将标题行添加到列表中
		for (String tableHeader2 : tableHeader){
			tableHeaderList.add(tableHeader2);
		}
		impModel = new DefaultTableModel(tableHeader, 0);
		impTable = new JTable() {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		impTable.getTableHeader().setReorderingAllowed(false);
		impTable.setFillsViewportHeight(true);
		impTable.setEnabled(true);
		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		impTable.setModel(impModel);
		for (int i = 1; i < impModel.getColumnCount(); i++) {
			TableColumn col = impTable.getColumnModel().getColumn(i);
			col.setCellRenderer(new TextAreaRenderer());
			col.setPreferredWidth(150);
		}
		
		setDatas(task, (TCComponentDataset) models[0], ruleOpsMap);
		addActionListener(models, cols);

		setLayout(new BorderLayout());
		topPanel.setPreferredSize(new Dimension(260, getHeight())); // 设置宽度
		add(BorderLayout.EAST, topPanel);
		add(BorderLayout.CENTER, new JScrollPane(impTable));
		pack();
		setSize(new Dimension(1400, 500));
		setDefaultLookAndFeelDecorated(true);
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		setAlwaysOnTop(true);
		setVisible(true);
	}

	/**
	 * 判断属性是否为lov类型
	 * @param attrName 属性字段
	 * @return
	 */
	private boolean isLovType(String attrName){
		System.out.println("触发isLovType方法：判断是否是LOV属性~");
		TCComponentListOfValuesType lovType;
		try {
			lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues");
			TCComponentListOfValues[] lov = lovType.find(attrName);
			if (lov.length > 0)
				return true;
		} catch (TCException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 获得TC LOV值的<真实值,显示值>集合
	 * @param seesion
	 * @return
	 * @throws TCException
	 */
	private static Map<String, String> getUnitValue_display(TCSession seesion,String lovProp) throws TCException
	{
		Map<String, String> value_displays = new HashMap<String, String>();
		TCComponentListOfValues unitLov = getLov(seesion, lovProp);
		if(unitLov !=null)
		{
			ListOfValuesInfo listOfValues = unitLov.getListOfValues();
			String[] realval = listOfValues.getStringListOfValues();
			String value="";
			boolean flag = false;
			for (int i = 0; i < realval.length; i++) {
				String disval = listOfValues.getDisplayableValue(realval[i]);
				value_displays.put(realval[i], disval);
			}
		}
		return value_displays;
	}

	private static TCComponentListOfValues getLov(TCSession session, String lovName) {
		TCComponentListOfValuesType lovType;
		try {
			lovType = (TCComponentListOfValuesType) session.getTypeComponent("ListOfValues");
			TCComponentListOfValues[] lov = lovType.find(lovName);
			if (lov.length > 0)
				return lov[0];
		} catch (TCException e) {
			e.printStackTrace();
		}
		return null;
	}
	 
	/**
	 * 根据任务节点获取流程参数
	 * @param task
	 * @return
	 * @throws TCException 
	 */
	private Map<String, String> getHandlerArgs(TCComponentTask task) throws TCException {
		System.out.println("getHandlerArgs~");
		Map<String, String> returnHandlerArgMap = new HashMap<String, String>();
		TCComponent handlerComp = task.getHandler(TCHandlerType.ACTION, TCComponentTaskTemplate.COMPLETE_ACTION, "j6_Standard");//Connor_check_process_member
		if (handlerComp == null) {
			MessageBox.post(ProcessAttriChangeDialog.this, "根据节点任务获取handler失败！", "ERROR", MessageBox.ERROR);
			return null ;
		}
		TCComponentActionHandler handler = (TCComponentActionHandler) handlerComp;
		String[] args = handler.getArguments();//获取流程参数数组，每个参数形如 "argName=argValue"
		if (args == null) {
			MessageBox.post(ProcessAttriChangeDialog.this, "获取流程下的参数失败！", "ERROR", MessageBox.ERROR);
			return null ;
		}
		for (int j = 0; j < args.length; j++) {
			System.out.println("handler param: " + args[j]);
			int ind = args[j].indexOf("=");
			if (ind <= 0) {
				continue;
			}
			String argName = args[j].substring(0, ind);
			String argValue = args[j].substring(ind + 1);
			returnHandlerArgMap.put(argName, argValue);
		}
		return returnHandlerArgMap;
	}
	

	@SuppressWarnings("rawtypes")
	private void setDatas(TCComponentTask task, TCComponentDataset model, LinkedHashMap<String, String[]> ruleOpsMap) throws Exception {
		System.out.println("开始执行setDatas···");
		TCComponentTcFile[] files = model.getTcFiles();
		File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read(file);
		Element root = doc.getRootElement();
		Element condizione = root.element("condizione");
		List typeEs = condizione.element("object_type").elements();
		ArrayList<String> types = new ArrayList<>();
		for(Object e : typeEs) {
			types.add(((Element)e).getText());
		}
		List regolaEs = condizione.element("regola").elements();
		HashMap<String, Boolean> regolas = new HashMap<>();
		for(Object e : regolaEs) {
			String t = ((Element)e).getText();
			String name = ((Element)e).getName();
			if(name.equals("item"))
				name = "object_type";
			if(t.equals("*")) {
				regolas.put(name, false);
			}else {
				regolas.put(name, true);
			}
		}
		List rows = root.element("data").elements();
		AIFComponentContext[] contexts = TCUtil.getPseudoFolder(task, "root_target_attachments").getChildren();
		revlist = new ArrayList<>();
		for(AIFComponentContext c : contexts) {
			if(!types.contains(c.getComponent().getType()))
				continue;
			TCComponentItemRevision rev = (TCComponentItemRevision) c.getComponent();
			HashMap<String, String> props = new HashMap<>();
			for(String s : regolas.keySet()) {
				if(rev.getTCProperty(s) == null) {
					System.out.println(rev+" >> "+s+"\n属性未找到");
					throw new Exception("判断条件配置错误，请检查配置信息");
				}
				props.put(s, rev.getProperty(s));
			}
			ROW:for(Object e : rows) {
				for(Object t : ((Element)e).elements()) {
					String name = ((Element)t).getName();
					if(!props.containsKey(name))
						continue;
					String text = ((Element)t).getText();
					String val = props.get(name);
					if(regolas.get(name)) {
						if(text.equals("null")) {
							if(!val.isEmpty())
								continue ROW;
						}else if(!val.equals(text))
							continue ROW;
					}else if(!regolas.get(name) && !val.contains(text)) {
						continue ROW;
					}
				}
				TCComponentItem item = rev.getItem();
				String[] row = new String[ruleOpsMap.size()+1];
				row[0] = impTable.getRowCount()+1+"";
				int i = 1;
				for(String n : ruleOpsMap.keySet()) {
					row[i] = getProp(ruleOpsMap.get(n), item, rev);
					i++;
				}
				System.out.println("row:"+Arrays.toString(row));
				impModel.addRow(row);
				revlist.add(rev);
				break;
			}
		}
	}

	private void addActionListener(TCComponent[] models, int[] cols) {
		impTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {//单机鼠标
				System.out.println("触发单击选中事件~");
				try {
					chooseRow= impTable.getSelectedRow();
					System.out.println("当前选中行："+chooseRow);
					if(chooseRow < 0) {
						return;
					}
					targetRevision = revlist.get(chooseRow);
					if (targetRevision != null) {
						initUi(modelsF, taskF, ruleOpsMapF, colsF);
					}
					
//					for (String key : textAreaMap.keySet()){
//						String showAttr = argMap.get(key);//显示在右边看板上的待编辑的属性名称
//						//获取列数
//						for (int t = 0; t < tableHeaderList.size(); t++){
//							//为右侧编辑框赋值
//							if (tableHeaderList.get(t).equals(showAttr)){
////								textAreaMap.get(key).setText(""+impTable.getValueAt(row, t));
//								//TODO
//								String setValue = "" + impTable.getValueAt(row, t);
//								setModelValue(textAreaMap.get(key), setValue);
//
//
//								break;
//							}
//						}
//					}

				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post(ProcessAttriChangeDialog.this, "错误：" + e1.getMessage(), "ERROR", MessageBox.ERROR);
				}
			}

		});
		remarkBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {//修改属性按钮
				System.out.println("触发修改属性事件~");
				try {
//					int row = impTable.getSelectedRow();
					chooseRow = impTable.getSelectedRow();
					System.out.println("当前选中行："+chooseRow);
					if(chooseRow < 0) {
						MessageBox.post(ProcessAttriChangeDialog.this, "请选择要编辑的行！", "ERROR", MessageBox.ERROR);
						return;
					}
					for (String key : textAreaMap.keySet()){
//						String text = textAreaMap.get(key).getText();//获取输入框中的值
						//
						Object component = textAreaMap.get(key);
						String text = getValueByAreaType(component);
						if (text == null){
							System.out.println("info：获取输入框组件值异常！");
						}
						
						String showAttr = argMap.get(key);//获取流程参数的value
						if(text.getBytes().length > 1024) {
							MessageBox.post(ProcessAttriChangeDialog.this, showAttr+"属性填写长度过长，无法修改！", "ERROR", MessageBox.ERROR);
							return;
						}else {
							//获取列数
							for (int t = 0; t < tableHeaderList.size(); t++){
								if (tableHeaderList.get(t).equals(showAttr)){
									impTable.setValueAt(text, chooseRow, t);
									break;
								}
							}
							
						}
					}

					TCComponentItemRevision rev = revlist.get(chooseRow);
					TCComponentItem item = rev.getItem();
					if(mark[0].equals("item") && item.isCheckedOut()) {
						MessageBox.post(ProcessAttriChangeDialog.this, item+" 已签出，无法修改！", "ERROR", MessageBox.ERROR);
						return;
					}else if(mark[0].equals("rev") && rev.isCheckedOut()) {
						MessageBox.post(ProcessAttriChangeDialog.this, rev+" 已签出，无法修改！", "E      RROR", MessageBox.ERROR);
						return;
					}
					MethodUtil.openByPass(session);
					if(mark[0].equals("item")) {
						for (String key : textAreaMap.keySet()){
//							String value = textAreaMap.get(key).getText();
							Object component = textAreaMap.get(key);
							String inputValue = getValueByAreaType(component);
							if (inputValue == null){
								System.out.println("info：获取输入框组件值异常！");
							}

							item.setProperty(key, inputValue);
						}
					}else if(mark[0].equals("rev")) {
						for (String key : textAreaMap.keySet()){
//							String value = textAreaMap.get(key).getText();
							Object component = textAreaMap.get(key);
							String inputValue = getValueByAreaType(component);
							if (inputValue == null){
								System.out.println("info：获取输入框组件值异常！");
							}
							rev.setProperty(key, inputValue);
						}
					}
					MethodUtil.closeByPass(session);
				}catch(Exception e1) {
					e1.printStackTrace();
					MessageBox.post(ProcessAttriChangeDialog.this, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					try {
						MethodUtil.closeByPass(session);
					}catch(Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		});

		exportBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("触发导出事件~");
				FileInputStream input = null;
				FileOutputStream output = null;
				XSSFWorkbook wb = null;
				try {
					File directory = TCUtil.saveExcelChooser(ProcessAttriChangeDialog.this, "");
					if(directory==null)
						return;
					if(directory.exists())
						directory.delete();
					TCComponentDataset model = (TCComponentDataset) models[1];
					TCComponentTcFile[] files = model.getTcFiles();
					File file = files[0].getFile(System.getProperty("java.io.tmpdir"));
					input = new FileInputStream(file);
					wb = new XSSFWorkbook(input);
					XSSFSheet sheet = wb.getSheetAt(0);
					XSSFRow row;
					XSSFCell cell;
					row = getRow(sheet, cols[0]);
					TableColumnModel cm = impTable.getColumnModel();
					for(int i=0; i<cm.getColumnCount(); i++) {
						cell = getCell(row, i);
						cell.setCellValue(cm.getColumn(i).getHeaderValue().toString());
					}
					for(int i=0; i<impTable.getRowCount(); i++) {
						row = getRow(sheet, i + cols[1]);
						for(int j=0; j<impTable.getColumnCount(); j++) {
							cell = getCell(row, j);
							cell.setCellValue(impTable.getValueAt(i, j).toString());
						}
					}
					output = new FileOutputStream(file.getPath());
					wb.write(output);
					input.close();
					output.close();
					file.renameTo(directory);
					MessageBox.post(ProcessAttriChangeDialog.this, "导出完成！", "提示", MessageBox.INFORMATION);
				}catch(Exception e1) {
					e1.printStackTrace();
					MessageBox.post(ProcessAttriChangeDialog.this, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
				}finally {
					if(input!=null)
						try {
							input.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					if(output!=null)
						try {
							output.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			}
		});
		
		closeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
	}
	

	/**
	 *  根据组件类型设置显示值
	 * @param object
	 * @param setValue
	 */
	private void setModelValue(Object object, String setValue) {
		// TODO 自动生成的方法存根
		
	}

	/**
	 * 根据组件类型获取值
	 * @param component 输入框组件（JComboBox，JTextArea）
	 * @return
	 */
	private String getValueByAreaType(Object component){
		if (component instanceof JComboBox) {
			// 如果是JComboBox，获取选中的项
			JComboBox<?> comboBox = (JComboBox<?>) component;
			String selectedItem = (String) comboBox.getSelectedItem();
//			System.out.println("JComboBox selected item: " + selectedItem);
			return selectedItem;
		} else if (component instanceof JTextArea) {
			// 如果是JTextArea，获取文本内容
			JTextArea textArea = (JTextArea) component;
			String text = textArea.getText();
//			System.out.println("JTextArea text: " + text);
			return text;
		}
		return null;
	}
	
	private String getProp(String[] ps, TCComponentItem item, TCComponentItemRevision rev) throws Exception {
		if(ps[0].equals("item")) {
			return item.getProperty(ps[1]);
		}else if(ps[0].equals("rev")) {
			return rev.getProperty(ps[1]);
		}
		return "";
	}

	private XSSFRow getRow(XSSFSheet sheet, int num) throws Exception {
		XSSFRow row = sheet.getRow(num);
		if(row==null)
			row = sheet.createRow(num);
		return row;
	}
	private XSSFCell getCell(XSSFRow row, int col) throws Exception {
		XSSFCell cell = row.getCell(col);
		if(cell==null)
			cell = row.createCell(col);
		return cell;
	}

	public class TextAreaRenderer extends JTextArea implements TableCellRenderer {
		private static final long serialVersionUID = 1L;
	     
	    public TextAreaRenderer() {
	        setLineWrap(true); //利用JTextArea的自动换行方法
	        setWrapStyleWord(true);
		}

		public Component getTableCellRendererComponent(JTable table, Object value,   
	            boolean isSelected, boolean hasFocus, int row, int column) {
			// 计算当下行的最佳高度   
			int maxPreferredHeight = 22;
			JTextArea cell = new JTextArea();
			for (int i=0; i<table.getColumnCount(); i++) {
				cell.setText("" + table.getValueAt(row, i));
				maxPreferredHeight = Math.max(maxPreferredHeight, 
						(cell.getPreferredSize().width/table.getColumnModel().getColumn(i).getWidth()+1)*cell.getPreferredSize().height+7);
			}
			if (table.getRowHeight(row) != maxPreferredHeight) 
				// 少了这行则处理器瞎忙   
				table.setRowHeight(row, maxPreferredHeight);
	   
			setText(value == null ? "" : value.toString());   
			fillColor(table,this,isSelected);
			return this;   
	    }
		
		public void fillColor(JTable t,JTextArea l,boolean isSelected ){
			if(isSelected){
				l.setBackground(t.getSelectionBackground());
				l.setForeground(t.getSelectionForeground());
			} else {
	            l.setBackground(t.getBackground());
	            l.setForeground(t.getForeground());
	        }
	    }
	}
}

