package cn.com.customization.create;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

import org.apache.log4j.Logger;

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.AbstractAIFDialog;
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.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentFolderType;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.kernel.TCTypeService;
import com.teamcenter.rac.util.ButtonLayout;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

/**
 * 文件夹复制对话框
 * 
 * @author
 */
@SuppressWarnings("serial")
public class CreateFolderFromTemplateDialog extends AbstractAIFDialog {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CreateFolderFromTemplateDialog.class);

	private TCSession session;

	private TCComponent tcTargets[];

	@SuppressWarnings("rawtypes")
	private JList jlist;

	private TCTypeService tctypeservice;

	private TCComponentFolder selectedFolder = null;

	private AbstractAIFApplication app = null;

	public CreateFolderFromTemplateDialog(Frame parent, AbstractAIFApplication papp) {
		super(parent, true);
		app = papp;
		session = (TCSession) papp.getSession();
		int flag = checkTargets();
		if (flag == 0) {
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					initDialog();
				}
			});

		}

		// } else if (flag == 1) {
		//				
		// MessageBox.post("请选择正确的项目对象！", "提示", 2);
		// } else if (flag == 2) {
		//				
		// MessageBox.post("您没有对选中项目对象的写权限！", "提示", 2);
		// } else if (flag == 3) {
		//				
		// MessageBox.post("请选择项目对象！", "提示", 2);
		// }
	}

	/*
	 * 初始化界面
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void initDialog() {
		this.setTitle("创建常规文件夹结构");
		JPanel mainPanel = new JPanel(new PropertyLayout());
		this.getContentPane().add(mainPanel);
		JPanel listPanel = new JPanel();
		TCComponent[] tccoms = getTemplateFolder();
		// String str[]={"111","2222"};
		jlist = new JList(tccoms);
		jlist.setSelectionMode(0);
		JScrollPane jListScrollPane = new JScrollPane(jlist);
		jListScrollPane.setPreferredSize(new Dimension(380, 150));
		jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listPanel.add(jListScrollPane);

		JPanel botPanel = new JPanel();
		botPanel.setLayout(new ButtonLayout(ButtonLayout.HORIZONTAL, ButtonLayout.CENTER, 10));
		JButton ok_button = new JButton("开始复制");
		ok_button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}

		});

		JButton cannel_button = new JButton("取消");
		cannel_button.setActionCommand("取消");
		cannel_button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				action(e);

			}

		});
		botPanel.add(ok_button);
		botPanel.add(cannel_button);
		JLabel jl1 = new JLabel("请选择要复制的文件夹");

		mainPanel.add("1.1.center.center", jl1);
		mainPanel.add("2.1.center.center", listPanel);
		mainPanel.add("3.1.center.center", botPanel);
		this.pack();
		this.centerToScreen();
		this.setVisible(true);

	}

	@SuppressWarnings("deprecation")
	public void action(ActionEvent e) {
		if (logger.isDebugEnabled()) {
			logger.debug("actionPerformed(ActionEvent) - start"); //$NON-NLS-1$
		}

		if (e.getActionCommand().equals("开始复制")) {
			Object[] values = jlist.getSelectedValues();
			try {
				int number = values.length;
				if (number > 0) {

					TCComponentFolder model_root_folder = (TCComponentFolder) jlist.getSelectedValue();
					System.out.println("model_root_folder" + model_root_folder);

					tctypeservice = session.getTypeService();
					if (logger.isInfoEnabled()) {
						logger.info("actionPerformed(ActionEvent) - TCTypeService tctypeservice=" + tctypeservice); //$NON-NLS-1$
					}

					// 开始创建folder
					System.out.println("开始创建项目目录文件夹");
					// createFolder(model_root_folder, this.selectedFolder);
					AIFComponentContext aif[] = model_root_folder.getChildren();

					for (int i = 0; i < aif.length; i++) {
						InterfaceAIFComponent inter = aif[i].getComponent();

						if (inter instanceof TCComponentFolder) {

							TCComponentFolder srcsubf = (TCComponentFolder) inter;
							createFolder(srcsubf, this.selectedFolder, "");
						}
					}
				} else {
					MessageBox.post("没有选择任何模板", "提示", 2);

					if (logger.isDebugEnabled()) {
						logger.debug("actionPerformed(ActionEvent) - end"); //$NON-NLS-1$
					}
					return;
				}
			} catch (Exception e1) {
				logger.error("actionPerformed(ActionEvent)", e1); //$NON-NLS-1$

				e1.printStackTrace();
			}

			dispose();
		} else if (e.getActionCommand().equals("取消")) {

			dispose();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("actionPerformed(ActionEvent) - end"); //$NON-NLS-1$
		}
	}

	/*
	 * 检查选中的输入对象是否符合条件
	 */
	private int checkTargets() {
		if (logger.isDebugEnabled()) {
			logger.debug("checkTargets() - start"); //$NON-NLS-1$
		}

		int flag = 0;
		AIFComponentContext aifcomponentcontext[] = app.getTargetContexts();
		if (aifcomponentcontext != null && aifcomponentcontext.length >= 0) {
			tcTargets = new TCComponent[aifcomponentcontext.length];
			for (int i = 0; i < aifcomponentcontext.length; i++) {
				tcTargets[i] = (TCComponent) aifcomponentcontext[i].getComponent();
				System.out.println("tcTargets[i]===" + tcTargets[i]);
			}
			selectedFolder = (TCComponentFolder) tcTargets[0];
			try {
				if (!checkAccessPrivilige(session.getUser(), tcTargets[0], "WRITE")) {
					flag = 2;
				}
			} catch (TCException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			flag = 3;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("checkTargets() - end"); //$NON-NLS-1$
		}
		return flag;
	}

	/**
	 * 检测用户针对指定对象是否有某项权限
	 * 
	 * @param user
	 *            用户
	 * @param comp
	 *            对象
	 * @param accessName
	 *            权限名称
	 * @return 是否有权限
	 * @throws TCException
	 */
	private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException {
		if (logger.isDebugEnabled()) {
			logger.debug("checkAccessPrivilige(TCComponentUser, TCComponent, String) - start"); //$NON-NLS-1$
		}

		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser user=" + user); //$NON-NLS-1$
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser comp=" + comp); //$NON-NLS-1$
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser accessName=" + accessName); //$NON-NLS-1$
		}
		TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService();
		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCAccessControlService accessService=" + accessService); //$NON-NLS-1$
		}
		boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName);
		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - boolean returnboolean=" + returnboolean); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("checkAccessPrivilige(TCComponentUser, TCComponent, String) - end"); //$NON-NLS-1$
		}
		return returnboolean;
	}

	// 查找模板
	public TCComponentFolder[] getTemplateFolder() {
		TCComponentFolder[] result = null;
		try {
			String str_key = "Type";
			String str_value = "YSR8_SDFolder";
			String str_key2 = "OwningUser";
			String str_value2 = "infodba";

			TCTextService textService = session.getTextService();
			TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			TCComponentQuery query = (TCComponentQuery) querytype.find("常规...");
			querytype.clearCache();
			String as[] = new String[2];
			String as1[] = new String[2];
			as[0] = textService.getTextValue(str_key);
			as1[0] = str_value;
			as[1] = textService.getTextValue(str_key2);
			as1[1] = str_value2;
			query.clearCache();
			System.out.println("query " + query);
			TCComponentContextList list = query.getExecuteResultsList(as, as1);

			if (list != null) {
				int count = list.getListCount();
				System.out.println(" folder coutn " + count);
				result = new TCComponentFolder[count];
				for (int i = 0; i < count; i++) {
					result[i] = (TCComponentFolder) list.get(i).getComponent();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/*
	 * 根据模板递归循环创建相同的目录结构
	 */
	public void createFolder(TCComponentFolder srcrootf, TCComponentFolder targetrootf, String foldername) {

		try {
			String subf_name = "";
			String object_desc = "";
			if (foldername.equals("")) {
				subf_name = srcrootf.getProperty("object_name");
				object_desc = srcrootf.getProperty("object_desc");
			} else {
				subf_name = foldername;
				object_desc = selectedFolder.getProperty("object_desc");
			}
			// System.out.println("subf_name "+subf_name);
			TCComponentFolderType foldertype = (TCComponentFolderType) tctypeservice.getTypeComponent("Folder");
			TCComponentFolder subfolder = foldertype.create(subf_name, "", "Folder");
			subfolder.setProperty("object_desc", object_desc);
			targetrootf.add("contents", subfolder);

			AIFComponentContext aif[] = srcrootf.getChildren();

			for (int i = 0; i < aif.length; i++) {
				InterfaceAIFComponent inter = aif[i].getComponent();

				if (inter instanceof TCComponentFolder) {

					TCComponentFolder srcsubf = (TCComponentFolder) inter;
					createFolder(srcsubf, subfolder, "");
				}
			}
		} catch (TCException e) {
			logger.error("createFolder(TCComponentFolder, TCComponentFolder)", e); //$NON-NLS-1$
			e.printStackTrace();
		}

	}
}
