package com.connor.bomCompare;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.accessibility.AccessibleContext;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.RowSorter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import com.teamcenter.rac.aif.AbstractAIFApplication;
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.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.pse.operations.ExpandBelowOperation;
import com.teamcenter.rac.psebase.AbstractBOMLineViewerApplication;
import com.teamcenter.rac.psebase.common.AbstractViewableNode;
import com.teamcenter.rac.psebase.common.AbstractViewableTreeTable;
import com.teamcenter.rac.treetable.IViewableNode;
import com.teamcenter.rac.treetable.TreeTableNode;


public class CXGYFrame  extends JFrame{
	private AbstractAIFApplication app;
	private TCSession session;
	private InterfaceAIFComponent comp1;
	private InterfaceAIFComponent comp2;
	private List<String> comp1List=new ArrayList<String>();//订单bom数据。零部件ID
	private Map<String,List<String>> comp1Data=new HashMap<String,List<String>>();//订单bom数据
	private List<String> comp2List=new ArrayList<String>();//订单工艺数据，消耗件ID
	private Map<String,List<String>> comp2Data=new HashMap<String,List<String>>();//订单工艺数据
	
	private int selectButton=1;
	private List<Integer> lightRow=new ArrayList<Integer>();//高亮行的行号
	
	
	private Vector table1Vector = new Vector();
	private Vector table2Vector = new Vector();
	private Vector table3Vector = new Vector();
	private String[] Names;
	private JLabel headLabel;//源对象
	private JLabel targetLabel;//目标对象
	private JTextArea headName;// 源对象名称
	private JTextArea targetName;// 目标对象名称
	private JButton[] topBtns;
	private CardLayout tableSwitch = new CardLayout();
	private JPanel table;
	private boolean isturn=true;
	private JButton refreshButton;// 刷新
	private JButton cancelButton;// 取消
	private int selectRow=-1;
	//表格
	private JTable mainTable1;
	private String[] header1 = new String[]{"序号","ID","名称","数量"};
	
	
	public CXGYFrame(TCSession session,InterfaceAIFComponent comp1,InterfaceAIFComponent comp2,String[] Names) {
		super();
		this.session = session;
		this.Names=Names;
		this.comp1=comp1;
		this.comp2=comp2;
		
		init();
		
	}
	
	private void init() {
		try {
			getMEOP1(comp1);
			getMEOP2(comp2);
		} catch (TCException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}
		
		compareData();
		this.setTitle("对比结果");
		this.setSize(new Dimension(1000, 600));
		this.setLayout(new BorderLayout());
		this.setResizable(true);
		this.setAlwaysOnTop(true);
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		
		Container container = this.getContentPane();
		container.setLayout(new BorderLayout());
		container.setSize(new Dimension(1000, 600));
		
		
		JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		
		this.headLabel=new JLabel("源目标");
		this.headLabel.setPreferredSize(new Dimension(450,20));
		this.targetLabel=new JLabel("目标对象");
		this.targetLabel.setPreferredSize(new Dimension(450,20));
		
		this.headName=new JTextArea(Names[0]);
		this.headName.setPreferredSize(new Dimension(450,60));
		this.targetName=new JTextArea(Names[1]);
		this.targetName.setPreferredSize(new Dimension(450,60));
		
		
		
		panel1.add("1.1.left.top",headLabel);
		panel1.add("1.2.left.top",targetLabel);
		panel1.add("2.1.left.top",headName);
		panel1.add("2.2.left.top",targetName);
		panel1.setPreferredSize(new Dimension(1000,100));
		
		
		//JPanel topBtnPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		topBtns = new JButton[3];
		topBtns[0] = new JButton("源对象独有数据");
		topBtns[1] = new JButton("目标对象独有数据");
		topBtns[2] = new JButton("数量差异数据");
		topBtns[0].setSelected(true);
		for (JButton btn : topBtns) {
			panel2.add("1.1.left.top",btn);
			btn.addActionListener(panelSwitch());
		}
		
		
		Vector headVector = new Vector();
		headVector.add("序号");
		headVector.add("ID");
		headVector.add("名称");
		headVector.add("数量");
		
		DefaultTableModel dtm = new DefaultTableModel(table1Vector,headVector);
		
		mainTable1=new JTable(dtm);
		mainTable1.setRowHeight(30);
		//mainTable1.setEnabled(false);//设置表格不可编辑
		mainTable1.addMouseListener(new MouseAdapter() {
		/**
		*鼠标监听
		*/
    public void mouseClicked(MouseEvent e) {
    	//获取当前的行
        int row = mainTable1.getSelectedRow();
        AbstractBOMLineViewerApplication bomapp = (AbstractBOMLineViewerApplication) AIFUtility
        	     .getCurrentApplication();
        	   AbstractViewableTreeTable m_tree = null;
        	   // 获取BOM树
        	   if (m_tree == null) {
        	    m_tree = bomapp.getAbstractViewableTreeTable();
        	   } else {
        	    m_tree = bomapp.getAbstractViewableTreeTable();

        	   }
        	   
        	// 展开BOM
        	   ExpandBelowOperation operation = new ExpandBelowOperation(m_tree);
        	  // session.queueOperation(operation);
        	   session.queueOperation(operation, true);
            	// session.queueOperation(operation, false);
        	//根据当前选中的表格和顶层bom类型来判断获取表格哪个值
        	  AbstractViewableNode  TopNode= m_tree.getRootNode();
        	  //获取顶层bom类型
        	  String type="";
        	  try {
				type=TopNode.getBOMLine().getItem().getType();
			} catch (TCException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
        	  String ID="";
        	  switch (selectButton) {
				case 1:
					 ID=(String) mainTable1.getValueAt(row, 1);
					break;
				case 2:
					 ID=(String) mainTable1.getValueAt(row, 1);
					break;
				case 3:
				try {
					if(type.equals(((TCComponentBOMLine)comp1).getItem().getType())) {
						ID=(String) mainTable1.getValueAt(row, 1);
					}else {
						ID=(String) mainTable1.getValueAt(row, 4);
					}
				} catch (TCException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
					break;
				default:
				}
        	  
        	 try {
        		getNode(TopNode,ID,m_tree);
        		 if(selectRow>0) {
        			 m_tree.clearSelection();
        			 m_tree.setRowSelectionInterval(selectRow,selectRow);
        			 selectRow=-1;
        		 }else {
        			 m_tree.clearSelection();
        			 selectRow=-1;
        		 }
			} catch (NumberFormatException | TCException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        	 session.queueOperation(operation, false);
        	
    }
});
		JScrollPane J1= new JScrollPane();
		J1.setPreferredSize(new Dimension(900, 300));
		J1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		J1.setViewportView(mainTable1);
		panel2.add("2.1.left.top",J1);
		
		this.refreshButton=new JButton("刷新");
		this.refreshButton.addActionListener(new ActionListener() {
			 // 当按钮被点击时，就会触发 ActionEvent事件
			 // actionPerformed 方法就会被执行
			 public void actionPerformed(ActionEvent e) {
				 dispose();
				 CXGYFrame sj=new CXGYFrame(session,comp1,comp2,Names);
			 }
		 });
		this.cancelButton=new JButton("取消");
		this.cancelButton.addActionListener(new ActionListener() {
			 // 当按钮被点击时，就会触发 ActionEvent事件
			 // actionPerformed 方法就会被执行
			 public void actionPerformed(ActionEvent e) {
				 dispose();
			 }
		});
		panel3.add(this.refreshButton);
		panel3.add(this.cancelButton);
		panel3.setPreferredSize(new Dimension(1000,100));
		
		
		
		
		container.add(panel1,BorderLayout.NORTH);
		container.add(panel2, BorderLayout.CENTER);
		container.add(panel3, BorderLayout.SOUTH);
		//container.add(table, BorderLayout.SOUTH);
		
	}
	
	private ActionListener panelSwitch() {
		return new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String text = ((JButton) e.getSource()).getText();
				for (int i = 0; i < topBtns.length; i++) {
					topBtns[i].setSelected(topBtns[i].getText().equals(text));
				}
				switch (text) {
				case "源对象独有数据":
					Vector headVector1 = new Vector();
					headVector1.add("序号");
					headVector1.add("ID");
					headVector1.add("名称");
					headVector1.add("数量");
					
					DefaultTableModel dtm1=(DefaultTableModel)mainTable1.getModel();//获取表格模型
					dtm1.setDataVector(table1Vector,headVector1);//设置新内容
					mainTable1.updateUI();//更新显示
					selectButton=1;
					break;
				case "目标对象独有数据":
					Vector headVector2 = new Vector();
					headVector2.add("序号");
					headVector2.add("ID");
					headVector2.add("名称");
					headVector2.add("数量");
					
					DefaultTableModel dtm2=(DefaultTableModel)mainTable1.getModel();//获取表格模型
					dtm2.setDataVector(table2Vector,headVector2);//设置新内容
					mainTable1.updateUI();//更新显示
					selectButton=2;
					break;
				case "数量差异数据":
					Vector headVector3 = new Vector();
					headVector3.add("序号");
					headVector3.add("ID");
					headVector3.add("名称");
					headVector3.add("数量");
					headVector3.add("ID");
					headVector3.add("名称");
					headVector3.add("数量");
					
					DefaultTableModel dtm3=(DefaultTableModel)mainTable1.getModel();//获取表格模型
					dtm3.setDataVector(table3Vector,headVector3);//设置新内容
					mainTable1.updateUI();//更新显示
					selectButton=3;
					break;
				default:
//					createLogDataSourceTable();
				}
			}

		};
	}

	
//	//获取订单BOM对象数据
//	private void getData(InterfaceAIFComponent comp) throws TCException {
//		
//	}
//		//获取订单工艺对象数据
//		private void getOPData(InterfaceAIFComponent comp) throws TCException {//bl_occ_type
//			getMEOP(comp);
//			}
		
		private void getMEOP1(InterfaceAIFComponent MEOP) throws TCException {
			AIFComponentContext[] meops=((TCComponentBOMLine) MEOP).getChildren();
			
			//事例类型为消耗件
			if(((TCComponentBOMLine)MEOP).getItemRevision().getType()!=null) {
				List<String> partData=new ArrayList<String>();
				
				if(!comp1List.contains(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"))) {
					comp1List.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));//获取ID
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("object_name"));//获取名称
					partData.add(((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity")==null||((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity").equals("")?
							"1":((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity"));//获取数量
					comp1Data.put(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"), partData);
				}else {
					Float oldnum=Float.valueOf(comp1Data.get(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id")).get(2));
					Float newnum=Float.valueOf(((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity")==null||((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity").equals("")?
							"1":((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity"));
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));//获取ID
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("object_name"));//获取名称
//					//可以去除小数点后面多余的.0
//					partData.add(String.valueOf(new BigDecimal(oldnum+newnum).stripTrailingZeros()));//累计数量
					partData.add(String.valueOf(oldnum+newnum));//累计数量
					comp1Data.put(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"),partData);
				}
				
			}
			
			if((meops.length==0||meops==null)) {
				return;
			}else {
				for(AIFComponentContext meop:meops) {
					getMEOP1(((TCComponentBOMLine)meop.getComponent()));
				}
			}
		}
		
		
		
		private void getMEOP2(InterfaceAIFComponent MEOP) throws TCException {
			AIFComponentContext[] meops=((TCComponentBOMLine) MEOP).getChildren();
			
			//事例类型为消耗件
			if(((TCComponentBOMLine)MEOP).getItemRevision().getType()!=null) {
				List<String> partData=new ArrayList<String>();
				
				if(!comp2List.contains(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"))) {
					comp2List.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));//获取ID
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("object_name"));//获取名称
					partData.add(((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity")==null||((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity").equals("")?
							"1":((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity"));//获取数量
					comp2Data.put(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"), partData);
				}else {
					Float oldnum=Float.valueOf(comp2Data.get(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id")).get(2));
					Float newnum=Float.valueOf(((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity")==null||((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity").equals("")?
							"1":((TCComponentBOMLine)MEOP).getStringProperty("bl_quantity"));
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"));//获取ID
					partData.add(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("object_name"));//获取名称
//					//可以去除小数点后面多余的.0
//					partData.add(String.valueOf(new BigDecimal(oldnum+newnum).stripTrailingZeros()));//累计数量
					partData.add(String.valueOf(oldnum+newnum));//累计数量
					comp2Data.put(((TCComponentBOMLine)MEOP).getItemRevision().getStringProperty("item_id"),partData);
				}
				
			}
			
			if((meops.length==0||meops==null)) {
				return;
			}else {
				for(AIFComponentContext meop:meops) {
					getMEOP2(((TCComponentBOMLine)meop.getComponent()));
				}
			}
		}
		
		
//		//获取bom行高亮选中
//		private void getNode(TCComponentBOMLine nodeBOMLine,String ID) throws TCException  {
//			 AIFComponentContext[] nodeBOMLineChild=nodeBOMLine.getChildren();
//			 if(getID(nodeBOMLine)==ID||getID(nodeBOMLine).equals(ID)) {
//				 lightRow.add(Integer.valueOf(getID(nodeBOMLine)));
//			 }
//			if(nodeBOMLineChild.length==0||nodeBOMLineChild==null) {
//				return;
//			}else {
//				for(AIFComponentContext node:nodeBOMLineChild) {
//					getNode(((TCComponentBOMLine)node.getComponent()), ID);
//				}
//			}
//		}
		
		private void getNode(AbstractViewableNode Node,String ID,AbstractViewableTreeTable m_tree) throws NumberFormatException, TCException {
			AbstractViewableNode  nextNode=(AbstractViewableNode) Node.getNextNode();
			TCComponentBOMLine NodeBOMLine=((IViewableNode) Node).getBOMLine();
			String IDS=getID(NodeBOMLine);
			if(IDS==ID||getID(NodeBOMLine).equals(ID)) {
				selectRow=m_tree.getRowForNode(Node);
				return;
			 }
			if(nextNode!=null){
				 getNode(nextNode,ID,m_tree);
			 }
		}
		
		private String getID(TCComponentBOMLine bomline) throws TCException {
			//获取ID，若ID内存在“-”则只取“-”前面的字符
			String ID=((TCComponentBOMLine)bomline).getItemRevision().getStringProperty("item_id");
			if(ID.indexOf("-")>=0) {
				return ID.split("-")[0];
			}
			return ID;
		}
		
		
		//数据对比
		private void compareData()  {
			List<String> List=new ArrayList<String>();
			
				if(true) {
					//comp1是订单bom
					for(int i=0;i<comp1List.size();i++) {
						int flog=0;
						for(int j=0;j<comp2List.size();j++) {
						if(comp1List.get(i).equals(comp2List.get(j))) {
							flog++;//一旦有一个相同就+1
							if(!List.contains(comp2List.get(j)))List.add(comp2List.get(j));//存在与订单bom相同的订单工艺的ID
							
							//if(!comp1Data.get(comp1List.get(i)).get(2).equals(comp2Data.get(comp2List.get(j)).get(2))) {//差异表里面数量不等的
							if(Float.parseFloat(comp1Data.get(comp1List.get(i)).get(2))!=Float.parseFloat(comp2Data.get(comp2List.get(j)).get(2))) {//差异表里面数量不等的
								Vector rowVector = new Vector();
								rowVector.add(String.valueOf(table3Vector.size()+1));
									rowVector.add(comp1Data.get(comp1List.get(i)).get(0));
									rowVector.add(comp1Data.get(comp1List.get(i)).get(1));
									rowVector.add(comp1Data.get(comp1List.get(i)).get(2));
									rowVector.add(comp2Data.get(comp2List.get(j)).get(0));
									rowVector.add(comp2Data.get(comp2List.get(j)).get(1));
									rowVector.add(comp2Data.get(comp2List.get(j)).get(2));
								table3Vector.add(rowVector);
							}
							break;
						}
					}
					if(flog==0)	{
						Vector rowVector = new Vector();
							rowVector.add(String.valueOf(table1Vector.size()+1));
							rowVector.add(comp1Data.get(comp1List.get(i)).get(0));
							rowVector.add(comp1Data.get(comp1List.get(i)).get(1));
							rowVector.add(comp1Data.get(comp1List.get(i)).get(2));
							table1Vector.add(rowVector);
					}
				  }
					for(int k=0;k<comp2List.size();k++) {//取不包含在List中的ID作为订单工艺的独有数据
						if(!List.contains(comp2List.get(k))) {
							Vector rowVector = new Vector();
								rowVector.add(String.valueOf(table2Vector.size()+1));
								rowVector.add(comp2Data.get(comp2List.get(k)).get(0));
								rowVector.add(comp2Data.get(comp2List.get(k)).get(1));
								rowVector.add(comp2Data.get(comp2List.get(k)).get(2));
								table2Vector.add(rowVector);
						}
					}
				}
				
			}
		
		
}
