package cn.net.connor.std.processedit.ldy;

import java.util.HashMap;


import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class ProcessBorrowOperation extends AbstractAIFOperation {
	
	private TCSession session;
	private TCComponentBOMLine target;
	private HashMap<TCComponentItem, TCComponentItemRevision> revMap;
	
	public ProcessBorrowOperation(TCSession session, TCComponentBOMLine target) {
		this.session = session;
		this.target = target;
	}
	
	@Override
	public void executeOperation() throws Exception {
		AIFDesktop desktop = AIFUtility.getActiveDesktop();
		try {
			revMap = new HashMap<>();
			TCComponentItemType itemType = (TCComponentItemType) session.getTypeService().getTypeComponent("LD6_MEProcessCr");
			TCComponentItem item = target.getItemRevision().saveAsItem(itemType.getNewID(), null);
			TCComponentBOMWindow window = TCUtil.getWindow(session);
			TCComponentBOMLine bom = TCUtil.getBOMLine(session, window, item.getLatestItemRevision());
			recycle(bom);
			window.save();
			window.close();
			TCComponentFolder home = session.getUser().getHomeFolder();
			home.add("contents", item);
			
			MessageBox.post(desktop, "工艺路线【"+item+"】已存至Home文件夹下", "INFO", MessageBox.INFORMATION);
		} catch (Exception e) {
			e.printStackTrace();
			MessageBox.post(desktop, "错误："+e.getMessage(), "ERROR", MessageBox.ERROR);
		}
	}
	
	private void recycle(TCComponentBOMLine parent) throws Exception {
		for(AIFComponentContext c : parent.getChildren()) {
			TCComponentBOMLine bom = (TCComponentBOMLine) c.getComponent();
			TCComponentItem item = bom.getItem();
			if(revMap.containsKey(item)) {
				TCComponentItemRevision rev = revMap.get(item);
				bom.replace(rev.getItem(), rev, null);
				continue;
			}
			if(!item.isTypeOf(new String[] { "LD6_MEProcess", "LD6_OMEOP", "LD6_MEOP" }))
				continue;
			TCComponentItemType itemType = (TCComponentItemType) session.getTypeService().getTypeComponent(item.getType());
			TCComponentItem newItem = bom.getItemRevision().saveAsItem(itemType.getNewID(), null);
			TCComponentItemRevision newRev = newItem.getLatestItemRevision();
			bom.replace(newItem, newRev, null);
			revMap.put(item, newRev);
			
			recycle(bom);
		}
	}
}
