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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;

import com.connor.ml.tcm.outfile.bean.NodeBean;
import com.teamcenter.rac.aif.AbstractAIFCommand;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class DbomTransitionToEbomCommand extends AbstractAIFCommand {

	private InterfaceAIFComponent comp;
	private TCSession session;
	private TCComponentBOMLine bomLine = null;
	static ArrayList<String> preList = new ArrayList<String>();
	private TCAccessControlService acs;
	private TCComponent[] user;
	private String[] props;
	
	public DbomTransitionToEbomCommand(InterfaceAIFComponent comp, TCSession session) {
		//  Auto-generated constructor stub
		this.comp = comp;
		this.session = session;
	}
	private List<String> ebomList;
	@Override
	public void executeModal() throws Exception {
		//  Auto-generated method stub
//		TCComponentType compType = session.getTypeComponent("ML8_Washing");
//		   String[] allProperties=compType.getPropertyNames();//获取类所有属性
		   //TCProperty[] allProperties=compType.getPropertyNames();//获取类所有属性
		acs = session.getTCAccessControlService();
		user = new TCComponent[]{ session.getUser(), session.getGroup(), session.getRole() };
		//获取选中的对象
		if(!(comp instanceof TCComponentBOMLine))
		{
			MessageBox.post("请在结构管理器中选中BOMLine对象！", "错误", MessageBox.ERROR);
			return;
		}
		//System.out.println("11111111111");
		bomLine = (TCComponentBOMLine) comp;

		//判断对象类型
		TCComponentItem item = bomLine.getItem();
//		boolean isTypeof=false;
		String[] prefValues = session.getPreferenceService().getStringValues("Pma0_Part_Design_Type");
		String[] ebomType = session.getPreferenceService().getStringValues("Pma0_EBOM_Type");
		
		ebomList = Arrays.asList(ebomType);
		System.out.println("ebomList==>"+ebomList);
		List<String> dtypeList = new ArrayList<String>();
		Map<String,String> DETypeMap = new HashMap<String,String>();
		for(String pref : prefValues) {
			String[] split = pref.split(",");
			String etypeString = split[0];
			String dtypeString = split[1];
			DETypeMap.put(dtypeString.replaceAll("DesignType:", ""), etypeString.replaceAll("PartType:", ""));
			dtypeList.add(dtypeString.replaceAll("DesignType:", ""));
			preList.add(dtypeString.replaceAll("DesignType:", ""));
//			if(pref.equals(item.getType())) {
//				isTypeof = true;
//			}
		}
		System.out.println(item.getType()+"dtypeList==>"+dtypeList.toString());
		if(!dtypeList.contains(item.getType())) {
			MessageBox.post("请选中设计对象", "提示", 2);
			return;
		}
		//lidy20240923界面中，BOM属性列的显示做成可配置，配置属性为BOMline属性的真实值
		String[] options = session.getPreferenceService().getStringValues("Pma0_Table_Columns");
//		if(options == null || options.length == 0) {
//			MessageBox.post("首选项配置不正确", "提示", 2);
//			return;
//		}
		String[] header = new String[options.length + 5];
		props = new String[options.length];
		header[0] = "DBOM对象";
		header[1] = "对应父节点";
		header[2] = "EBOM对象";
		header[3] = "发布状态";
		header[4] = "选中";
		for(int i = 0; i < options.length; i++) {
			String[] split = options[i].split("=");
			header[i + 5] = split[0];
			props[i] = split[1];
		}
		
		new Thread() {
			@Override
			public void run() {
				ProcessBarDialog progress = new ProcessBarDialog("正在加载BOM转换页面...");
			    progress.open();
				try {
					DefaultMutableTreeTableNode node = getBomPropertyToNode(session, bomLine);
					progress.close();
//					DbomTransitionToEbomDialog dialog = 
							new DbomTransitionToEbomDialog(comp, session, node, preList, progress, header);
				} catch (Exception e) {
					//  Auto-generated catch block
					e.printStackTrace();
					progress.close();
				}
			}
		}.start();
//		super.executeModal();
	}
//	private Map<TCComponentItemRevision, List<BomValBean>> bomValMap = new HashMap<TCComponentItemRevision, List<BomValBean>>();
	
	/**
	 * 全部打包
	 * 
	 * @param topBomline
	 
	private void packAll(TCComponentBOMLine topBomline) throws Exception {
		TCComponentBOMLine[] bomlines = new TCComponentBOMLine[1];
		bomlines[0] = topBomline;
		StructureService structureService = StructureService.getService(session.getSoaConnection());
//		ServiceData serviceData = 
				structureService.packOrUnpack(bomlines, 2);
//		serviceDat
//		TCServiceExceptionUtils.validateServiceException(serviceData);
	}*/
	/**
	 * 获取BOM属性
	 * @throws TCException 
	 */
	private DefaultMutableTreeTableNode getBomPropertyToNode(TCSession session, TCComponentBOMLine topBomLine) 
			throws Exception {
		//  Auto-generated method stub
		
		NodeBean nodeBean = new NodeBean();

		//对象ID
		nodeBean.setDbom("顶层");
		nodeBean.setEbom("");
//		nodeBean.setEbomId("");
		nodeBean.setNum("");
		nodeBean.setLabel("");
		nodeBean.setRefreshStatus("");
		nodeBean.setParentString("");
		
		DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode(nodeBean);
		//获取BOM 
		try {
			//getRepresentationPropertysToNode(topBomLine, rootNode, "");
			getBomPropertysToNode(topBomLine, rootNode, "",null);
			return rootNode;
		} catch (Exception e) {
			// : handle exception
			e.printStackTrace();
		}
		return null;
	}
	/***
	 * 获取表示下的对象
	 * @param bomLine
	 * @param rootNode
	 * @param parentID
	 * @throws TCException 
	 */
	private Boolean getRepresentationPropertysToNode(TCComponentBOMLine bomLine, DefaultMutableTreeTableNode rootNode)
			throws Exception {
//			, String parentID,String quantity,String blJz) throws Exception {
		Boolean jxZk = false;
		TCComponentItemRevision itemRevision = bomLine.getItemRevision();
		//刷新表示关系
		//TCComponent referenceProperty = itemRevision.getReferenceProperty("representation_for");
		//referenceProperty.refresh();
		//获取表示关系下的对象
		itemRevision.refresh();
		TCComponent[] tcComponents = itemRevision.getReferenceListProperty("representation_for");
		for (TCComponent tcComponent : tcComponents) {
			
			TCProperty refreshStatusProperty = tcComponent.getTCProperty("release_status_list");
			TCComponent[] refreshStatus = refreshStatusProperty.getReferenceValueArray();
			TCProperty processProperty = tcComponent.getTCProperty("process_stage_list");
			TCComponent[] processStage = processProperty.getReferenceValueArray();
			
			NodeBean nodeBean = new NodeBean();
			String stringProperty = tcComponent.getStringProperty("object_string");
			nodeBean.setDbom("");
			nodeBean.setEbom(stringProperty);
//			nodeBean.setEbomId(tcComponent.getStringProperty("item_id"));
//			nodeBean.setEbomDesc(tcComponent.getStringProperty("object_desc"));
			nodeBean.setNum(bomLine.getStringProperty("bl_quantity"));
			nodeBean.setBom(bomLine);
			for(int i = 0; i < props.length; i++) {
				System.out.println("setValueAt" + (i + 5) + "==" + props[i] + "==" + bomLine.getProperty(props[i]));
				nodeBean.setValueAt(i + 5, tcComponent.getProperty(props[i]));//TODO lidy20240925D转E需要显示的属性调整成物料版本属性
			}
			nodeBean.setTcComponent(tcComponent);
			nodeBean.setpRev(itemRevision);
			nodeBean.setLabel("0");
//			nodeBean.setBl_plmxml_abs_xform(bomLine.getProperty("bl_plmxml_occ_xform"));
			if(refreshStatus.length > 0) {
				StringBuffer stringBuffer = new StringBuffer();
				//添加发布状态
				for (int i = 0; i < refreshStatus.length; i++) {
					stringBuffer.append(refreshStatus[i].toString());
					if(i < refreshStatus.length - 1) {
						stringBuffer.append(",");
					}
				}
				nodeBean.setRefreshStatus(stringBuffer.toString());
			}else if(processStage.length > 0) {
				nodeBean.setRefreshStatus("流程中");
			}else {
				nodeBean.setRefreshStatus("");
			}
			nodeBean.setParentString(itemRevision.getStringProperty("object_string"));
			
			DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(nodeBean);
			rootNode.add(node);
			
			if(tcComponents.length == 1) {
				if(getTopRefresh(node)) {
					nodeBean.setLabel("0");
				}else {
					nodeBean.setLabel("1");
				}
			}
			
//			String property = tcComponent.getProperty("j6_processtype");
			if(!acs.checkAccessorsPrivilege(user, tcComponent, "WRITE")){ // || stringProperty.contains("55")
				System.out.println(stringProperty + "=====stringProperty");
//				jxZk = false;
//			}else if(property!=null && (property.equals("外购件") || property.equals("外协件"))) {
//				jxZk = false;
			}else {
				//一图多物的情况，只要对一个物具有写权限，就允许展开下级
				jxZk = true;
			}
		}
		return jxZk;
	}
	/***
	 * 判断上级是否勾选已发布对象
	 * @param node
	 * @return
	 */
	private static boolean getTopRefresh(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();) {
      				DefaultMutableTreeTableNode childNode = (DefaultMutableTreeTableNode) rootNode.getChildAt(i);
      				NodeBean childBean = (NodeBean) childNode.getUserObject();
      				if(childBean.getLabel().equals("1") && childBean.getRefreshStatus().indexOf("发布") >= 0) {
      					//MessageBox.post("上层["+childBean.getEbom()+"]已勾选发布的对象，下层不允许勾选！", "错误", MessageBox.ERROR);
      					return true;
      				}
      				else {
      					return getTopRefresh(childNode);
      				}
				}
      		}
      	}
		return result;
	}
	
	
	/**
	 * 获取BOM信息
	 * @param bomLine
	 * @param bomPropertyList
	 * @param parentID
	 */
	private void getBomPropertysToNode(TCComponentBOMLine bomLine, DefaultMutableTreeTableNode rootNode, 
			String parentID, TCComponentBOMLine pLine) {
		try {

			NodeBean nodeBean = new NodeBean();
			String itemType = bomLine.getStringProperty("bl_item_object_type");
			System.out.println(itemType);
//			if(bomLine.getStringProperty("bl_item_object_type").equals("LD6_3Ddesign")) {
//				return;
//			}
			nodeBean.setDbom(bomLine.getStringProperty("bl_item_object_string"));
			nodeBean.setNum(bomLine.getStringProperty("bl_quantity"));
			nodeBean.setEbom("");
//			nodeBean.setEbomId("");
			for(int i = 0; i < props.length; i++) {
				nodeBean.setValueAt(i + 5, bomLine.getProperty(props[i]));
			}
			if(preList.contains(itemType)) {
				nodeBean.setLabel("3");
			}else {
				nodeBean.setLabel("");
			}
			nodeBean.setRev(bomLine.getItemRevision());
			nodeBean.setRefreshStatus("");
			nodeBean.setParentString("");
			nodeBean.setBom(bomLine);
			
			String type = bomLine.getItem().getType();
			if(ebomList.contains(type) || "EDAComp".equals(itemType) || "J6_ZX".equals(itemType) ) {
				nodeBean.setpRev(pLine.getItemRevision());
				nodeBean.setRootNode(rootNode);
				nodeBean.setIsTw(true);
			}
			
//			nodeBean.setBl_plmxml_abs_xform(bomLine.getProperty("bl_plmxml_abs_xform"));
			DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode(nodeBean);
			rootNode.add(node);
			
			getPackMessage(nodeBean, bomLine);

			Boolean jxZk = getRepresentationPropertysToNode(bomLine, node);//, bomLine.getStringProperty("bl_item_item_id"),
//					bomLine.getStringProperty("bl_quantity"), bomLine.getProperty("bl_plmxml_occ_xform"));
			if(jxZk && bomLine.getChildren().length > 0) {//TODO 
				AIFComponentContext aif[] = bomLine.getChildren();
				for (int i = 0; i < aif.length; i++) {
					TCComponentBOMLine subline = (TCComponentBOMLine) aif[i].getComponent();
					if(subline.getLogicalProperty("bl_is_occ_suppressed"))//lidy20240925抑制的事例不应在D转E功能中被转化出来
						continue;
					getBomPropertysToNode(subline, node, bomLine.getStringProperty("bl_item_item_id"), bomLine);
				}
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getPackMessage(NodeBean nodeBean, TCComponentBOMLine bomLine) {
		//  Auto-generated method stub
		try {
			Map<TCComponentItemRevision, List<BomValBean>> bomValMap = new HashMap<TCComponentItemRevision, List<BomValBean>>();
			AIFComponentContext[] children = bomLine.getChildren();
//			boolean hasPack = false;
//			 unpack
			for (int i = 0; i < children.length; i++) {
				TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
				System.out.println(cLine + " 是否打包：" + cLine.isPacked());
				if (cLine.isPacked()) {
					String bl_quantity2 = cLine.getStringProperty("bl_quantity");
					if(bl_quantity2.isEmpty()) {
						bl_quantity2 = "1";
					}
					BigDecimal bigDecimal2 = new BigDecimal(bl_quantity2);
					TCComponentBOMLine[] packedLines = cLine.getPackedLines();
					for(TCComponentBOMLine ccLine : packedLines) {
//						TCComponentBOMLine cLine = (TCComponentBOMLine) children2[i].getComponent();
						TCComponentItemRevision itemRevision = ccLine.getItemRevision();
						String bl_sequence_no = ccLine.getStringProperty("bl_sequence_no");
						String bl_plmxml_abs_xform = ccLine.getStringProperty("bl_plmxml_abs_xform");//bl_plmxml_occ_xform
						String bl_quantity = ccLine.getStringProperty("bl_quantity");
						if(bl_quantity.isEmpty()) {
							bl_quantity = "1";
						}
						bigDecimal2 = bigDecimal2.subtract(new BigDecimal(bl_quantity));
						BomValBean bean = new BomValBean();
						bean.setBl_czbh(bl_sequence_no);
						bean.setBl_jdjz(bl_plmxml_abs_xform);
						bean.setBl_quantity(bl_quantity);
						if(bomValMap.containsKey(itemRevision)) {
							List<BomValBean> list = bomValMap.get(itemRevision);
							list.add(bean);
						}else {
							 List<BomValBean> list = new ArrayList<BomValBean>();
							 list.add(bean);
							 bomValMap.put(itemRevision, list);
						}
					}
					cLine.unpack();
					cLine.refresh();
					TCComponentItemRevision itemRevision = cLine.getItemRevision();
					String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
					String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
					
					BomValBean bean = new BomValBean();
					bean.setBl_czbh(bl_sequence_no);
					bean.setBl_jdjz(bl_plmxml_abs_xform);
					bean.setBl_quantity(bigDecimal2.toString());
					if(bomValMap.containsKey(itemRevision)) {
						List<BomValBean> list = bomValMap.get(itemRevision);
						list.add(bean);
					}else {
						 List<BomValBean> list = new ArrayList<BomValBean>();
						 list.add(bean);
						 bomValMap.put(itemRevision, list);
					}
					cLine.pack();
				}else {
//					TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
					TCComponentItemRevision itemRevision = cLine.getItemRevision();
					String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
					String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
					String bl_quantity = cLine.getStringProperty("bl_quantity");
					BomValBean bean = new BomValBean();
					bean.setBl_czbh(bl_sequence_no);
					bean.setBl_jdjz(bl_plmxml_abs_xform);
					bean.setBl_quantity(bl_quantity);
					if(bomValMap.containsKey(itemRevision)) {
						List<BomValBean> list = bomValMap.get(itemRevision);
						list.add(bean);
					}else {
						 List<BomValBean> list = new ArrayList<BomValBean>();
						 list.add(bean);
						 bomValMap.put(itemRevision, list);
					}
				}
			}
			
//			AIFComponentContext[] children2 = null;
//			if (hasPack) {
//				bomLine.refresh();
//				children2 = bomLine.getChildren();
//				for(int i = 0; i < children2.length; i++) {
//					TCComponentBOMLine cLine = (TCComponentBOMLine) children2[i].getComponent();
//					TCComponentItemRevision itemRevision = cLine.getItemRevision();
//					String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
//					String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
//					String bl_quantity = cLine.getStringProperty("bl_quantity");
//					BomValBean bean = new BomValBean();
//					bean.setBl_czbh(bl_sequence_no);
//					bean.setBl_jdjz(bl_plmxml_abs_xform);
//					bean.setBl_quantity(bl_quantity);
//					if(bomValMap.containsKey(itemRevision)) {
//						List<BomValBean> list = bomValMap.get(itemRevision);
//						list.add(bean);
//					}else {
//						 List<BomValBean> list = new ArrayList<BomValBean>();
//						 list.add(bean);
//						 bomValMap.put(itemRevision, list);
//					}
//				}
//			}else {
//				for(int i = 0; i < children.length; i++) {
//					TCComponentBOMLine cLine = (TCComponentBOMLine) children[i].getComponent();
//					TCComponentItemRevision itemRevision = cLine.getItemRevision();
//					String bl_sequence_no = cLine.getStringProperty("bl_sequence_no");
//					String bl_plmxml_abs_xform = cLine.getStringProperty("bl_plmxml_abs_xform");
//					String bl_quantity = cLine.getStringProperty("bl_quantity");
//					BomValBean bean = new BomValBean();
//					bean.setBl_czbh(bl_sequence_no);
//					bean.setBl_jdjz(bl_plmxml_abs_xform);
//					bean.setBl_quantity(bl_quantity);
//					if(bomValMap.containsKey(itemRevision)) {
//						List<BomValBean> list = bomValMap.get(itemRevision);
//						list.add(bean);
//					}else {
//						 List<BomValBean> list = new ArrayList<BomValBean>();
//						 list.add(bean);
//						 bomValMap.put(itemRevision, list);
//					}
//				}
//			}
			nodeBean.setBomValMap(bomValMap);
			
//			try {
//				if(hasPack) {
//					packAll(bomLine);
//					bomLine.refresh();
//				}
//			} catch (Exception e1) {
//				//  Auto-generated catch block
//				e1.printStackTrace();
//			}
		}catch (Exception e) {
			// : handle exception
			e.printStackTrace();
		}
	}
}
