package com.connor.ml.tcm.outfile.util;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;

/**
 * Adapter 实现 JTables 中的复制粘贴 剪贴板功能。 适配器所用的剪贴板数据格式 与 Excel 所用的剪贴板格式兼容。这提供了
 * 支持的 JTables 和 Excel 间的互操作。
 */
public class Adapter implements ActionListener {
	private String rowstring, value;
	private Clipboard system;
	private StringSelection stsel;
	private JTable jTable1;
	private List<List<Object>> selectValue = new ArrayList<List<Object>>();

	/**
	 * Excel 适配器由 JTable 构成， 它实现了 JTable 上的复制粘贴 功能，并充当剪贴板监听程序。
	 */

	public Adapter(JTable myJTable) {
		jTable1 = myJTable;
		KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C,
				ActionEvent.CTRL_MASK, false);

		// 确定复制按键用户可以对其进行修改
		// 以实现其它按键组合的复制功能。
		KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
				ActionEvent.CTRL_MASK, false);

		// 确定粘贴按键用户可以对其进行修改
		// 以实现其它按键组合的复制功能。

		jTable1.registerKeyboardAction(this, "Copy", copy,
				JComponent.WHEN_FOCUSED);

		jTable1.registerKeyboardAction(this, "Paste", paste,
				JComponent.WHEN_FOCUSED);

		system = Toolkit.getDefaultToolkit().getSystemClipboard();
	}

	/**
	 * 此适配器运行图表的公共读方法。
	 */
	public JTable getJTable() {
		return jTable1;
	}

	public void setJTable(JTable jTable1) {
		this.jTable1 = jTable1;
	}

	/**
	 * 在我们监听此实现的按键上激活这种方法。 此处，它监听复制和粘贴 ActionCommands。 包含不相邻单元格的选择导致选择无效，
	 * 而且此后复制动作无法执行。 粘贴的方法是将选定内容的左上角与 JTable 的当前选定内容的第一个元素对齐。
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().compareTo("Copy") == 0) {
			StringBuffer sbf = new StringBuffer();

			selectValue.clear();
			// 检查以确保我们仅选择了单元格的
			// 相邻块
			int numcols = jTable1.getSelectedColumnCount();
			int numrows = jTable1.getSelectedRowCount();
			int[] rowsselected = jTable1.getSelectedRows();
			int[] colsselected = jTable1.getSelectedColumns();

//			if (!((numrows - 1 == rowsselected[rowsselected.length - 1]
//					- rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1]
//					- colsselected[0] && numcols == colsselected.length))) {
//				JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
//						"Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
//
//				return;
//			}
			
			for (int i=0;i<numrows;i++)
	         {
	            for (int j=0;j<numcols;j++)
	            {
	            	if(jTable1.getValueAt(rowsselected[i],colsselected[j]) != null && jTable1.getValueAt(rowsselected[i],colsselected[j]).toString().indexOf("\n") >= 0)
	            	{
	            		sbf.append("\"");
	            		sbf.append(jTable1.getValueAt(rowsselected[i],colsselected[j]));
	            		sbf.append("\"");
	            	}
	            	else if(jTable1.getValueAt(rowsselected[i],colsselected[j]) == null)
	            	{
	            		sbf.append("");
	            	}
	            	else
	            	{
	            		sbf.append(jTable1.getValueAt(rowsselected[i],colsselected[j]));
	            	}
	               if (j<numcols-1)
	               {
	            	   sbf.append("\t".toString());
	            	   
	               }
	            }
	            sbf.append("\n".toString());
	         }

	         stsel  = new StringSelection(sbf.toString().trim());
	         system = Toolkit.getDefaultToolkit().getSystemClipboard();
	         system.setContents(stsel,stsel);
			
		}

		if (e.getActionCommand().compareTo("Paste") == 0) {
			System.out.println("Trying to Paste");
			//int startRow = (jTable1.getSelectedRows())[0];
			//int startCol = (jTable1.getSelectedColumns())[0];
			try {
				String trstring= (String)(system.getContents(this).getTransferData(DataFlavor.stringFlavor));

	             System.out.println("String is:"+trstring);
	             String[] values = trstring.split("\"");
	             StringBuffer sb = new StringBuffer();
	             //替换Excel中的换行符
	             for (int i = 0; i < values.length; i++) {
	            	 System.out.println(i+values[i]);
	            	 if(i % 2 ==0 && values[i].indexOf("\n") >= 0)
	            	 {
	            		 sb.append(values[i].replace("\n", " $")); 
	            	 }
	            	 else
	            	 {
	            		 sb.append(values[i]); 
	            	 }
					//System.out.println(i+s[i]);
				}
	             System.out.println("sb======"+sb.toString());
	             String copyValue = sb.toString();
	             String[] st1=copyValue.split("\\$");  //new StringTokenizer(sb.toString(),"$".toString());
	             
	             
	             
	           int[] rows = jTable1.getSelectedRows();
	           int[] columns = jTable1.getSelectedColumns();
	           int startRow = rows[0];
	           int startCol = columns[0];
	           if(rows.length ==1 )
	           {
		             for(int i=0;i<st1.length;i++)
		             {
		                rowstring=st1[i];
		                System.out.println("rowstring============"+rowstring);
		                if(rowstring.indexOf("\t") >= 0)
			            {
		                	String[] cellValue = rowstring.split("\t");
			                for(int j=0;j<cellValue.length;j++)
			                {
			                	value=(String)cellValue[j];
			                	System.out.println("value============"+value);
			                	if (startRow+i< jTable1.getRowCount()  &&
			                			startCol+j < jTable1.getColumnCount()-1)
			                	{
			                		jTable1.setValueAt(value.trim(),startRow+i,startCol+j);
			                	}
			                	System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+j);
			               }
			            }
		                else
		                {
		                	jTable1.setValueAt(rowstring.trim(),startRow+i,startCol);
		                }
		            }
	           }
	           else if(rows.length > 1 )
	           {
	        	   
	        	   //如果选择行大于复制行//选中行除以复制行
	        	   if(rows.length > st1.length)
	        	   {
	        		  // int num = rows.length / st1.length;
	        		   for (int i = 0; i < rows.length; i++) {
	        			   //for (int j = 0; j < num; j++) {
	        				   //for (int j2 = 0; j2 < st1.length; j2++) {
	        					   	rowstring=st1[(i+st1.length)%st1.length];
		   			                System.out.println("rowstring============"+rowstring);
		   			                if(rowstring.indexOf("\t") >= 0)
		   			                {
		   			                	String[] cellValue = rowstring.split("\t");
			   			                for (int k = 0; k < cellValue.length; k++) {
			   			                	value=(String)cellValue[k];
						                	System.out.println("value============"+value);
						                	jTable1.setValueAt(value.trim(),rows[i],startCol+k);
						                	System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
										}
		   			                }
		   			                else
		   			                {
		   			                	jTable1.setValueAt(rowstring.trim(),rows[i],startCol);
		   			                }
	        				   //}
	        			   //}
	        		   }
	        	   }
	        	   else //写入选中行内容
	        	   {
	        		   for(int i=0;i<st1.length;i++)
			            {
			                rowstring=st1[i];
			                System.out.println("rowstring============"+rowstring);
			                if(rowstring.indexOf("\t") >= 0)
   			                {
			                	String[] cellValue = rowstring.split("\t");
				                for(int j=0;j<cellValue.length;j++)
				                {
				                	value=(String)cellValue[j];
				                	System.out.println("value============"+value);
				                	if (startRow+i< jTable1.getRowCount()  &&
				                			startCol+j< jTable1.getColumnCount()-1)
				                	{
				                		jTable1.setValueAt(value.trim(),startRow+i,startCol+j);
				                	}
				                	System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+j);
				               }
   			                }
			                else
			                {
			                	jTable1.setValueAt(rowstring.trim(),startRow+i,startCol);
			                }
			            }
	        	   }
	           }
	           if(columns.length > st1[0].split("\t").length) //如果选中列数大于复制列数
        	   {
        		   System.out.println("========================================================================");
        		   if(rows.length > st1.length)
        		   {
        			   for (int i = 0; i < rows.length; i++) {
	        			   for (int j = 0; j < columns.length; j++) {
	        				   rowstring=st1[(i+st1.length)%st1.length];
	   			                System.out.println("rowstring============"+rowstring);
	   			                if(rowstring.indexOf("\t") >= 0)
	   			                {
	   			                	String[] cellValue = rowstring.split("\t");
		   			                for (int k = 0; k < cellValue.length; k++) {
		   			                	value=(String)cellValue[(j+cellValue.length)%cellValue.length];
					                	System.out.println("value============"+value);
					                	jTable1.setValueAt(value.trim(),rows[i],columns[j]);
					                	System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
									}
	   			                }
	   			                else
	   			                {
	   			                	jTable1.setValueAt(rowstring.trim(),rows[i],columns[j]);
	   			                }
	        			   }
	        		   }
        		   }
        		   else
        		   {
        			   for (int i = 0; i < st1.length; i++) {
        				   for (int j = 0; j < columns.length; j++) {
	        				   rowstring=st1[(i+st1.length)%st1.length];
	   			                System.out.println("rowstring============"+rowstring);
	   			                if(rowstring.indexOf("\t") >= 0)
	   			                {
	   			                	String[] cellValue = rowstring.split("\t");
		   			                for (int k = 0; k < cellValue.length; k++) {
		   			                	value=(String)cellValue[(j+cellValue.length)%cellValue.length];
					                	System.out.println("value============"+value);
					                	jTable1.setValueAt(value.trim(),startRow+i,columns[j]);
					                	System.out.println("Putting "+ value+"atrow="+startRow+i+"column="+startCol+k);
									}
	   			                }
	   			                else
	   			                {
	   			                	jTable1.setValueAt(rowstring.trim(),startRow+i,columns[j]);
	   			                }
	        			   }
        			   }
        		   }
        	   }
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
	}
}