package com.connor.touliao;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;

//import com.connor.zcbb.sb.handlers.SbjxbDialog;
import com.sun.corba.se.impl.encoding.EncapsOutputStream;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
//import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTypeService;
import com.teamcenter.rac.kernel.TCUserService;
import com.teamcenter.rac.pse.graphics.actions.Export3DFileAction;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.soaictstubs.booleanSeq_tHolder;
//import com.ufc.masterform.JButtonMargin;
//import com.ufc.util.MyRenderer;

public class TouliaoDialog extends AbstractAIFOperation{
	
	private Color bgColor = new Color(241, 250, 255);
	private JFileChooser jFileChooser;
	
	private int xhFlag=1;
	
	private List<String[]> difBomline=new ArrayList<String[]>();
	
	private boolean sameFlag=false;
	
	private boolean flagCal = true;
	
	private DefaultTableModel model;
	
	private TCSession session;
	
	private	TCComponentItemRevision itemRevision;
	
	private TCComponent meTarget;
	
	private Map<TCComponentItem, String> touliaoMap;
	
	private Map<TCComponentItem, String> bomLineMap;
	
	private Map<TCComponentItem, String> quantityNull;
	
	private Map<TCComponentItem, String> quantityNullBom;
	
//	public TouliaoDialog(TCSession session,Map<TCComponentItemRevision, TCComponentBOMLine> bomLineMap,Map<TCComponentItemRevision, Double> touliaoMap,TCComponentForm master){
//		this.session = session;
//		this.touliaoMap=touliaoMap;
//		this.bomLineMap=bomLineMap;
//		//this.nameString="test";
//		model = new DefaultTableModel(new Object[][] {},
//				new String[] { "序号","BOM子件号","子件名称","BOM数量","工艺投料件号","投料名称","工艺用量"});
//	}
	
	public TouliaoDialog(TCSession session,TCComponentItemRevision itemRevision, TCComponent meTarget) {
		this.session = session;
		this.itemRevision=itemRevision;
		this.meTarget=meTarget;
		model = new DefaultTableModel(new Object[][] {},
				new String[] { "序号","BOM子件号","子件名称","BOM数量","工艺投料件号","投料名称","工艺用量"});
	}

	@Override
	public void executeOperation() {
		
		//显示窗口
		try {
			TCComponentForm master = (TCComponentForm)itemRevision.getRelatedComponent("IMAN_master_form_rev");
			boolean isFcheck = master.getLogicalProperty("nhl8_isFcheck");
			Object obj[] = new Object[1];
			obj[0] = 1;
			TCUserService service = session.getUserService();
			touliaoMap=new HashMap<TCComponentItem, String>();
			
			bomLineMap=new HashMap<TCComponentItem, String>();
			
			quantityNull=new HashMap<TCComponentItem, String>();
			quantityNullBom=new HashMap<TCComponentItem, String>();
			TCComponentItemRevision meTargetRev =(TCComponentItemRevision) meTarget;
			service.call("openByPass", obj);

			if(!isFcheck) {
				
				getProcessItem(session, itemRevision);
				System.out.println("bomLineMap"+touliaoMap.size());
				if(flagCal) {
					getMeTargetItem(session,meTargetRev);
				}
			}else {
				boolean isfPass = false;
//						 String isfPassString="false";
				try {
					isfPass = master.getLogicalProperty("nhl8_isfPass");
					int option=1;
					if(isfPass) {
						option = JOptionPane.showOptionDialog(null, itemRevision+"已经进行过投料检查，检查结果为“投料检查通过”。是否再次进行投料检查?", "", 0, 1, null, null, 
						  	          Integer.valueOf(0));
					}else {
						option = JOptionPane.showOptionDialog(null, itemRevision+"已经进行过投料检查，检查结果为“投料检查不通过”。是否再次进行投料检查?", "", 0, 1, null, null, 
					  	          Integer.valueOf(0));
					}
					if(option==1 || option==-1) {
						return;
					}
					
				} catch (Exception e3) {
					// TODO Auto-generated catch block
					e3.printStackTrace();
				}
				getProcessItem(session, itemRevision);
				if(flagCal) {
					getMeTargetItem(session,meTargetRev);
				}
				
				
			}
			service.call("closeByPass", obj);
			
			if(flagCal) {
				if(quantityNull.size()==0 && quantityNullBom.size()==0) {
					compareBomline();
				}else {
					sameFlag=false;
				}
				
			
				bomLineMap.clear();
				touliaoMap.clear();
				if(!sameFlag) {
					
					service.call("openByPass", obj);
					System.out.println("表单"+master.toString());
					
					master.setLogicalProperty("nhl8_isFcheck", true);
					
					master.setLogicalProperty("nhl8_isfPass", false);
					service.call("closeByPass", obj);
					init();
					
					
					
				}else {
					service.call("openByPass", obj);
					
					master.setLogicalProperty("nhl8_isFcheck", true);
					master.setLogicalProperty("nhl8_isfPass", true);
					service.call("closeByPass", obj);
					MessageBox.post(itemRevision+"投料检查通过","提示",MessageBox.INFORMATION);
				}
			}

			
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//启用查询按钮
//		qryBtn.setEnabled(true);	
	}

	private void compareBomline() throws TCException {
		// TODO Auto-generated method stub
		
		System.out.println("touliao"+touliaoMap.size());
//		System.out.println("bom");
		
		for(Map.Entry<TCComponentItem, String> key:touliaoMap.entrySet()) {
			TCComponentItem key2 = key.getKey();
			if(bomLineMap.containsKey(key2)) {
				String tcComponentBOMLine = bomLineMap.get(key2);
				if(tcComponentBOMLine==null) {
					System.out.println("???");
					continue;
				}
			}
		}
		
		for(Map.Entry<TCComponentItem, String> key:touliaoMap.entrySet()) {
			TCComponentItem key2 = key.getKey();
			String value = key.getValue();
			String bl_quantity = String.valueOf(value);
			String item_id = key2.getStringProperty("item_id");
			String revision_id = key2.getStringProperty("object_name");
			if(bomLineMap.containsKey(key2)) {
				String tcComponentBOMLine = bomLineMap.get(key2);
				if(tcComponentBOMLine==null) {
					continue;
				}
				String stringProperty = tcComponentBOMLine;
				if(stringProperty==null || stringProperty.equals("")) {
//					quantityNull.put(bomLine.getItem(), "");
//					continue;
//					stringProperty="0";
				}
				if(!stringProperty.equals(bl_quantity)) {
					System.out.println("不同"+key2.getStringProperty("object_string"));
					difBomline.add(new String[] {String.valueOf(xhFlag),item_id,revision_id,stringProperty,item_id,revision_id,bl_quantity});
					xhFlag++;
				}
			}else {
				System.out.println("缺少"+key2.getStringProperty("object_string"));
				difBomline.add(new String[] {String.valueOf(xhFlag),"","","",item_id,revision_id,bl_quantity});
				xhFlag++;
			}
		}
		
		for(Map.Entry<TCComponentItem, String> key:bomLineMap.entrySet()) {
			TCComponentItem key2 = key.getKey();
			String value = key.getValue();
			String bl_quantity = value;
			String item_id = key2.getStringProperty("item_id");
			String revision_id = key2.getStringProperty("object_name");
			if(!touliaoMap.containsKey(key2)) {
				System.out.println("投料缺少"+key2.getStringProperty("object_string"));
				difBomline.add(new String[] {String.valueOf(xhFlag),item_id,revision_id,bl_quantity,"","",""});
				xhFlag++;
			}
			
		}
		System.out.println(difBomline.size());
		if(difBomline.size()==0) {
			sameFlag=true;
		}
		
	}

	private void init() {
		
		Thread t=new Thread(new Runnable(){
			public void run(){
				
				try {
					MessageDialog dialog=new MessageDialog(session,difBomline,quantityNull,quantityNullBom);
				} catch (TCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

//				System.out.println("modelExcel"+modelExcel.getAbsolutePath());
//				SbjxbDialog sbjxbDialog = new SbjxbDialog(session,writeSheet.pxList,modelExcel,docRev,docName,dsType,dsRef, "IMAN_specification",modelExcel.getAbsolutePath());
			}
	    });
		t.start();
		// TODO Auto-generated method stub
//		for(String[] row:difBomline) {
//			System.out.println(row[1]);
//			model.addRow(row);
//		}
//		
//		
//		this.setModal(true);
//		this.setSize(1000, 500);
////		this.getContentPane().setBackground(bgColor);
//		setTitle("投料检查结果");
//		setLayout(null);
//		jFileChooser = new JFileChooser();
////		this.jFileChooser.setCurrentDirectory(new File());
//		this.jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//		JScrollPane scrollPane = new JScrollPane();
//		scrollPane.setBounds(0, 0, 1000, 400);
//		
//		
//		
//		JTable table = new JTable();
//		table.setEnabled(false);
//		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//		table.setSurrendersFocusOnKeystroke(true);
//		table.setColumnSelectionAllowed(true);
//		table.setCellSelectionEnabled(true);	
//		table.setRowHeight(30);
////		table.setForeground(Color.DARK_GRAY);
//		table.setModel(model);
////		TableModel model2 = table.getModel();
////		System.out.println(model2.getRowCount()+"model"+model2.getValueAt(0, 0));
//		
////		table.getTableHeader().setBackground(bgColor);
//		table.getColumnModel().getColumn(0).setPreferredWidth(50);
//		table.getColumnModel().getColumn(1).setPreferredWidth(100);
//		table.getColumnModel().getColumn(2).setPreferredWidth(150);
//		table.getColumnModel().getColumn(3).setPreferredWidth(50);
//		table.getColumnModel().getColumn(4).setPreferredWidth(100);
//		table.getColumnModel().getColumn(5).setPreferredWidth(150);
//		table.getColumnModel().getColumn(6).setPreferredWidth(50);
//		MyRenderer myRender = new MyRenderer();
//		table.setDefaultRenderer(Object.class, myRender);
//		
//		JTableHeader header1 = new JTableHeader();
//		header1.setTable(table);
//		scrollPane.setViewportView(table);
////		scrollPane.getViewport().setBackground(bgColor);
//
//		this.add(scrollPane);
//		
//		JButton cancelBtn=new JButton("关闭");
//		cancelBtn.setBounds(550, 410, 100, 30);
//		
//		cancelBtn.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub
//				dispose();
//			}
//		});
//		
//		
//		this.add(cancelBtn);
//		JButton outBtn = new JButton("导出");
//		outBtn.setBounds(400, 410, 100, 30);
////		outBtn.setBackground(bgColor);
//		
//		
//		outBtn.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub
//				selectFileButtonEvent();
//			}
//		});
//		this.add(outBtn);
////		JButton okBtn = new JButton("关闭");
////		okBtn.setBounds(500, 410, 60, 30);
//////		okBtn.setBackground(bgColor);
////		scrollPane.add(okBtn);
////		
////		okBtn.addActionListener(new ActionListener() {
////			@Override
////			public void actionPerformed(ActionEvent e) {
////				// TODO Auto-generated method stub
////				dispose();
////			}
////		});
//		
//		this.setLocationRelativeTo(null);
//		this.setVisible(true);
	}
	
//	public void selectFileButtonEvent(){
//		int state = jFileChooser.showOpenDialog(null);
//		if(state == 1) {
//			return;
//		}else{
//			File f = jFileChooser.getSelectedFile();
//			TouliaoOperation operation=new TouliaoOperation(f,difBomline);
//			session.queueOperation(operation);
//			System.out.println(f.getAbsolutePath());
//		}
//	}
	
	private void getMeTargetItem(TCSession session, TCComponentItemRevision meTargetRev) throws TCException {
		// TODO Auto-generated method stub
		Map<TCComponentItemRevision, String> packMap=new HashMap<TCComponentItemRevision, String>();
		TCTypeService service = session.getTypeService();
		TCComponentBOMWindowType winType = (TCComponentBOMWindowType) service
				.getTypeComponent("BOMWindow");
		System.out.println("获取制造目标下的item");
		
		TCComponentBOMWindow window = winType.create(null);
		window.lock();
		TCComponentBOMLine topLine = window.setWindowTopLine(
				meTargetRev.getItem(), meTargetRev, null, null);
		
		AIFComponentContext[] children = topLine.getChildren();
		for(AIFComponentContext context:children) {
			TCComponentBOMLine bomLine = (TCComponentBOMLine)context.getComponent();
			System.out.println("制造目标bomline"+bomLine.getStringProperty("object_string"));
			
			TCComponentItemRevision itemRevision = bomLine.getItemRevision();
			String bl_sequence_no = bomLine.getStringProperty("bl_sequence_no");
//			boolean containsKey = packMap.containsKey(itemRevision);
//			if(containsKey) {
////				bomLine.setStringProperty("bl_sequence_no", packMap.get(itemRevision));
////				bomLine.pack();
//			}else {
//				packMap.put(itemRevision, bl_sequence_no);
//			}
			String stringProperty = bomLine.getStringProperty("bl_quantity");
			if(stringProperty==null || stringProperty.equals("")) {
				
				if(bomLine.getItem().getStringProperty("item_id").contains("GB")) {
					continue;
				}
				quantityNullBom.put(bomLine.getItem(), "bom");
				continue;
//				stringProperty="0";
				
			}
			BigDecimal bigDecimal = new BigDecimal(stringProperty);
			System.out.println(bigDecimal.toString() );
			if(bomLineMap.containsKey(bomLine.getItem())) {
				String string = bomLineMap.get(bomLine.getItem());
				BigDecimal big2 = new BigDecimal(string);
				BigDecimal add = big2.add(bigDecimal);
				bomLineMap.put(bomLine.getItem(),add.toString() );
			}else {
				bomLineMap.put(bomLine.getItem(),bigDecimal.toString() );
			}
			
		}
		
		window.save();
		window.unlock();
		window.close();
	}

	private void getProcessItem(TCSession session,TCComponentItemRevision revision) throws TCException {
		// TODO Auto-generated method stub
		Map<TCComponentItemRevision, String> packMap=new HashMap<TCComponentItemRevision, String>();
		
		TCTypeService service = session.getTypeService();
		TCComponentBOMWindowType winType = (TCComponentBOMWindowType) service
				.getTypeComponent("BOMWindow");
		System.out.println("获取工艺对象下的工步");
		
		TCComponentBOMWindow window = winType.create(null);
		window.lock();
		TCComponentBOMLine topLine = window.setWindowTopLine(
				revision.getItem(), revision, null, null);
		AIFComponentContext[] children = topLine.getChildren();
		for(AIFComponentContext child:children) {
			TCComponentBOMLine component =(TCComponentBOMLine) child.getComponent();
//			System.out.println(component.getStringProperty("object_string"));
			AIFComponentContext[] children2 = component.getChildren();
			for(AIFComponentContext gbdxContext:children2) {
				TCComponentBOMLine GBComponent =(TCComponentBOMLine) gbdxContext.getComponent();
				String bomType = GBComponent.getItem().getType();
//				&& && bl_occ_type.equals("MEConsumed")
//				System.out.println("类型"+bomType);
//				if(bomType.equals("NHL8_RigOutAC") || 1==1) {
				AIFComponentContext[] touLiaos = GBComponent.getChildren();
				for(AIFComponentContext touLiao:touLiaos) {
					TCComponentBOMLine touLiaoLine =(TCComponentBOMLine) touLiao.getComponent();
					String bl_occ_type = touLiaoLine.getStringProperty("bl_occ_type"); 
					System.out.println(touLiaoLine.getStringProperty("object_string")+"投料事例类型"+bl_occ_type);
					
					if(bl_occ_type.equals("MEDisassemble")) {
						MessageBox.post("非CAL号工艺不允许存在拆卸件的业务","提示",2);
						
						flagCal=false;
						
						return;
					}
					
					if(bl_occ_type.equals("MEConsumed") ) { //|| bl_occ_type.equals("MEDisassemble")
						TCComponentItemRevision itemRevision = touLiaoLine.getItemRevision();
						String bl_sequence_no = touLiaoLine.getStringProperty("bl_sequence_no");
						boolean containsKey = packMap.containsKey(itemRevision);
						if(containsKey) {
//							touLiaoLine.setStringProperty("bl_sequence_no", packMap.get(itemRevision));
//							touLiaoLine.pack();
						}else {
							packMap.put(itemRevision, bl_sequence_no);
						}
						
					}
//					System.out.println("打包完成");
				}
//				}
				
			}
		}
		window.save();
		window.unlock();
		window.close();
		getProcessItem2(session,revision);
	}
	
	
	private void getProcessItem2(TCSession session,TCComponentItemRevision revision) throws TCException {
		// TODO Auto-generated method stub
		Map<TCComponentItemRevision, String> packMap=new HashMap<TCComponentItemRevision, String>();
		
		TCTypeService service = session.getTypeService();
		TCComponentBOMWindowType winType = (TCComponentBOMWindowType) service
				.getTypeComponent("BOMWindow");
		System.out.println("获取工艺对象下的工步");
		
		TCComponentBOMWindow window = winType.create(null);
		window.lock();
		TCComponentBOMLine topLine = window.setWindowTopLine(
				revision.getItem(), revision, null, null);
		
		AIFComponentContext[] children = topLine.getChildren();
		for(AIFComponentContext child:children) {
			TCComponentBOMLine component =(TCComponentBOMLine) child.getComponent();
//			System.out.println(component.getStringProperty("object_string"));
			AIFComponentContext[] children2 = component.getChildren();
			for(AIFComponentContext gbdxContext:children2) {
				TCComponentBOMLine GBComponent =(TCComponentBOMLine) gbdxContext.getComponent();
//				String bomType = GBComponent.getItem().getType();
//				&& && bl_occ_type.equals("MEConsumed")
//				System.out.println("类型"+bomType);
//				if(bomType.equals("NHL8_RigOutAC") || 1==1) {
				AIFComponentContext[] touLiaos = GBComponent.getChildren();
				
				String stringProperty = GBComponent.getStringProperty("bl_occ_type");
				
				if(stringProperty.equals("MEDisassemble")) {
					MessageBox.post("非CAL号工艺不允许存在拆卸件的业务","提示",2);
					
					flagCal=false;
					
					return;
				}
				
				if(stringProperty.equals("MEConsumed")) {
					String stringProperty2 = GBComponent.getStringProperty("bl_quantity");
					if(stringProperty2==null ||stringProperty2.equals("")){
						
//						quantityNull.put(GBComponent.getItem(), "process");
//						continue;
//						stringProperty2="0";
					}else {
						BigDecimal bigDecimal = new BigDecimal(stringProperty2);
						if(touliaoMap.containsKey(GBComponent.getItem())) {
//							BigDecimal bigDecimal = new BigDecimal(stringProperty2);
							BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(touliaoMap.get(GBComponent.getItem())));
							bigDecimal= bigDecimal.add(bigDecimal2);
//							valueOf=Double.valueOf(bigDecimal.toString());
						}
						System.out.println(GBComponent.getItemRevision().getStringProperty("object_string")+"222value"+bigDecimal.toString());
						touliaoMap.put(GBComponent.getItem(), bigDecimal.toString());
					}
				
					continue;
				}
				
				for(AIFComponentContext touLiao:touLiaos) {
					TCComponentBOMLine touLiaoLine =(TCComponentBOMLine) touLiao.getComponent();
					String bl_occ_type = touLiaoLine.getStringProperty("bl_occ_type"); 
					
					if(bl_occ_type.equals("MEConsumed") || bl_occ_type.equals("MEDisassemble")) {
						TCComponentItemRevision itemRevision = touLiaoLine.getItemRevision();
						String stringProperty2 = touLiaoLine.getStringProperty("bl_quantity");
						if(stringProperty2==null ||stringProperty2.equals("")){
							quantityNull.put(touLiaoLine.getItem(), "process");
//							stringProperty2="0";
						}else {
							BigDecimal bigDecimal = new BigDecimal(stringProperty2);
//							Double valueOf = Double.valueOf(stringProperty2);
							if(touliaoMap.containsKey(touLiaoLine.getItem())) {
//								bigDecimal = new BigDecimal(stringProperty2);
								BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(touliaoMap.get(touLiaoLine.getItem())));
								bigDecimal= bigDecimal.add(bigDecimal2);
//								valueOf=Double.valueOf(bigDecimal.toString());
							}
							System.out.println(itemRevision.getStringProperty("object_string")+"value"+bigDecimal.toString());
							touliaoMap.put(touLiaoLine.getItem(), bigDecimal.toString());
						}
						
					}
				}
//				}
				
			}
		}
		window.save();
		window.unlock();
		window.close();
		
	}
	
	
}
