package nc.ui.pub.filesystem;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.event.MouseInputAdapter;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pub.filesystem.FileSystemUtil;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.funcnode.ui.action.SeparatorAction;
import nc.pub.filesystem.newui.FileContentPanel;
import nc.pub.filesystem.newui.ThFileContentPanel;
import nc.sfbase.client.ClientToolKit;
import nc.ui.ml.NCLangRes;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIButton;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.beans.UITree;
import nc.ui.uif2.editor.BillForm;
import nc.vo.pub.BusinessException;
import nc.vo.pub.filesystem.ItemObj;
import nc.vo.pub.filesystem.NCFileNode;

import com.sun.java.swing.plaf.windows.WindowsToolBarSeparatorUI;



public class ThFileManageUI extends JPanel {
	private String rootDirStr = null;	
	public ThFileManageUI() {
		super();
		setLayout(new BorderLayout());
		filepanel = new ThFileContentPanel(rootDirStr,null);
		add(filepanel, BorderLayout.CENTER);
	}
	private ThFileContentPanel filepanel ;
	public ThFileManageUI(String rootDirStr,BillForm editor) {
		super();
		setLayout(new BorderLayout());
		filepanel = new ThFileContentPanel(rootDirStr,editor);	
		setPreferredSize(new Dimension(800,700));
//		add(filepanel);
		add(filepanel,BorderLayout.CENTER);

	}
	
	/*
	 * 
	 *TODO 下边的方法除了设置按钮的方法基本都废弃，
	 *考虑到方法很多是公开的，
	 *TODO 可能会有调用，不敢删除
	 */
	
	
	/**
	 * 
	 */
	private class  DefaultFileNameRender implements IRootNodeNameRender{

		public String getDisplayName(String name) {
			return name;
		}
		
	}
	private static final long serialVersionUID = -2269771697062506234L;
	
	private class CTreeUI extends BasicTreeUI {
		public CTreeUI() {
			super();
		}

		@Override
		protected void completeEditing(boolean messageStop, boolean messageCancel, boolean messageTree) {
			super.completeEditing(messageStop, messageCancel, true);
		}

		@Override
		protected boolean startEditing(TreePath path, MouseEvent event) {
			if (path != null) {
			Object obj = path.getLastPathComponent();
			if (obj.equals(rootNode)) {
				// MessageDialog.showErrorDlg(tree, "错误", "不能对根节点重命名");
				return false;
			}
		}
			return super.startEditing(path, event);
		}

//		@Override
//		public void startEditingAtPath(JTree tree, TreePath path) {
//			if (path != null) {
//				Object obj = path.getLastPathComponent();
//				if (obj.equals(rootNode)) {
//					// MessageDialog.showErrorDlg(tree, "错误", "不能对根节点重命名");
//					return;
//				}
//			}
//			super.startEditingAtPath(tree, path);
//		}

	}

	private class CTreeCellRender extends DefaultTreeCellRenderer {
		private static final long serialVersionUID = -8004831268687492791L;

		@Override
		public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
			Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
			if (value instanceof NCFileNode) {
				NCFileNode node = (NCFileNode) value;
				JLabel lbl = (JLabel) comp;
				Icon icon = null;
				if (!node.getAllowsChildren()) {
					String name = node.getName();
					int index = name.lastIndexOf(".");
					if (index != -1) {
						String ext = name.substring(index + 1).toLowerCase();
						icon = ClientToolKit.loadImageIcon("images/filesystem/" + ext + ".png");
					} else {
						icon = ClientToolKit.loadImageIcon("images/filesystem/default.png");
					}
				} else if (node.equals(rootNode)) {
					icon = ClientToolKit.loadImageIcon("images/filesystem/root.png");
				}
				if (icon != null) {
					lbl.setIcon(icon);
				}
				if(node.equals(rootNode)){
					String displayName = getRootNodeNameRender().getDisplayName(node.getName());
					lbl.setText(displayName);
				}
				
			}
			return comp;
		}

	}

	private class CTreeCellEditor extends DefaultTreeCellEditor {
		private NCFileNode node = null;

		public CTreeCellEditor(JTree tree) {
			super(tree, treeCellRender);
		}

		@Override
		public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
			if (value instanceof NCFileNode) {
				node = (NCFileNode) value;
			}
			return super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
		}
		@Override
		public Object getCellEditorValue() {
			Object o = super.getCellEditorValue();
			if (o instanceof String && node != null) {
				String newValue = ((String) o).trim();
				String oldValue = node.getName();
				String oldPath = node.getFullPath();
				node.setUserObject(newValue);
				String newPath = node.getFullPath();
				boolean b = false;
				try {
					if (newValue.indexOf("/") != -1 || newValue.indexOf("\\") != -1) {
						MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000001")/*文件名中不能包含\\或/符号*/);
						return oldValue;
					}
					//如果去掉前后空格长度为0,返回原来值,提示文件名不能空
					if(newValue.trim().length()==0)
					{
						//MessageDialog.showErrorDlg(FileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, "文件名不能为空");
						return oldValue;
					}
					if (!oldPath.equals(newPath)) {
						IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
						b = service.rename(oldPath, newPath);
						if (!b) {
							MessageDialog.showHintDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000002")/*提示*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000003")/*文件名重复*/);
						}
					}
				} catch (BusinessException e) {
					Logger.error(e);
				}
				if (b) {
					return newValue;
				} else {
					return oldValue;
				}
			}
			return o;
		}

		@Override
		protected void determineOffset(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
			super.determineOffset(tree, value, isSelected, expanded, leaf, row);
			if (renderer != null) {
				editingIcon = ((JLabel) renderer.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, false)).getIcon();
			}
		}

	}

	private class CreateFolderAction extends AbstractAction {
		private static final long serialVersionUID = 8586968483409225741L;

		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath path = getFileManageTree().getSelectionPath();
			if (path == null) {
				path = new TreePath(rootNode.getPath());
			}
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
			String pPath = "";
			if (node instanceof NCFileNode) {
				pPath = ((NCFileNode) node).getFullPath();
			}
			if (!node.getAllowsChildren()) {
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000004")/*不能在文件下面新建文件夹*/);
				return;
			}
			String str = (String) MessageDialog.showInputDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000005")/*新建文件夹*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000006")/*请输入文件夹名称*/, "newfolder");
			if (str != null && str.trim().length() > 0) {
				try {
					if(CheckTheSameFileName(node,str))
					{
						return;
					}
					IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
					NCFileNode newNode = service.createNewFileNode(pPath, str, WorkbenchEnvironment.getInstance().getLoginUser().getCuserid());
					DefaultTreeModel model = getFileManageTreeModel();
					model.insertNodeInto(newNode, node, node.getChildCount());
					model.nodeStructureChanged(node);
					TreePath newPath = new TreePath(getTreePath(newNode));
					getFileManageTree().setSelectionPath(newPath);
					getFileManageTree().expandPath(newPath);
				} catch (Exception ex) {
					Logger.error(ex.getMessage(), ex);
					MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
				}
			}
		}
	}

	private class DeleteNCFileNodeAction extends AbstractAction {
		private static final long serialVersionUID = 480062171698567464L;

		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath[] paths = getFileManageTree().getSelectionPaths();
			if (paths == null || paths.length == 0)
				return;
			List<String> nodePathsList = new ArrayList<String>();
			List<DefaultMutableTreeNode> nodeList = new ArrayList<DefaultMutableTreeNode>();
			for (int i = 0; i < paths.length; i++) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
				if (node.equals(rootNode)) {
					continue;
				}
				if (node instanceof NCFileNode) {
					String nodePath = ((NCFileNode) node).getFullPath();
					nodePathsList.add(nodePath);
					nodeList.add(node);
				}

			}
			if (nodePathsList.size() > 0) {
				try {
					IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
					StringBuilder sb = new StringBuilder(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000019")+"\r\n");
					for (int i = 0; i < nodeList.size(); i++) {
						TreeNode[] nodes = getTreePath(nodeList.get(i));
						sb.append(convertTreePathToString(nodes)).append("\r\n");
					}
					if (MessageDialog.showOkCancelDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000007")/*删除确认框*/, sb.toString()) == MessageDialog.ID_OK) {
						service.deleteNCFileNodes(nodePathsList.toArray(new String[0]));
						DefaultTreeModel model = getFileManageTreeModel();
						for (int i = 0; i < nodeList.size(); i++) {
							DefaultMutableTreeNode tempNode = nodeList.get(i);
							TreeNode parent = tempNode.getParent();
							model.removeNodeFromParent(tempNode);
							if (parent != null) {
								model.nodeStructureChanged(parent);
							}
						}
						// model.removeNodeFromParent(node);
						// model.nodeStructureChanged(parent);
					}
				} catch (BusinessException ex) {
					Logger.error(ex.getMessage(), ex);
				}
			}

		}

	}
	private static Window getTopWindow(Container parentContainer) {
		Container parent = parentContainer;
		while (parent != null && !(parent instanceof Dialog || parent instanceof Frame)) {
			parent = parent.getParent();
		}
		if(parent == null){
			parent = JOptionPane.getFrameForComponent(parentContainer);
		}
		return (Window)parent;
	}
	private class UploadFormSCanerAction extends AbstractAction{
		@Override
		public void actionPerformed(ActionEvent e) {
			try{

				ScanUIDialog f = new ScanUIDialog(getTopWindow(ThFileManageUI.this.getTopLevelAncestor()) , getFileManageTree(),rootNode);
				Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
//				Insets insets =Toolkit.getDefaultToolkit().getScreenInsets(window.getGraphicsConfiguration());
				f.setLocation(new Point(((int)(dim.width-700)/2),(int)(dim.height-600)/2));
				f.setModal(true);
				f.show(true);
//				Display display = Display.getDefault();
//
//				TestOcx thisClass = new TestOcx(getFileManageTree(),rootNode);
//
//				thisClass.createSShell();
//				thisClass.createActivex();
//				thisClass.createControl();
//				thisClass.sShell.open();
//
//				while (!thisClass.sShell.isDisposed())
//				{
//				   if (!display.readAndDispatch())
//				     display.sleep();
//				}
			}catch(Exception ex){
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000001")/*连接失败*/, NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000002")/*连接高拍仪失败!*/);
			}
		}
	}
	
	private class UploadFileAction extends AbstractAction {
		private static final long serialVersionUID = 2336027794934776723L;

		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath path = getFileManageTree().getSelectionPath();
			if (path == null) {
				path = new TreePath(rootNode.getPath());
			}
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
//			if (!node.getAllowsChildren()) {
//				MessageDialog.showErrorDlg(FileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000008")/*不能在文件下面新建文件*/);
//				return;
//			}
			//树的点击点  取所在文件夹(如果点击的是文件,则取上一层)
			node = getClosedValidateNode(node);
			
			JFileChooser chooser = new JFileChooser();
			if (chooser.showOpenDialog(ThFileManageUI.this) == JFileChooser.APPROVE_OPTION) {
				String pPath = "";
				if (node instanceof NCFileNode) {
					pPath = ((NCFileNode) node).getFullPath();
				}
				File file = chooser.getSelectedFile();
				String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter().getDataSourceName();
				String fileName = file.getName();
				String creator = WorkbenchEnvironment.getInstance().getLoginUser().getCuserid();
				FileInputStream input = null;
				
				//校验是否同名
				if(CheckTheSameFileName(node, fileName)){
					return ;
				}
					
					
				try {
					input = new FileInputStream(file);
					NCFileNode newNode = FileManageServletClient.uploadFile(dsName, pPath, fileName, input, creator, file.length());
					if (newNode != null) {
						DefaultTreeModel model = getFileManageTreeModel();
						model.insertNodeInto(newNode, node, node.getChildCount());
						model.nodeStructureChanged(node);
						// getFileManageTree().expandPath(path);
						TreePath newPath = new TreePath(getTreePath(newNode));
						getFileManageTree().setSelectionPath(newPath);
						getFileManageTree().expandPath(newPath);
					}
				} catch (Exception ex) {
					Logger.error(ex.getMessage(), ex);
					MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
				} finally {
					try {
						if (input != null) {
							input.close();
						}
					} catch (Exception e2) {
					}
				}
			}
		}
	}
	
	private DefaultMutableTreeNode getClosedValidateNode(DefaultMutableTreeNode node){
		if(node.getAllowsChildren())
			return node;
		DefaultMutableTreeNode parentnode =(DefaultMutableTreeNode) node.getParent();
		return getClosedValidateNode(parentnode);
	}
	
	private class RefrenceFileAction extends AbstractAction {

		private static final long serialVersionUID = 3497920350046729694L;

		@Override
		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath path = getFileManageTree().getSelectionPath();
			if (path == null) {
				path = new TreePath(rootNode.getPath());
			}
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
//			if (!node.getAllowsChildren()) {
//				MessageDialog.showErrorDlg(FileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000008")/*不能在文件下面新建文件*/);
//				return;
//			}
			node = getClosedValidateNode(node);
			UIRefPane fileref = new UIRefPane("文档");/*-=notranslate=-*/  
			fileref.setMultiSelectedEnabled(false);
			fileref.getRefModel().setUseDataPower(false);
			
			fileref.showModel();
			String pk_doc = fileref.getRefPK();
			if(pk_doc==null)
				return;
			String pPath = "";
			if (node instanceof NCFileNode) {
				pPath = ((NCFileNode) node).getFullPath();
			}
			String creator = WorkbenchEnvironment.getInstance().getLoginUser().getCuserid();
			try{
				IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
				NCFileNode newNode = service.createRefFileNode(pPath, creator, pk_doc);
				if (newNode != null) {
					DefaultTreeModel model = getFileManageTreeModel();
					model.insertNodeInto(newNode, node, node.getChildCount());
					model.nodeStructureChanged(node);
					// getFileManageTree().expandPath(path);
					TreePath newPath = new TreePath(getTreePath(newNode));
					getFileManageTree().setSelectionPath(newPath);
					getFileManageTree().expandPath(newPath);
				}
			} catch (Exception ex) {
				Logger.error(ex.getMessage(), ex);
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
			}
			
		}
		
	}

	private class DownLoadFileAction extends AbstractAction {
		private static final long serialVersionUID = -2148614538083746599L;

		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath treePath = getFileManageTree().getSelectionPath();
			if (treePath == null) {
				return;
			}
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
			if (node.getAllowsChildren()) {
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000009")/*只能下载文件*/);
				return;
			}
			if (node instanceof NCFileNode) {
				String path = ((NCFileNode) node).getFullPath();
				String name=((NCFileNode) node).getName();
				String defaultType= getFileType(name);
				JFileChooser chooser = new JFileChooser();
				// 设置默认选中文件
				chooser.setSelectedFile(new File(name));
				
				if (chooser.showSaveDialog(ThFileManageUI.this) == JFileChooser.APPROVE_OPTION) {				
					File file = chooser.getSelectedFile();					
					// 如果选中文件无后缀名,添加默认后缀名
					if (!file.getName().contains(".") && defaultType != null) {
						file = new File(file.getParent(), file.getName()
								+ defaultType);
					}
					String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter().getDataSourceName();
					FileOutputStream fos = null;
					try {
						fos = new FileOutputStream(file);
						FileManageServletClient.downloadFile(dsName, path, fos);
					} catch (Exception ex) {
						Logger.error(ex.getMessage(), ex);
						MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
					} finally {
						try {
							if (fos != null) {
								fos.close();
							}
						} catch (Exception e2) {
						}
					}
				}
				
			}
			

		}
		/**
		 * @param name
		 * @return 返回文件后缀名，包含"."
		 */
		private String getFileType(String name) {
			String type=null;
			if(name!=null&&name.contains(".")){
				type=name.substring(name.lastIndexOf("."), name.length());
			}
			return type;
		}


	}

	private class RefreshAction extends AbstractAction {
		private static final long serialVersionUID = -7401161189389362236L;

		public void actionPerformed(ActionEvent e) {
			constructTree();
		}

	}

	private class ShowFileInWebAction extends AbstractAction {
		private static final long serialVersionUID = -5973794844705935313L;

		public void actionPerformed(ActionEvent e) {
			//测试进入action次数
			Logger.error("--------------------------zhoujjtestinmethod测试进入action次数---------------------------------------");
			
			if (rootNode == null) {
				return;
			}
			TreePath treePath = getFileManageTree().getSelectionPath();
			if (treePath == null) {
				return;
			}
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
			if (node.getAllowsChildren()) {
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000010")/*请选择一个文件*/);
				return;
			}
			String path = "";
			if (node instanceof NCFileNode) {
				path = ((NCFileNode) node).getFullPath();
			}
			String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter().getDataSourceName();
			try {
				FileManageServletClient.showFileInWeb(dsName, path,((NCFileNode)node).getTime());
			} catch (Exception e1) {
				Logger.error(e1);
			}

		}
	}

	private class RenameTreeNodeAction extends AbstractAction {
		private static final long serialVersionUID = -5973794844705935313L;

		public void actionPerformed(ActionEvent e) {
			if (rootNode == null) {
				return;
			}
			TreePath treePath = getFileManageTree().getSelectionPath();
			if (treePath == null) {
				return;
			}
			Object obj = treePath.getLastPathComponent();
			if (obj.equals(rootNode)) {
				MessageDialog.showErrorDlg(getFileManageTree(), NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000011")/*不能对根节点重命名*/);
				return;
			}

			getFileManageTree().getUI().startEditingAtPath(getFileManageTree(), treePath);

		}
	}

	private class CMouseHandler extends MouseInputAdapter {
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
				doDoubleClicked(e);
			}
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			if (e.isPopupTrigger()) {
				showPopupMenu(e);
			}
		}

	}

	

	private NCFileNode rootNode = null;

	private UITree fileManageTree = null;

	private JToolBar toolBar = null;

	private JPopupMenu popMenu = null;

	private JScrollPane scrollPane = null;

	private DefaultTreeModel fileManageTreeModel = null;

	private CMouseHandler mouseHandler = new CMouseHandler();

	private CreateFolderAction createFolderAction = null;
	private UIButton btncreateFolder = null;
	public UIButton getBtncreateFolder(){
		if(btncreateFolder == null){
			btncreateFolder = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000005")/*新建文件夹*/);
			btncreateFolder.addActionListener(new CreateFolderAction());
		}
		return btncreateFolder;
	}
	
	private DeleteNCFileNodeAction deleteNCFileNodeAction = null;
	private UIButton btndeleteNCFileNode = null;
	public UIButton getBtnDeleteNCFileNode(){
		if(btndeleteNCFileNode == null){
			btndeleteNCFileNode = new UIButton( NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000012")/*删除*/);
			btndeleteNCFileNode.addActionListener(new DeleteNCFileNodeAction());
		}
		return btndeleteNCFileNode;
	}
	//上传文件的popup
	private JPopupMenu uploadPopAction;
	public JPopupMenu getUploadPopAction(){
		if(uploadPopAction==null){
			uploadPopAction = new JPopupMenu();
			uploadPopAction.add(getUploadFileAction());
			uploadPopAction.add(getUpscan());
//			uploadPopAction.add(getRefrenceFileAction());			
			
		}
		return uploadPopAction;
	}
	//本地文件上传 action
	private UploadFileAction uploadFileAction = null;
	public final UploadFileAction getUploadFileAction() {
		if (uploadFileAction == null) {
			uploadFileAction = new UploadFileAction();
			uploadFileAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000013")/*上传文件*/);
			uploadFileAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000013")/*上传文件*/);
			uploadFileAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/upload.png"));
		}
		return uploadFileAction;
	}

	
	//高拍仪上传action
	private UploadFormSCanerAction upscan;
	public final UploadFormSCanerAction getUpscan(){
		if(upscan==null){
			upscan= new UploadFormSCanerAction();
			upscan.putValue(AbstractAction.NAME,NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000003")/*抓拍上传*/);
			upscan.putValue(Action.SHORT_DESCRIPTION,NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000003")/*抓拍上传*/);
			upscan.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/upload.png"));
		}
		return upscan;
	}

	//弹出三个上传popup的action
	private   UploadPopAction upAction ;
	private class UploadPopAction extends AbstractAction{
		@Override
		public void actionPerformed(ActionEvent e) {			
			getUploadPopAction().show(getToolBar().getComponent(2), 0, getToolBar().getComponent(2).getHeight()+10);
			
		}
	}
	//弹出上传pop的 按钮 toolbar button
	private UIButton btnup = null;
	public UIButton getBtnupscan(){
		if(btnup==null){
			btnup = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000013")/*上传文件*/);
			btnup.addActionListener(new UploadPopAction());
			
		}
		return btnup;
	}
	public UploadPopAction getUpButton(){
		if(upAction == null){
			upAction = new UploadPopAction();			
			upAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000013")/*上传文件*/);
			upAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000013")/*上传文件*/);
			upAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/upload.png"));
		}
			
		return upAction;
	}
		
	//引用文档 action
	private RefrenceFileAction refrenceFileAction = null;
	//
	
	//下载action
	private DownLoadFileAction downLoadFileAction = null;
	//下载button
	private UIButton btndownLoadFile = null;
	public UIButton getBtndownLoadFile(){
		if(btndownLoadFile==null){
			btndownLoadFile = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000014")/*下载文件*/);
			btndownLoadFile.addActionListener(new DownLoadFileAction());
			
		}
		return btndownLoadFile;
	}
	//刷新 action
	private RefreshAction refreshAction = null;
	//刷新button
	private UIButton btnrefresh = null;
	public UIButton getBtnrefresh(){
		if(btnrefresh==null){
			btnrefresh = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000015")/*刷新*/);
			btnrefresh.addActionListener(new RefreshAction());
			
		}
		return btnrefresh;
	}
	//预览 action
	private ShowFileInWebAction showFileInWebAction = null;
	//预览button
	private UIButton btnshowFileInWeb = null;
	public UIButton getBtnshowFileInWeb(){
		if(btnshowFileInWeb==null){
			btnshowFileInWeb = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000016")/*阅览*/);
			btnshowFileInWeb.addActionListener(new ShowFileInWebAction());
			
		}
		return btnshowFileInWeb;
	}
	//重命名 action
	private RenameTreeNodeAction renameTreeNodeAction = null;
	//重命名 button
	private UIButton btnrenameTreeNode = null;
	public UIButton getBtnrenameTreeNode(){
		if(btnrenameTreeNode==null){
			btnrenameTreeNode = new UIButton(NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000017")/*重命名*/);
			btnrenameTreeNode.addActionListener(new RenameTreeNodeAction());
			
		}
		return btnrenameTreeNode;
	}
	private CTreeCellRender treeCellRender = new CTreeCellRender();
	private IRootNodeNameRender rootNodeNameRender = null;
	

	



	public void setRootDirStr(String dirStr) {
		if (dirStr != null) {
			rootDirStr = FileSystemUtil.validatePathString(dirStr);
			// rootDirStr = dirStr.replace('\\', '/');
			// if(rootDirStr.endsWith("/")){
			// rootDirStr = rootDirStr.substring(0, rootDirStr.length()-1);
			// }
		}
		constructTree();
	}

	public void showPopupMenu(MouseEvent e) {
		ArrayList<TreePath> list = new ArrayList<TreePath>();
		TreePath tp = getFileManageTree().getPathForLocation(e.getX(), e.getY());
		if (tp != null) {
			list.add(tp);
		}
		if (e.isControlDown()) {
			TreePath[] tps = getFileManageTree().getSelectionPaths();
			if (tps != null && tps.length > 0) {
				list.addAll(Arrays.asList(tps));
			}
		}
		getFileManageTree().setSelectionPaths(list.toArray(new TreePath[0]));

		getPopMenu().show(getFileManageTree(), e.getX(), e.getY());

	}

	private void doDoubleClicked(MouseEvent e) {
		TreePath selPath = getFileManageTree().getPathForLocation(e.getX(), e.getY());// getSelectionPath();
		if (selPath != null) {
			Object obj = selPath.getLastPathComponent();
			if (obj instanceof NCFileNode) {
				NCFileNode node = (NCFileNode) obj;
				if (!node.isFolder()) {
					getShowFileInWebAction().actionPerformed(null);
				}
			}
		}

	}

	private void initialize() {
		setLayout(new BorderLayout());
		this.scrollPane = new JScrollPane(getFileManageTree());
		this.scrollPane.setColumnHeaderView(getToolBar());
		add(this.scrollPane, BorderLayout.CENTER);
		setTreeEditable(true);
		constructTree();
	}

	private void constructTree() {
		try {
			if (rootDirStr != null) {
				IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
				NCFileNode node = service.getNCFileNodeTreeAndCreateAsNeed(rootDirStr, WorkbenchEnvironment.getInstance().getLoginUser().getCuserid());
				rootNode = findNode(node, rootDirStr);
			} else {
				rootNode = null;
			}
			getFileManageTreeModel().setRoot(rootNode);
			getFileManageTreeModel().nodeStructureChanged(rootNode);

		} catch (BusinessException e) {
			Logger.error(e);
		}

	}

	@SuppressWarnings("unchecked")
	static NCFileNode findNode(NCFileNode node, String path) {
		Enumeration<NCFileNode> enumer = node.breadthFirstEnumeration();
		NCFileNode retrNode = null;
		while (enumer.hasMoreElements()) {
			NCFileNode tempNode = (NCFileNode) enumer.nextElement();
			if (tempNode.getFullPath().equals(path)) {
				retrNode = tempNode;
				break;
			}
		}
		return retrNode;
	}

	private DefaultTreeModel getFileManageTreeModel() {
		if (fileManageTreeModel == null) {
			fileManageTreeModel = new DefaultTreeModel(null);
			fileManageTreeModel.setAsksAllowsChildren(true);
		}
		return fileManageTreeModel;
	}

	private UITree getFileManageTree() {
		if (fileManageTree == null) {
			fileManageTree = new UITree(getFileManageTreeModel());
			fileManageTree.addMouseListener(mouseHandler);
			fileManageTree.setCellRenderer(treeCellRender);
			fileManageTree.setUI(new CTreeUI());
			CTreeCellEditor treeCellEditor = new CTreeCellEditor(fileManageTree);
			fileManageTree.setCellEditor(treeCellEditor);

		}
		return fileManageTree;
	}

	private TreeNode[] getTreePath(TreeNode node) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		TreeNode temp = node;
		while (temp != null && !temp.equals(rootNode)) {
			list.add(0, temp);
			temp = temp.getParent();
		}
		list.add(0, rootNode);
		return list.toArray(new TreeNode[0]);
	}

	private String convertTreePathToString(TreeNode[] nodes) {
		StringBuilder sb = new StringBuilder();
		int count = nodes == null ? 0 : nodes.length;
		int index = 0;
		if (!getFileManageTree().isRootVisible())
			index = 1;
		for (int i = index; i < count; i++) {
			if (sb.length() > 0)
				sb.append("/");
			sb.append(nodes[i]);
		}
		return sb.toString();
	}

	private JToolBar getToolBar() {
		if (toolBar == null) {
			toolBar = new JToolBar() {
				private static final long serialVersionUID = 3388557700603254117L;

				@Override
				protected JButton createActionComponent(Action a) {
					JButton btn = new ToolBarButton(a);
					return btn;
				}

				@Override
				public void addSeparator(Dimension size) {
					JToolBar.Separator s = new JToolBar.Separator(size);
					s.setUI(new WindowsToolBarSeparatorUI());
					add(s);
				}

			};
			toolBar.add(getBtncreateFolder());
			toolBar.add(getBtnDeleteNCFileNode());
			toolBar.add(new SeparatorAction());

			toolBar.add(getBtnupscan());
			toolBar.add(getBtndownLoadFile());

			toolBar.add(new SeparatorAction());
			toolBar.add(getBtnrefresh());
			toolBar.add(getBtnshowFileInWeb());
			toolBar.add(getBtnrenameTreeNode());			
		}
		return toolBar;
	}

	public final CreateFolderAction getCreatFolderAction() {
		if (createFolderAction == null) {
			createFolderAction = new CreateFolderAction();
			createFolderAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000005")/*新建文件夹*/);
			createFolderAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000005")/*新建文件夹*/);
			createFolderAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/newfolder.png"));

		}
		return createFolderAction;
	}

	public final DeleteNCFileNodeAction getDeleteNCFileNodeAction() {
		if (deleteNCFileNodeAction == null) {
			deleteNCFileNodeAction = new DeleteNCFileNodeAction();
			deleteNCFileNodeAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000012")/*删除*/);
			deleteNCFileNodeAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000012")/*删除*/);
			deleteNCFileNodeAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/delete.png"));

		}
		return deleteNCFileNodeAction;
	}

	
	
	public final RefrenceFileAction getRefrenceFileAction() {
		if (refrenceFileAction == null) {
			refrenceFileAction = new RefrenceFileAction();
			refrenceFileAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000018")/*"引用文档"*/);
			refrenceFileAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000018")/*"引用文档"*/);
			refrenceFileAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/iconlib/8-1.gif"));
		}
		return refrenceFileAction;
	}

	public final DownLoadFileAction getDownLoadFileAction() {
		if (downLoadFileAction == null) {
			downLoadFileAction = new DownLoadFileAction();
			downLoadFileAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000014")/*下载文件*/);
			downLoadFileAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000014")/*下载文件*/);
			downLoadFileAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/download.png"));
		}
		return downLoadFileAction;
	}
	

	public final RefreshAction getRefreshAction() {
		if (refreshAction == null) {
			refreshAction = new RefreshAction();
			refreshAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000015")/*刷新*/);
			refreshAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000015")/*刷新*/);
			refreshAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/refresh.png"));

		}
		return refreshAction;
	}

	public final ShowFileInWebAction getShowFileInWebAction() {
		if (showFileInWebAction == null) {
			showFileInWebAction = new ShowFileInWebAction();
			showFileInWebAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000016")/*阅览*/);
			showFileInWebAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000016")/*阅览*/);
			showFileInWebAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/view.png"));
		}
		return showFileInWebAction;
	}

	public final RenameTreeNodeAction getRenameTreeNodeAction() {
		if (renameTreeNodeAction == null) {
			renameTreeNodeAction = new RenameTreeNodeAction();
			renameTreeNodeAction.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000017")/*重命名*/);
			renameTreeNodeAction.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000017")/*重命名*/);
			renameTreeNodeAction.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/rename.png"));
			renameTreeNodeAction.setEnabled(getFileManageTree().isEditable());
		}
		return renameTreeNodeAction;
	}

	private JPopupMenu getPopMenu() {
		if (popMenu == null) {
			popMenu = new JPopupMenu();
			popMenu.add(getCreatFolderAction());
			popMenu.add(getDeleteNCFileNodeAction());
			popMenu.addSeparator();
			popMenu.add(getUploadFileAction());
			popMenu.add(getUpscan());
			popMenu.add(getDownLoadFileAction());
			popMenu.addSeparator();
			popMenu.add(getRefreshAction());
			popMenu.add(getShowFileInWebAction());
			popMenu.add(getRenameTreeNodeAction());
		}
		return popMenu;
	}
	public void showcombox(ArrayList<ItemObj> list){
		filepanel.showcombox(list);
	}
	public void setCreateNewFolderEnable(boolean enable) {
//		getCreatFolderAction().setEnabled(enable);
		filepanel.setCreateNewFolderEnable(enable);
	}

	public void setDeleteNodeEnable(boolean enable) {
//		getDeleteNCFileNodeAction().setEnabled(enable);
		filepanel.setDeleteNodeEnable(enable);
	}

	public void setUploadFileEnable(boolean enable) {
//		getUploadFileAction().setEnabled(enable);
		filepanel.setUploadFileEnable(enable);
	}

	public void setDownloadFileEnable(boolean enable) {
//		getDownLoadFileAction().setEnabled(enable);
		filepanel.setDownloadFileEnable(enable);
	}
	
	public void setRefrenceFileEnable(boolean enable) {
//		getRefrenceFileAction().setEnabled(enable);
	}

	public void setRefreshEnable(boolean enable) {
//		getRefreshAction().setEnabled(enable);
	}

	public void setShowFileEnable(boolean enable) {
//		getShowFileInWebAction().setEnabled(enable);
		filepanel.setShowFileEnable(enable);
	}
	
	public void setRenameNodeEnable(boolean enable) {
//		getRenameTreeNodeAction().setEnabled(enable);
		filepanel.setRenameNodeEnable(enable);
	}

	public void setTreeRootVisible(boolean visible) {
//		getFileManageTree().setRootVisible(visible);
	}

	public void setToolBarVisible(boolean visible) {
//		getToolBar().setVisible(visible);
//		if (visible) {
//			scrollPane.setColumnHeaderView(getToolBar());
//		} else {
//			scrollPane.setColumnHeaderView(null);
//		}
	}

	public void setTreeEditable(boolean editable) {
//		getFileManageTree().setEditable(editable);
//		getRenameTreeNodeAction().setEnabled(editable);
	}

	/**
	 * 
	 * @param parent
	 *            父窗口
	 * @param title
	 *            对话框标题
	 * @param rootPath
	 *            文件管理控件的根目录
	 */
	public static void showInDlg(Container parent, String title, String rootPath) {
		UIDialog dlg = new UIDialog(parent, title);

		dlg.getContentPane().setLayout(new BorderLayout());
//		FileManageUI ui = new FileManageUI(rootPath);
		FileContentPanel ui = new FileContentPanel(rootPath);
		dlg.getContentPane().add(ui, BorderLayout.CENTER);
//		ui.setTreeRootVisible(false);
		dlg.setResizable(true);
		dlg.setSize(600, 400);
		dlg.showModal();

	}

	/**
	 * 
	 * @param parent
	 *            父窗口
	 * @param rootPath
	 *            文件管理控件的根目录
	 * @param subPath
	 *            子目录
	 * @param creator
	 *            创建者
	 */
	public static void uploadFile(Container parent, String rootPath, String subPath, String creator) {
		JFileChooser chooser = new JFileChooser();
		if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
			String pPath = rootPath.replace('\\', '/');
			if (!pPath.endsWith("/"))
				pPath += "/";
			if (subPath != null) {
				pPath += subPath.replace('\\', '/');
			}
			File file = chooser.getSelectedFile();
			String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter().getDataSourceName();
			String fileName = file.getName();
			FileInputStream input = null;
			try {
				input = new FileInputStream(file);
				FileManageServletClient.uploadFile(dsName, pPath, fileName, input, creator, file.length());
			} catch (Exception ex) {
				Logger.error(ex.getMessage(), ex);
				MessageDialog.showErrorDlg(parent, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
			} finally {
				try {
					if (input != null) {
						input.close();
					}
				} catch (Exception e2) {
				}
			}
		}

	}

	public IRootNodeNameRender getRootNodeNameRender() {
		if(rootNodeNameRender == null){
			rootNodeNameRender = new DefaultFileNameRender();
		}
		return rootNodeNameRender;
	}

	public void setRootNodeNameRender(IRootNodeNameRender rootNodeNameRender) {
//		if(rootNodeNameRender == null){
//			rootNodeNameRender = new DefaultFileNameRender();
//		}
//		IRootNodeNameRender old = this.rootNodeNameRender;
//		this.rootNodeNameRender = rootNodeNameRender;
//		if(!this.rootNodeNameRender.equals(old)){
//			getFileManageTree().repaint();
//		}
	}
	/**
	 * 加入前台校验是否在同一节点下存在同名节点 ,有同名返回true
	 * @author zhoujja
	 * @param node 要判断的节点
	 * @param filename 新建节点名字
	 */
	public boolean CheckTheSameFileName(TreeNode node ,String filename)
	{
		//加入 前台校验 ,判断是否存在同名 文件,同名不允许添加
		for(int noden=0; noden<node.getChildCount();noden++)
		{
			TreeNode subnode =node.getChildAt(noden);
			//如果选择node下有同名的node
			if(filename.trim().equalsIgnoreCase(subnode.toString().trim()))
			{
				MessageDialog.showErrorDlg(ThFileManageUI.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000000", null, new String[]{filename})/*文件存在:{0}*/);
				return  true;
			}
		}
		return false;
		
	}
}
