/*
#=============================================================================
#																			   
#			opyright (c) 2009 Origin Enterprise Solution LTD.		   
#																			   
#=============================================================================
# File name: CopyFolderAndAssginToProjectDialog.java
# File description: 										   	
#=============================================================================
#	Date		Name		Action	Description of Change					   
#	2017-5-10	Administrator  	Ini		初始化										   
#=============================================================================
 */
package cn.com.customization.project;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.commands.paste.PasteOperation;
import com.teamcenter.rac.common.create.BOCreateDefinition;
import com.teamcenter.rac.common.create.BOCreateDefinitionFactory;
import com.teamcenter.rac.common.create.CreateInstanceInput;
import com.teamcenter.rac.common.create.ICreateInstanceInput;
import com.teamcenter.rac.common.create.SOAGenericCreateHelper;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentFolderType;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentProjectType;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.util.ButtonLayout;
import com.teamcenter.rac.util.HorizontalLayout;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.VerticalLayout;

/**
 * @author Administrator
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class CopyFolderAndAssginToProjectDialog extends AbstractAIFDialog {

	private static final long	serialVersionUID	= 1L;
	TCSession					session;
	AbstractAIFUIApplication	app;

	private JList folderList;
	private JList proList; 
	private JTextField jt2; 
	private String folderType;
	private InterfaceAIFComponent selectTarget;
	
	public CopyFolderAndAssginToProjectDialog(AbstractAIFUIApplication application, TCSession pSession,
			Frame frame, boolean flag, String folderType, InterfaceAIFComponent selectTarget) {
		super(frame, flag); // true
		session = pSession;
		app = application;
		this.folderType = folderType;
		this.selectTarget = selectTarget;
		init();
	}

	private void init() {
		setTitle("创建项目资料夹");
		JPanel jptop = new JPanel(new HorizontalLayout());
		final JPanel jptopleft = new JPanel(new PropertyLayout(2,2,2,2,2,2));
		final JPanel jptopright = new JPanel(new VerticalLayout());
		Vector folderv = listDCProjTemplFolder();
		folderList = new JList(folderv);
		folderList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		jptopleft.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "请选择将要复制的文件夹", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("新宋体", 0, 12))); // NOI18N
		JScrollPane folderscrollPane = new JScrollPane();
		folderscrollPane.setPreferredSize(new Dimension(210,310));
		folderscrollPane.getViewport().add(folderList);
		jptopleft.add("1.1.left.center", folderscrollPane);
		
		Vector prov = listPro("*");
		proList = new JList(prov);
		jptopright.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "指派到的项目", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("新宋体", 0, 12))); // NOI18N
		
		proList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane proscrollPane = new JScrollPane(proList);
		proscrollPane.setPreferredSize(new Dimension(210,310));
		
		final JTextField jt = new JTextField(30);

		jt.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent ke) {
				char code = ke.getKeyChar();
				if (code == KeyEvent.VK_ENTER) {
					System.out.println("ceshi 回车" + code + "=====" + KeyEvent.VK_ENTER);
					Vector pronewVector = listPro(jt.getText());
					proList.setListData(pronewVector);
				}
			}

		});
		jptopright.add("top.bind.center.top", jt);
		jptopright.add("top.bind.center.top", proscrollPane);

		jptop.add("1.1.center.center.resizable.resizable", jptopleft);
		jptop.add("1.2.center.center.resizable.resizable", jptopright);
		
		JPanel jp1 = new JPanel(new HorizontalLayout());
		jt2 = new JTextField(20);
		
		jp1.add("left.bind.center.center", new JLabel("新创建文件夹名字"));
		jp1.add("unbound.bind.center.center", jt2);
		
		JPanel butPanel = new JPanel(new ButtonLayout());
		JButton okbtn = new JButton("开始复制");
		JButton canceltn = new JButton("取消");
		butPanel.add(okbtn);
		butPanel.add(canceltn);
		canceltn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent actionevent) {
				dispose();
			}
		});

		JPanel jpx = new JPanel(new VerticalLayout());
		jpx.add("top.bind.center.top", jptop);
		jpx.add("top.bind.center.top", jp1);
		jpx.add("top.bind.center.top", butPanel);
		okbtn.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent actionevent) {
				try {
					doCopy();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		MouseListener mouseListener = new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				TCComponentProject tcproject = (TCComponentProject) proList.getSelectedValue();
				try {
					String proid = tcproject.getStringProperty("project_id");
					jt2.setText(proid);
				} catch (TCException e1) {
					e1.printStackTrace();
				}
			}
		};
		proList.addMouseListener(mouseListener);
		add(jpx);
		setResizable(false);
		pack();
		centerToScreen();
		setVisible(true);
	}

	/**
	 * listDCProjTemplFolder:查询系统项目对象
	 */
	public Vector<TCComponentFolder> listDCProjTemplFolder() {
		Vector<TCComponentFolder> result = new Vector<TCComponentFolder>();
		try {
			String str_key = "object_type";
			String str_value = "YSR8_ProjTemplFolder";

//			if(folderType.equals("cDC_Projectfolder")){
//				str_value = "cDC_Kprojtemplfolder";
//			}
			TCTextService textService = session.getTextService();
			TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			TCComponentQuery query = (TCComponentQuery) querytype.find("__findfolder");
			System.out.println("getTextValue===========" + textService.getTextValue(str_key));
			if (null == query) {
				MessageBox.post(app.getDesktop().getShell(), "请先创建查询构建器findfolder！", "警告", MessageBox.ERROR);
				return null;
			}

			querytype.clearCache();
			String as[] = { textService.getTextValue(str_key) };
			String as1[] = new String[1];
			as1[0] = str_value;
			query.clearCache();
			TCComponentContextList list = query.getExecuteResultsList(as, as1); // as
			// =查询key
			// ;
			// as1
			// =查询value
			TCComponentFolder tcfolder = null;
			if (list != null) {
				int count = list.getListCount();
				System.out.println(" folder  coutn " + count);
				for (int i = 0; i < count; i++) {
					tcfolder = (TCComponentFolder) list.get(i).getComponent();
					result.add(tcfolder);
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * listPro:获取系统中的项目
	 */
	public Vector<TCComponentProject> listPro(String str_value) {
		Vector<TCComponentProject> result = new Vector<TCComponentProject>();
		try {
			String str_key = "project_id";
			TCTextService textService = session.getTextService();
			TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			TCComponentQuery query = (TCComponentQuery) querytype.find("__findproject");
			if (null == query) {
				MessageBox.post(app.getDesktop().getShell(), "请先创建查询构建器__findproject ！", "警告", MessageBox.ERROR);
				return null;
			}

			querytype.clearCache();
			String as[] = { textService.getTextValue(str_key), textService.getTextValue("is_active")};
			// String as[] = { "project_name" };
			System.out.println("getTextValue===========" + textService.getTextValue(str_key));
			String as1[] = new String[2];
			as1[0] = str_value;
			as1[1] = "true";
			query.clearCache();
			TCComponentContextList list = query.getExecuteResultsList(as, as1); // as
			// =查询key
			// ;
			// as1
			// =查询value
			TCComponentProject tcpro = null;

			if (list != null) {
				int count = list.getListCount();
				System.out.println(" pro  coutn " + count);
				for (int i = 0; i < count; i++) {
					tcpro = (TCComponentProject) list.get(i).getComponent();
					result.add(tcpro);
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * pasteNewFolder:把对象拷贝到文件夹
	 */
	public void pasteNewFolder(TCComponentFolder newFolder, InterfaceAIFComponent pasteTarget) throws Exception { // InterfaceAIFComponent[]pasteTargets
		
		TCComponentFolder parentcom = (TCComponentFolder)pasteTarget;
		InterfaceAIFComponent childcoms = newFolder;
		PasteOperation op = new PasteOperation(app,parentcom,childcoms,"contents");
		op.executeOperation();
	}

	/**
	 * assigntoPro:把对象指派到项目
	 */
	public void assigntoPro(TCComponentProject atccomponentproject, TCComponent atccomponent) {

		TCComponentProjectType tccomponentprojecttype;
		try {
			tccomponentprojecttype = (TCComponentProjectType) session.getTypeComponent("TC_Project");
			tccomponentprojecttype.assignToProject(atccomponentproject, atccomponent);
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * createFolder:创建文件夹
	 */
	public void createFolder(TCComponentFolder tcf, TCComponentProject tcproject, TCComponentFolder parent) {
		try {
			AIFComponentContext[] aifcon = tcf.getChildren();
			for (int i = 0; i < aifcon.length; i++) {
				String type = aifcon[i].getComponent().getType();
				System.out.println("in getFolderName () the type = " + type);
				if (type.equals("Folder")) {
					String folderName = aifcon[i].getComponent().getProperty("object_name");
					String folderDescription = "";
					String newFolderType = "Folder";
					TCComponentFolder newFolder = null;
					TCComponentFolderType tccomponentfoldertype;
					try {
						tccomponentfoldertype = (TCComponentFolderType) session.getTypeComponent(newFolderType);
						newFolder = tccomponentfoldertype.create(folderName, folderDescription, newFolderType);

					} catch (TCException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					InterfaceAIFComponent pasteTarget = parent;
					pasteNewFolder(newFolder, pasteTarget);
					assigntoPro(tcproject, newFolder);

					TCComponentFolder tcfolder = (TCComponentFolder) aifcon[i].getComponent();
					createFolder(tcfolder, tcproject, newFolder);
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * createFolder:创建文件夹
	 */
	public void createKSMFolder(TCComponentFolder tcf, TCComponentProject tcproject, TCComponentFolder parent) {
		try {
			AIFComponentContext[] aifcon = tcf.getChildren();
			for (int i = 0; i < aifcon.length; i++) {
				String type = aifcon[i].getComponent().getType();
				System.out.println("in getFolderName () the type = " + type);
				if (type.equals("Folder")) {
					String folderName = aifcon[i].getComponent().getProperty("object_name");
					TCComponentFolder newFolder = null;
					List<ICreateInstanceInput> input = new ArrayList<ICreateInstanceInput>();
					BOCreateDefinition itemDef = (BOCreateDefinition) BOCreateDefinitionFactory.getInstance().getCreateDefinition(session, "cDC_Projectfolder");
					CreateInstanceInput createInput = new CreateInstanceInput(itemDef);
					createInput.add("object_name", folderName);
					input.add(createInput);
					
					//SOAGenericCreateHelper helper = new SOAGenericCreateHelper();
					List list1 = SOAGenericCreateHelper.create(session, itemDef, input);
					Iterator it = list1.iterator();
					TCComponent component = null;
					do {
						if (!it.hasNext())
							break;
						component = (TCComponent) it.next();
					} while (!(component instanceof TCComponentFolder));
					newFolder = (TCComponentFolder) component;
					
					InterfaceAIFComponent pasteTarget = parent;
					pasteNewFolder(newFolder, pasteTarget);
					assigntoPro(tcproject, newFolder);

					TCComponentFolder tcfolder = (TCComponentFolder) aifcon[i].getComponent();
					createKSMFolder(tcfolder, tcproject, newFolder);
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * doCopy:在满足条件的情况下复制
	 * */
	private boolean doCopy(){
		try {
//			InterfaceAIFComponent[] pasteTargets = app.getTargetComponents();
			if(folderList.getSelectedIndex() == -1 || proList.getSelectedIndex() == -1 || jt2.getText().equals("") ){
				MessageBox.post(app.getDesktop().getShell(), "模板文件夹、项目、新创建文件夹名称都不能为空！", "警告", MessageBox.WARNING);
				return false;
			}
			
			TCComponentFolder tcfolder = (TCComponentFolder) folderList.getSelectedValue();
			TCComponentProject tcproject = (TCComponentProject) proList.getSelectedValue();
			
			if (selectTarget.equals(tcfolder)) {
				MessageBox.post(app.getDesktop().getShell(), "复制目标不能是同一个文件夹！", "警告", MessageBox.WARNING);
				return false;
			}
			System.out.println("jt2 text " + jt2.getText());
			
			if(folderType.equals("cDC_Projectfolder")){
				TCComponentFolder newFolder = null;
				List<ICreateInstanceInput> input = new ArrayList<ICreateInstanceInput>();
				BOCreateDefinition itemDef = (BOCreateDefinition) BOCreateDefinitionFactory.getInstance().getCreateDefinition(session, "cDC_Projectfolder");
				CreateInstanceInput createInput = new CreateInstanceInput(itemDef);
				createInput.add("object_name", jt2.getText());
				input.add(createInput);
				
				//SOAGenericCreateHelper helper = new SOAGenericCreateHelper();
				List list1 = SOAGenericCreateHelper.create(session, itemDef, input);
				Iterator it = list1.iterator();
				TCComponent component = null;
				do {
					if (!it.hasNext())
						break;
					component = (TCComponent) it.next();
				} while (!(component instanceof TCComponentFolder));
				newFolder = (TCComponentFolder) component;
				pasteNewFolder(newFolder, selectTarget);
				assigntoPro(tcproject, newFolder);
				
				createKSMFolder(tcfolder, tcproject, newFolder);
				
			}else{
				TCComponentFolder newFolder = null;
				TCComponentFolderType tccomponentfoldertype;
				tccomponentfoldertype = (TCComponentFolderType) session.getTypeComponent("Folder");
				newFolder = tccomponentfoldertype.create(jt2.getText(), "", "Folder");
	
				session.setStatus("正在复制模板文件目录,请稍等...");
				pasteNewFolder(newFolder, selectTarget);
				assigntoPro(tcproject, newFolder);
				System.out.println("first folder create end ");
				createFolder(tcfolder, tcproject, newFolder);
			}
			System.out.println("actionPerformed  end ");
			dispose();
		} catch (TCException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.setReadyStatus();
		}
		return true;
	}
}
