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

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.tree.TreePath;
import com.teamcenter.rac.kernel.TCAccessControlService;

import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;

import com.connor.ml.tcm.outfile.bean.NodeBean;
import com.connor.ml.tcm.outfile.util.MethodUtil;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
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.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
//import com.teamcenter.soa.exceptions.NotLoadedException;

public class DbomTransitionToEbomDialog extends JFrame implements ActionListener, MouseListener {
	//AbstractAIFDialog

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private TCSession session;
	private InterfaceAIFComponent comp;
	//private InterfaceAIFComponent comp;//获取选中的对象
	
	private List<Integer> isNotEditableRow = new ArrayList<Integer>();
	//private TCComponentBOMLine bomLine;
	private DefaultMutableTreeTableNode node;
	
	private String[] header = new String[] { "DBOM对象", "EBOM对象","选中", "EBOMID", "物料描述","数量","发布状态","对应父节点"};
	
	private JPanel titlePanel;
	private JLabel titleLabel;
	private JTreeTable table;
	private JTreeTableModel map;
	
	private JPanel rootPanel;
	private JButton okButton;
	private JButton celButton;
	private JButton refreshButton;
//	private Map<TCComponentItemRevision, List<BomValBean>> bomValMap;
	private ArrayList<String> preList;
	private StringBuilder builder = new StringBuilder("");
//	private ProcessBarDialog progress;
	private Boolean falg1 = true;
	private TCAccessControlService acs;
	private TCComponent[] user;
	private StringBuilder msg2;
	private List<TCComponentItem> items = new ArrayList<TCComponentItem>();
	public DbomTransitionToEbomDialog(InterfaceAIFComponent comp, TCSession session, DefaultMutableTreeTableNode node,
			ArrayList<String> preList, ProcessBarDialog progress, String[] header) {
		//  Auto-generated constructor stub
//		super(false);
		this.session = session;
		this.comp = comp;
		this.node = node;
		this.preList = preList;
//		this.progress = progress;
		this.header = header;
		
		acs = session.getTCAccessControlService();
		user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
		msg2 = new StringBuilder("");
//		this.bomValMap = bomValMap;
//		System.out.println("bomValMap==>"+bomValMap.toString());
		init();
	}

	private void init() {
		//  Auto-generated method stub
		this.setTitle("DBOM转EBOM");
		this.setPreferredSize(new Dimension(800, 600));
		// 初始化标题部分控件
		this.titlePanel = new JPanel();
		this.titleLabel = new JLabel("DBOM转EBOM");
		this.titleLabel.setFont(new Font("宋体", 1, 18));
		this.titlePanel.add(titleLabel);
		
		JPanel panel = new JPanel();
		panel.add(this.titlePanel,BorderLayout.NORTH);
		
		getJTreeTable();
		
		this.table.addMouseListener(this);
//		Adapter adapter = new Adapter(table); 
		
		this.rootPanel = new JPanel(new FlowLayout());
		this.okButton = new JButton("确认");
		this.celButton = new JButton("取消");
		this.refreshButton = new JButton("刷新");
		
		this.rootPanel.add(okButton);
		this.rootPanel.add(celButton);
		this.rootPanel.add(refreshButton);
		//this.rootPanel.add(celValueButton);
		
		// 添加鼠标监听
		this.createActionEvent();
		this.setLayout(new BorderLayout());
		// this.add(centerPanel, BorderLayout.NORTH);
		this.add(panel, BorderLayout.NORTH);
		this.add(new JScrollPane(this.table), BorderLayout.CENTER);
		// dialog.add(tablePanel, BorderLayout.CENTER);
		this.add(rootPanel, BorderLayout.SOUTH);
		//this.setAlwaysOnTop(true);
		this.pack();
		this.setLocationRelativeTo(null); 
		this.setVisible(true);
//		this.setAlwaysOnTop(true);
	}

	//添加监听
	private void createActionEvent() {
		this.okButton.addActionListener(this);
		this.celButton.addActionListener(this);
		this.refreshButton.addActionListener(this);
		//this.celValueButton.addActionListener(this);
	}
		
	//Jtable通用方法
	private void getJTreeTable() {
//		int simpleLen = 100;
//		int totleLen = 1500;
		if (table == null) {
			this.map = new JTreeTableModel(this.node, header);
			this.map.setIsNotEditableRow(this.isNotEditableRow);
			//map.setColumnIdentifiers(titleNames);
			
			table = new JTreeTable(map);
			table.setIsNotEditableRow(this.isNotEditableRow);
			table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			// partsTable.setRowHeight(1, 50);
			// partsTable.setRowHeight(2, 100);
			table.setRowHeight(30);
			table.expandAll();  //  展开全部节点
			// 隐藏列
//				partsTable.HiddenCell(0);

			table.getColumnModel().getColumn(NodeBean.DBOM).setPreferredWidth(188); //  设置第一列宽度
			table.getColumnModel().getColumn(NodeBean.EBOM).setPreferredWidth(150); //  设置第二列宽度
			table.getColumnModel().getColumn(NodeBean.LABEL).setPreferredWidth(55); //  设置第三列宽度

			table.setHighlighters(HighlighterFactory.createSimpleStriping());
			
//			if (simpleLen * header.length >= totleLen) {
//				for (int i = 0; i < header.length; i++) {
//					table.getColumnModel().getColumn(i).setPreferredWidth(simpleLen);
//				}
//				table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);//AUTO_RESIZE_OFF
//			} else {
//				table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);//AUTO_RESIZE_NEXT_COLUMN
//			}
			table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF);
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//  Auto-generated method stub
		if(e.getClickCount() == 2) {
			TreePath treePath = table.getPathForLocation(e.getX(),e.getY());
	        if (treePath != null) {
              	DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) treePath.getLastPathComponent();
              	NodeBean nodeBean = (NodeBean) node.getUserObject();
              	String itemId = nodeBean.getDbom();
              	if(itemId != null && !itemId.isEmpty()) {
              		try {
                  		//获取对象
              			TCComponentItemType itemType = (TCComponentItemType) this.session.getTypeComponent("Item");
                  		TCComponentItem item = itemType.findItems(itemId.split("-")[0])[0];
                  		
                  		com.teamcenter.rac.common.Activator.getDefault()
                  		.openPerspective("com.teamcenter.rac.ui.perspectives.navigatorPerspective");
                  		com.teamcenter.rac.common.Activator.getDefault()
                        .openComponents("com.teamcenter.rac.ui.perspectives.navigatorPerspective", 
                        		new InterfaceAIFComponent[] { item });
					} catch (Exception e2) {
						// : handle exception
						e2.printStackTrace();
					}
              	}
	        }
		} else if (e.getClickCount() > 0) {
			// 获得选中列
	        int selectColumn = table.getTableHeader().columnAtPoint(e.getPoint());
	        
	        if(selectColumn != NodeBean.LABEL) {
	        	return;
	        }
	        TreePath treePath = table.getPathForLocation(e.getX(),e.getY());
	        if (treePath != null) {
              	DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) treePath.getLastPathComponent();
              	NodeBean nodeBean = (NodeBean) node.getUserObject();
              	
        		try {
        	      	DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent();
      				String status = nodeBean.getRefreshStatus();
  					if(!status.equals("属性发布") && !status.equals("流程中") && !status.isEmpty()
        					&& getChildRefresh(parentNode, false)) {
                  		MessageBox.post("下层已勾选，上层不允许勾选已发布或没权限对象！", "错误", MessageBox.ERROR);
      					return;
      				}else if(!acs.checkAccessorsPrivilege(user, nodeBean.getTcComponent(), "WRITE") 
      						&& getChildRefresh(parentNode, false)) {
                  		MessageBox.post("下层已勾选，上层不允许勾选已发布或没权限对象！", "错误", MessageBox.ERROR);
      					return;
        			}
                  	if(getTopRefresh(node)) {
                  		MessageBox.post("上层已勾选发布或无权限的对象，下层不允许勾选！", "错误", MessageBox.ERROR);
      					return;
                  	}
                  	
//                  	if(getTopProcessRefresh(node)) {
//                  		MessageBox.post("上层已勾选流程中的对象，下层不允许勾选！", "错误", MessageBox.ERROR);
//      					return;
//                  	}

            		if(parentNode != null) {
//                  		DefaultMutableTreeTableNode rootNode = (DefaultMutableTreeTableNode) parentNode.getParent();
//                  		NodeBean rootNodeBean = (NodeBean) rootNode.getUserObject();
                  		
                  		
//                  		if(!rootNodeBean.getDbom().equals("顶层") && !getTop(node) && nodeBean.getLabel().equals("0") ) {
//                      		MessageBox.post("上层未勾选对象，下层不允许勾选！", "错误", MessageBox.ERROR);
//          					return;
//                      	}
                  	}
//        			TCComponentItemType itemType = (TCComponentItemType) session.getTypeComponent("Item");
                  	//TODO 勾选事件
                  	if(nodeBean.getLabel().equals("0")) {
                  		//判断同一层是否已勾选
                		if(parentNode != null) {
                			for (int i = 0; i < parentNode.getChildCount(); i++) {
                				DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) parentNode.getChildAt(i);
                  				NodeBean childBean = (NodeBean) childNode.getUserObject();
                  				if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty() && !nodeBean.getEbom().isEmpty()) {
                              		MessageBox.post("同一层级只允许选中一个！", "错误", MessageBox.ERROR);
                  					return;
                  				}
        					}
                      	}
                  		nodeBean.setLabel("1");
                  		if(parentNode != null)
                  			autoCheck(parentNode, "1");
                  		//isHaveBom(node, nodeBean.getEbomId(), "1", itemType);
                  	}else if(nodeBean.getLabel().equals("1")) {
                  		nodeBean.setLabel("0");
                  		if(parentNode != null)
                  			autoCheck(parentNode, "0");
                  		//isHaveBom(node, nodeBean.getEbomId(), "0", itemType);
                  	}
                  	Robot robot = new Robot();
                  	robot.keyPress(KeyEvent.VK_TAB);
                  	robot.keyRelease(KeyEvent.VK_TAB);
				} catch (Exception e2) {
					// : handle exception
					e2.printStackTrace();
              		MessageBox.post("错误：" + e2, "错误", MessageBox.ERROR);
				}
	        }
		}
	}
	
	/***
	 * 判断上级是否勾选
	 * @param node
	 * @return
	 * @throws TCException 
	 */
//	private void isHaveBom(DefaultMutableTreeTableNode node,String parentID,String status,TCComponentItemType itemType)
//	throws Exception {
//		TCComponentItem item = itemType.findItems(parentID)[0];
//		TCComponentItemRevision itemRevision = item.getLatestItemRevision();
//		
//		TCComponent[] tcComponents = itemRevision.getReferenceListProperty("view");
//		if(tcComponents.length > 0)
//		{
//			for (int ii = 0; ii < node.getParent().getChildCount(); ii++) {
//				DefaultMutableTreeTableNode tableNode = (DefaultMutableTreeTableNode)node.getParent().getChildAt(ii);
//				
//				if(tableNode.getChildCount() > 0)
//				{
//					for (int i = 0; i < tcComponents.length; i++) {
//						TCComponent childBomLine = tcComponents[i];
//						List<String> haveItemID = new ArrayList<String>();
//						for (int j = 0; j < tableNode.getChildCount(); j++) {
//							String childItemId = childBomLine.getStringProperty("item_id");
//							NodeBean childNodeBean = (NodeBean) tableNode.getChildAt(j).getUserObject();
//							if(childItemId.equals(childNodeBean.getEbomId()) && !haveItemID.contains(childNodeBean.getEbomId()))
//							{
//								haveItemID.add(childNodeBean.getEbomId());
//								childNodeBean.setLabel(status);
//								isHaveBom((DefaultMutableTreeTableNode)(tableNode.getChildAt(j)), childNodeBean.getEbomId(), status, itemType);
//							}
//						}
//					}
//				}
//			}
//		}
//	}
	
	/***
	 * 判断上级是否勾选
	 * @param node
	 * @return
	 */
//	private boolean getTop(DefaultMutableTreeTableNode node) {
//		boolean result = false;
//
//      	//判断上层是否勾选已发布的对象
//      	DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent();
//		if(parentNode != null)
//      	{
//      		DefaultMutableTreeTableNode rootNode = (DefaultMutableTreeTableNode) parentNode.getParent();
//      		if(rootNode != null)
//      		{
//      			for (int i = 0; i < rootNode.getChildCount(); i++) {
//      				DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i);
//      				NodeBean childBean = (NodeBean) childNode.getUserObject();
//      				if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty())
//      				{
//      					//MessageBox.post("上层["+childBean.getEbom()+"]已勾选发布的对象，下层不允许勾选！", "错误", MessageBox.ERROR);
//      					return true;
//      				}
//				}
//      		}
//      	}
//		
//		return result;
//	}
	
	/***
	 * 判断上级是否勾选已发布对象
	 * @param node
	 * @return
	 */
	private boolean getTopRefresh(DefaultMutableTreeTableNode node) throws Exception {
		boolean result = false;

      	//判断上层是否勾选已发布的对象
      	DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent();
		if(parentNode != null) {
      		DefaultMutableTreeTableNode rootNode = (DefaultMutableTreeTableNode) parentNode.getParent();
      		if(rootNode != null) {
      			for (int i = 0; i < rootNode.getChildCount(); i++) {
      				DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i);
      				NodeBean childBean = (NodeBean) childNode.getUserObject();

      				if(childBean.getLabel().equals("1")) {
          				TCComponent tcComponent = childBean.getTcComponent();
//          				String property = tcComponent.getProperty("j6_processtype");
          				String status = childBean.getRefreshStatus();
      					if(!status.equals("属性发布") && !status.equals("流程中") && !status.isEmpty()) {
      						System.out.println("发布：" + tcComponent);
          					result = true;
          					break;
//          				}else if(property != null && (property.equals("外购件") || property.equals("外协件"))) {
//          					result = true;
//          					break;
          				}else if(!acs.checkAccessorsPrivilege(user, tcComponent, "WRITE")) {
      						System.out.println("无权：" + tcComponent);
          					result = true;
          					break;
          				}
      				}else{
      					if(getTopRefresh(childNode)) {
          					result = true;
          					break;
      					}
      				}
				}
      		}
      	}
		
		return result;
	}
	
	/***
	 * 判断下级是否勾选
	 * @param node 父级树节点
	 * @param p 是否检查当前层
	 * @return 下级是否勾选
	 */
	private boolean getChildRefresh(DefaultMutableTreeTableNode node, boolean p) throws Exception {
		if(node == null)
			return false;
		boolean result = false;
		int count = node.getChildCount();
		for(int i = 0; !result && i < count; i++) {
			DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) node.getChildAt(i);
			if(p) {
				NodeBean childBean = (NodeBean) childNode.getUserObject();
				if(childBean.getLabel().equals("1")) {
					return true;
				}
			}
			result = getChildRefresh(childNode, true);
		}
		return result;
	}
	/***
	 * 上级取消勾选，下级同时取消勾选；上级勾选，下级同时勾选。对一图多物目前是不默认勾选，保持现状即可
	 * @param parentNode 父级树节点
	 * @param val 设置勾选值0或1
	 */
	private void autoCheck(DefaultMutableTreeTableNode parentNode, String val) {
		for (int i = 0; i < parentNode.getChildCount(); i++) {
			DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) parentNode.getChildAt(i);
			NodeBean bean = (NodeBean) node.getUserObject();
			if(!bean.getDbom().isEmpty()) {
				boolean change = true;
				NodeBean eBean = null;
				for (int j = 0; j < node.getChildCount(); j++) {
					DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) parentNode.getChildAt(i);
					NodeBean childBean = (NodeBean) childNode.getUserObject();
					if(!childBean.getEbom().isEmpty()) {
						if(eBean == null) {
							eBean = childBean;
						}else {
							change = false;
						}
					}else if(!childBean.getDbom().isEmpty()) {
						autoCheck(childNode, val);
					}
				}
				System.out.println("autoCheck：" + bean.getDbom() + "==" + change + "==" + eBean + ">>" + val);
				if(eBean != null && (change || val.equals("0"))) {
					eBean.setLabel(val);
				}
			}
		}
	}
	
	/***
	 * 判断上级是否勾选流程中对象
	 * @param node
	 * @return
	 */
//	private boolean getTopProcessRefresh(DefaultMutableTreeTableNode node) {
//		boolean result = false;
//      	//判断上层是否勾选已发布的对象
//      	DefaultMutableTreeTableNode parentNode = (DefaultMutableTreeTableNode) node.getParent();
//		if(parentNode != null) {
//      		DefaultMutableTreeTableNode rootNode = (DefaultMutableTreeTableNode) parentNode.getParent();
//      		if(rootNode != null) {
//      			for (int i = 0; i < rootNode.getChildCount(); i++) {
//      				DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i);
//      				NodeBean childBean = (NodeBean) childNode.getUserObject();
//      				if(childBean.getLabel().equals("1") && childBean.getRefreshStatus().equals("流程中")) {
//      					result = true;
//      					break;
//      				}else {
//      					if(getTopProcessRefresh(childNode)) {
//          					result = true;
//          					break;
//      					}
//      				}
//				}
//      		}
//      	}
//		return result;
//	}

	@Override
	public void mousePressed(MouseEvent e) {
		//  Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		//  Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		//  Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		//  Auto-generated method stub
		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		//  Auto-generated method stub
		Object source = e.getSource();
		if (source.equals(this.okButton)) 
		{
			//获取选中的EBOM对象
			new Thread() {
				@Override
				public void run() {
					try {
						topLineItem = null;
						builder.setLength(0);
						falg1 = true;
//						MethodUtil.openByPass(session);
						TCComponentItemType itemType = (TCComponentItemType) session
								.getTypeComponent("Item");
						bomStructMap.clear();
						msg2.setLength(0);
						items.clear();

						//lidy20240914增加权限检查，避免其他人将对象发布
						DefaultMutableTreeTableNode top = (DefaultMutableTreeTableNode) node.getChildAt(0);
						for(int i = 0, size = top.getChildCount(); i < size; i++) {
							DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) top.getChildAt(i);
							NodeBean childBean = (NodeBean) childNode.getUserObject();
							if(childBean.getLabel().equals("1")) {
								TCComponent comp = childBean.getTcComponent();
								comp.refresh();
		  						TCComponent[] bom = comp.getRelatedComponents("structure_revisions");
		  						System.out.println("top：" + comp + "==" + Arrays.toString(bom));
								if(!acs.checkAccessorsPrivilege(user, comp, "WRITE") || 
										bom.length > 0 && !acs.checkAccessorsPrivilege(user, bom[0], "WRITE")) {
									MessageBox.post(comp + " 无编辑权限，已跳过BOM转换！", "成功", MessageBox.INFORMATION);
								  	dispose();
								  	return;
								}
							}
						}
						
						adaptiveVariants(top, itemType,true);
						if(!builder.toString().equals("")) {
							JTextArea jTextArea = new JTextArea(builder.toString());
							jTextArea.setEditable(false);
							JScrollPane jScrollPane = new JScrollPane(jTextArea);
							jScrollPane.setBorder(BorderFactory.createTitledBorder("存在以下情况，是否继续创建"));
							jScrollPane.setPreferredSize(new Dimension(300, 100));
					    	int option = JOptionPane.showOptionDialog(null, jScrollPane, "", 0, 1, null, null, 
						  	          Integer.valueOf(0));
						  	if(option!=0) {
						  		MethodUtil.closeByPass(session);
						  		return;
						  	}
						}
//						builder.append("是否继续转换?");
						
						if(!falg1) {
							return;
						}
//						MethodUtil.closeByPass(session);
						ProcessBarDialog progress = new ProcessBarDialog("正在进行BOM转换...");
					    progress.open();
					    
					  	reBuildBOM();
					  	
					  	progress.close();
					  	StringBuilder m = new StringBuilder("对象：\n");
					  	if(msg2.length()>0) {
					  		m.append(msg2.deleteCharAt(msg2.length() - 1)).append(" 无编辑权限，已跳过BOM转换！");
					  		MessageBox.post(m.toString(), "成功", MessageBox.INFORMATION);
					  	}else {
							MessageBox.post("转换成功！", "成功", MessageBox.INFORMATION);
					  	}
					  	dispose();
					} catch (Exception e1) {
						//  Auto-generated catch block
						e1.printStackTrace();
					}
					
				}
			}.start();
			
		}
		else if(source.equals(this.refreshButton))
		{
			this.dispose();
			try {
				DbomTransitionToEbomCommand command = new DbomTransitionToEbomCommand(comp, session);
				command.executeModal();
			} catch (Exception e1) {
				//  Auto-generated catch block
				e1.printStackTrace();
			}
		}
		else
		{
			this.dispose();
		}
	}
	Map<TCComponentItem, Map<TCComponentItemRevision, List<BomValBean>>> bomStructMap = 
			new HashMap<TCComponentItem, Map<TCComponentItemRevision, List<BomValBean>>>();
	TCComponentBOMLine resultTopline = null;
	
	TCComponentItem topLineItem = null;
	
	
	/**
	 * 重新搭建BOM
	 * 
	 * @param topItem
	 * @throws TCException
	 */
	private void adaptiveVariants(DefaultMutableTreeTableNode tableNode, TCComponentItemType itemType, 
			boolean ifCreate) throws Exception {
		TCComponentItem topItem = null;
		//存放id相同时，更新数量
//		LinkedHashMap<TCComponentItemRevision, Integer> countMap = 
//				new LinkedHashMap<TCComponentItemRevision, Integer>();
//		存放id相同时，更新数量
//		List<String> 
//		LinkedHashMap<TCComponentItemRevision, TCComponentItemRevision> pcMap = 
//				new LinkedHashMap<TCComponentItemRevision, TCComponentItemRevision>();
//		ArrayList<TCComponentItemRevision> itemList = new ArrayList<TCComponentItemRevision>();
//		Map<String,String> itemNumMap = new HashMap<String, String>();
		
		NodeBean pBean = (NodeBean) tableNode.getUserObject();
		Map<TCComponentItemRevision, List<BomValBean>> bomValMap = pBean.getBomValMap();
		System.out.println("bomValMap:" + bomValMap.toString());
		TCComponentItemRevision parentRev = pBean.getRev();
		Map<TCComponentItemRevision, List<BomValBean>> childMap = 
				new HashMap<TCComponentItemRevision, List<BomValBean>>();
		boolean topFlag = false;
		for (int i = 0; i < tableNode.getChildCount(); i++) {
			DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) tableNode.getChildAt(i);
			NodeBean childBean = (NodeBean) childNode.getUserObject();
			if(childBean.getLabel().equals("1") && !childBean.getEbom().isEmpty()) {
				topFlag = true;
//				topItem = itemType.findItems(childBean.getEbomId())[0];
				TCComponentItemRevision comp = (TCComponentItemRevision) childBean.getTcComponent();
				System.out.println("childBean:" + comp);
				topItem = comp.getItem();
				for (int j = 0; j < tableNode.getChildCount(); j++) {
					DefaultMutableTreeTableNode node = (DefaultMutableTreeTableNode) tableNode.getChildAt(j);
					NodeBean topBean = (NodeBean) node.getUserObject();
					
					if(topBean.getIsTw()) {
						System.out.println("=================");
						DefaultMutableTreeTableNode rootNode = topBean.getRootNode();
						NodeBean rootBean = (NodeBean) rootNode.getUserObject();
						Map<TCComponentItemRevision, List<BomValBean>> rootValMap = rootBean.getBomValMap();
//							System.out.println(topBean.getpRev());
						System.out.println(topBean.getRev());
						if(rootValMap.containsKey(topBean.getRev())) {
							List<BomValBean> list = rootValMap.get(topBean.getRev());
							childMap.put(topBean.getRev(), list);
							System.out.println("list==" + list.toString());
						}
						System.out.println(rootValMap.toString());
						if(topLineItem == null) {
							topLineItem = topItem;
						}
						continue;
					}
					
//					System.out.println(bomValMap.toString() + "pBean==" + pBean.getDbom());
					System.out.println("topBean==" + topBean.getDbom() + "==>" + topBean.getTcComponent());
					TCComponentBOMLine dbom = topBean.getBom();
					System.out.println("dbom:" + dbom + "==>" + dbom.isPacked());
					BomValBean pValBean = new BomValBean();
					pValBean.setBl_czbh(dbom.getStringProperty("bl_sequence_no"));
					pValBean.setBl_jdjz(dbom.getStringProperty("bl_plmxml_abs_xform"));
					pValBean.setBl_quantity(dbom.getProperty("bl_quantity"));
					if(pValBean.getBl_quantity().isEmpty())
						pValBean.setBl_quantity("1");
					int index = 0;
					for (int k = 0; k < node.getChildCount(); k++) {
						DefaultMutableTreeTableNode childTableNode = (DefaultMutableTreeTableNode) node.getChildAt(k);
						NodeBean childNodeBean = (NodeBean) childTableNode.getUserObject();
						if(childNodeBean.getLabel().equals("1")) {
							if(index > 0) {
								builder.append(pBean.getDbom()).append("勾选了多个物料;\n");
							}
							index = index + 1;
							TCComponentItemRevision nodeComp = (TCComponentItemRevision) childNodeBean.getTcComponent();
							TCComponentItem item = nodeComp.getItem();
							System.out.println("childNodeBean:" + nodeComp);
//							if(childNodeBean.getEbomId() == null || childNodeBean.getEbomId().isEmpty()) {
//								String dbom = childNodeBean.getDbom();
//								String id = "";
//								if(dbom.contains("-")) {
//									id = dbom.substring(0, dbom.indexOf("-"));
//								}else {
//									id = dbom;
//								}
//								item = itemType.findItems(id)[0];
//							}else {
//								item = itemType.findItems(childNodeBean.getEbomId())[0];
//							}	
							if(preList.contains(item.getType())){
								continue;
							}
							String num = childNodeBean.getNum();
							if(num == null || num.isEmpty() || num.equals("0")) {
								num = "1";
							}
							TCComponentItemRevision latestItemRevision = item.getLatestItemRevision();
							
							TCComponentItemRevision pRev = childNodeBean.getpRev();
							System.out.println("pRev：" + pRev);
							if(dbom.isPacked() && bomValMap.containsKey(pRev)) {
								List<BomValBean> list = bomValMap.get(pRev);
								childMap.put(latestItemRevision, list);
							}else {
								//TODO lidy20241211 
								List<BomValBean> list = new ArrayList<>();
								list.add(pValBean);
								childMap.put(latestItemRevision, list);
							}
							
							TCComponent tcComponent = childNodeBean.getTcComponent();
							Boolean jxzjBoolean = true;
							if(parentRev != null) {
								TCComponent rev = tcComponent;
								jxzjBoolean = acs.checkAccessorsPrivilege(user, rev, "WRITE");
								if(!jxzjBoolean ) { //|| childNodeBean.getEbom().contains("55")
//									System.out.println(topItem+"权限检查iiiiiiii");
									//lidy20240914没有子级的对象不提示
									boolean has = false;
									for (int l = 0; l < node.getChildCount(); l++) {
										DefaultMutableTreeTableNode cn = (DefaultMutableTreeTableNode) node.getChildAt(l);
										NodeBean cnb = (NodeBean) cn.getUserObject();
										if(!cnb.getDbom().isEmpty()) {
											has = true;
											break;
										}
									}
									if(has)
										msg2.append(rev).append("、");
									if(rev instanceof TCComponentItemRevision) {
										items.add(((TCComponentItemRevision)rev).getItem());
									}else if(rev instanceof TCComponentItem){
										items.add((TCComponentItem)rev);
									}
								}
							}
							if(topLineItem == null) {
								topLineItem = topItem;
							}
							System.out.println(tcComponent + "权限检查" + jxzjBoolean);
							if(!jxzjBoolean) {
								continue;
							}
							String status = childNodeBean.getRefreshStatus();
							if(status.equals("属性发布") || status.equals("流程中") || status.equals("")) {
								adaptiveVariants((DefaultMutableTreeTableNode)(childTableNode.getParent()), 
										itemType,true);
							}
						}
					}
					if(!topBean.getDbom().equals("") && index == 0) {
						builder.append(topBean.getDbom()).append("没有勾选物料;\n");
					}
				}
			}
		}
		if(!topFlag) {
			falg1 = false;
			MessageBox.post("未选择顶层物料，无法创建","提示",2);
		}
		if(topItem != null) {
			bomStructMap.put(topItem, childMap);
		}
	}
	@SuppressWarnings("deprecation")
	private void reBuildBOM() throws Exception {
		
		System.out.println("reBuildBOM==>" + bomStructMap.toString());
		
		if(topLineItem != null) {
			Map<TCComponentItemRevision, List<BomValBean>> map2 = bomStructMap.get(topLineItem);
			
			TCComponentBOMWindow bomWindow = null;
			try {
				TCComponentBOMWindowType bomWindowType = (TCComponentBOMWindowType) session
						.getTypeComponent("BOMWindow");
				bomWindow = bomWindowType.create(null);
				TCComponentBOMLine topline = bomWindow.setWindowTopLine(topLineItem,
						topLineItem.getLatestItemRevision(), null, null);
				bomWindow.lock();
				recreateBom2(topLineItem, map2, topline);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
			bomWindow.save();
			bomWindow.unlock();
			bomWindow.refresh();
		}
		
	}
	/**
	 * 重新搭建BOM遍历
	 * 
	 * @param item
	 * @param itemlists
	 * @throws TCException
	 */
	@SuppressWarnings("deprecation")
	private void recreateBom2(TCComponentItem topItem, 
			Map<TCComponentItemRevision, List<BomValBean>> map2,TCComponentBOMLine topline)
			throws Exception {
//		TCComponentBOMWindow bomWindow = null;
		try {
			topline.refresh();
			topline.lock();
			System.out.println("items==>" + items.toString()); 
			List<TCComponentBOMLine> bomLines = new ArrayList<TCComponentBOMLine>();
			
			if (topline.hasChildren()) {
				System.out.println(topItem);
				if(items.contains(topItem)) {
					return;
				}
				AIFComponentContext[] childrens = topline.getChildren();
				for (AIFComponentContext children : childrens) {
					TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent();
					if(bLine.isPacked())
						bLine.unpack();
				}
				topline.refresh();
				childrens = topline.getChildren();
				for (AIFComponentContext children : childrens) {
					TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent();
					System.out.println("addorcut===>" + bLine);
					if(bLine.getStringProperty("J6_BOM_DTE").equals("DBOM转换")) { //J6_BOM_DTE bl_ref_designator
						System.out.println("cut");
						bLine.cut();
					}else {
						System.out.println("add");
						bomLines.add(bLine);
					}
				}
			}
			String maxSeq = "";

			System.out.println("topline===>" + topline);
			topline.setPrecision(true);
			for(TCComponentItemRevision rev : map2.keySet()) {
				List<BomValBean> list = map2.get(rev);
				System.out.println("list===>" + list.toString());
				for(BomValBean bean : list) {
					TCComponentItem item = rev.getItem();
					TCComponentBOMLine add = topline.add(item, rev, null, false, "");
					add.lock();
					add.setStringProperty("bl_quantity", bean.getBl_quantity());
					add.setStringProperty("bl_plmxml_abs_xform", bean.getBl_jdjz());//bl_plmxml_occ_xform
					add.setStringProperty("bl_sequence_no", bean.getBl_czbh());
					System.out.println("add===>" + add + ">>>" + bean.getBl_quantity());//TODO add
//					System.out.println("bean.getBl_czbh()==>" + bean.getBl_czbh());
//					System.out.println("maxSeq==>" + maxSeq);
					if(maxSeq.compareTo(bean.getBl_czbh())<0) {
//						System.out.println(maxSeq);
						maxSeq = bean.getBl_czbh();
					}
					add.setStringProperty("J6_BOM_DTE", "DBOM转换"); ////J6_BOM_DTE
					add.save();
					add.unlock();
					if(bomStructMap.containsKey(item)) {
						Map<TCComponentItemRevision, List<BomValBean>> map3 = bomStructMap.get(item);
						recreateBom2(item, map3, add);
					}
					
				}
			}
			if(!maxSeq.equals("")) {
				Integer valueOf = Integer.valueOf(maxSeq);
				for(TCComponentBOMLine bomLine : bomLines) {
					bomLine.lock();
					valueOf = valueOf + 10;
					bomLine.setStringProperty("bl_sequence_no", String.valueOf(valueOf));
					bomLine.save();
					bomLine.unlock();
				}
			}
			
			topline.save();
			topline.unlock();
			topline.refresh();
		} catch (Exception e) {
			// : handle exception
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 重新搭建BOM
	 * 
	 * @param item
	 * @param itemlists
	 * @throws Exception
	 
	@SuppressWarnings("deprecation")
	private void recreateBom(TCComponentItemRevision topItemRev, 
			boolean isDelete,Map<TCComponentItemRevision, List<BomValBean>> map2)
			throws Exception {
		TCComponentBOMWindow bomWindow = null;
		try {
			TCComponentBOMWindowType bomWindowType = (TCComponentBOMWindowType) session
					.getTypeComponent("BOMWindow");
			bomWindow = bomWindowType.create(null);
			TCComponentBOMLine topline = bomWindow.setWindowTopLine(topItemRev.getItem(),
					topItemRev, null, null);
			resultTopline = topline;
			bomWindow.lock();
			topline.lock();
			System.out.println("items==>"+items.toString());
			List<TCComponentBOMLine> bomLines = new ArrayList<TCComponentBOMLine>();
			if (isDelete) {
				if (topline.hasChildren()) {
					System.out.println(topItemRev.getItem());
					if(items.contains(topItemRev.getItem())) {
						return;
					}
					AIFComponentContext[] childrens = topline.getChildren();
					for (AIFComponentContext children : childrens) {
						TCComponentBOMLine bLine = (TCComponentBOMLine) children.getComponent();
						if(bLine.getStringProperty("J6_BOM_DTE").equals("DBOM转换")) {
							bLine.cut();
						}else {
							bomLines.add(bLine);
						}
					}
				}
			}
			String maxSeq = "";
			for(TCComponentItemRevision rev:map2.keySet()) {
				List<BomValBean> list = map2.get(rev);
				for(BomValBean bean:list) {
					TCComponentBOMLine add = topline.add(rev.getItem(), rev, null, false, "");
					add.lock();
					add.setStringProperty("bl_quantity", bean.getBl_quantity());
					add.setStringProperty("bl_plmxml_occ_xform", bean.getBl_jdjz());
					add.setStringProperty("bl_sequence_no", bean.getBl_czbh());
					System.out.println("bean.getBl_czbh()==>"+bean.getBl_czbh());
					System.out.println("maxSeq==>"+maxSeq);
					if(maxSeq.compareTo(bean.getBl_czbh())<0) {
//						System.out.println(maxSeq);
						maxSeq = bean.getBl_czbh();
					}
					
					add.setStringProperty("J6_BOM_DTE","DBOM转换");
					add.save();
					add.unlock();
				}
			}
			if(!maxSeq.equals("")) {
				Integer valueOf = Integer.valueOf(maxSeq);
				for(TCComponentBOMLine bomLine : bomLines) {
					bomLine.lock();
					valueOf = valueOf + 10;
					bomLine.setStringProperty("bl_sequence_no", String.valueOf(valueOf));
					bomLine.save();
					bomLine.unlock();
				}
			}
			
			topline.save();
			topline.unlock();
			topline.refresh();
			if(topline.getBOMView() != null)
			{
				topline.getBOMView().save();
				topline.getBOMView().refresh();
			}
		} catch (Exception e) {
			// : handle exception
			e.printStackTrace();
		}
		bomWindow.save();
		bomWindow.unlock();
		bomWindow.refresh();
	}*/

}
