package nc.pub.filesystem.newui;
import nc.vo.arap.utils.StringUtil;
import nc.vo.bd.defdoc.DefdocVO;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.itf.th.IThOcrService;
import nc.itf.uap.IUAPQueryBS;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
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.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.border.AbstractBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import nc.ui.uif2.editor.BillForm;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.logging.Logger;
import nc.bs.pub.filesystem.IFileSystemActionConst;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.bs.pub.filesystem.IQueryFolderTreeNodeService;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.funcnode.ui.ActionButton;
import nc.funcnode.ui.FuncletMenuBar;
import nc.funcnode.ui.action.AbstractNCAction;
import nc.funcnode.ui.action.SeparatorAction;
import nc.pub.filesystem.newui.control.ActionDelegate;
import nc.pub.filesystem.newui.control.MenuAction;
import nc.pub.filesystem.newui.control.MenuButton;
import nc.pub.filesystem.newui.control.SeparatorButton;
import nc.sfbase.client.ClientToolKit;
import nc.ui.ml.NCLangRes;
import nc.ui.pub.beans.ActionsBar;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.ScaleSlider;
import nc.ui.pub.beans.UIComboBox;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UIPanel;
import nc.ui.pub.beans.UISplitPane;
import nc.ui.pub.beans.UITable;
import nc.ui.pub.beans.UITree;
import nc.ui.pub.beans.table.VOTableModel;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pub.filesystem.FileManageServletClient;
import nc.uitheme.ui.ThemeResourceCenter;
import nc.vo.pub.BusinessException;
import nc.vo.pub.ValueObject;
import nc.vo.pub.filesystem.FileTypeConst;
import nc.vo.pub.filesystem.ItemObj;
import nc.vo.pub.filesystem.NCFileNode;
import nc.vo.pub.filesystem.NCFileVO;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.uap.rbac.FuncSubInfo;
import nc.itf.bd.defdoc.IDefdocService;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;

public class ThFileContentPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5442105336247254657L;
	//当前页面的状态
	public int PAGE_STATE=BROWSELISTTABLE_STATE;
	//列表浏览
	public static final int BROWSELISTTABLE_STATE =0;
	//ppt浏览
	public static final int BROWSEPPTICON_STATE =1;
	//单张浏览
	public static final int BROWSESINGLEICON_STATE =2;
	//缩略图浏览
	public static final int BROWSESMALLICON_STATE =3; 
	
	protected BillForm editor_;
	private int colnumbtnpane =5 ;
	private int colnumbtnbrow =1;
	protected String rootDirStr = "dir1/dir2/ewei";
	//
	
	private String funcode ;
	public String getFuncode(){
		return funcode;
	}
	private FuncSubInfo funcsubinfo ;
	
//	IFuncRegisterQueryService.queryFunctionByCode
	public String getRootDirStr() {
		return rootDirStr;
	}

	protected NCFileNode rootNode;
	protected NCFileNode selfoldernode;
	/** 节点上的文件缓存 */
	private HashMap<String, Collection<NCFileVO>> treenodefilecacheMap = new HashMap<String, Collection<NCFileVO>>();

	private class SmallImageFileFilter implements  FileFilter{
		@Override
		public boolean accept(File pathname) {					
			int  index  =pathname.getName().lastIndexOf(".");
			if(pathname.isFile()
					&&index!=-1
					&&pathname.getName().substring(index+1).equalsIgnoreCase("jpg")
					){
				return true;			
			}else{
				return false ;
			}
		}
	}
	/** 节点上的文件缓存 */
	protected HashMap<String, Collection<NCFileVO>> getTreenodefilecacheMap() {
		return treenodefilecacheMap;
	}
	private List<ItemObj> itemlist ;
	public  List<ItemObj> getItemlist(){
		if(itemlist==null){
			itemlist = new ArrayList<ItemObj>();
		}
		return itemlist;
	}
	public void showcombox(ArrayList<ItemObj>list){
		setItemlist(list);
		getComboxbilltype().addItems(list.toArray(new ItemObj[0]));
		getComboxbilltype().setVisible(true);
		getComboxbilltype().validate();
	}
	public void setItemlist( List<ItemObj> list){
		getItemlist().clear();
		getItemlist().addAll(list);
	}
	/** 节点大小缓存 */
	private HashMap<String, Long> treefileszieMap = new HashMap<String, Long>();

//	/** 构造器 */
//	public FileContentPanel(String fcode,String root) {		
//		super();
//		funcode =fcode ;
//		rootDirStr = root ;
//		initUI();
//	}
	/** 构造器 */
	public ThFileContentPanel(FuncSubInfo pfuncsubinfo,String root) {		
		super();
		
		this.funcsubinfo=pfuncsubinfo ;
		funcode =pfuncsubinfo.getFuncode() ;
		rootDirStr = root ;
		//设置权限
		setUIEnable();
		initUI();
	}
	public ThFileContentPanel(String root,BillForm editor) {		
		super();
		rootDirStr = root ;
		editor_ = editor;
		//设置权限		
		initUI();
	}

	/**
	 * 
	 */
	private void setUIEnable() {
		if(funcsubinfo!=null){
			uploadenable =funcsubinfo.isValidButton(IFileSystemActionConst.UPLOAD);
			downloadenable =funcsubinfo.isValidButton(IFileSystemActionConst.DOWNLOAD);
			browseenable =funcsubinfo.isValidButton(IFileSystemActionConst.BROWSE);
			deleteenable =funcsubinfo.isValidButton(IFileSystemActionConst.DELETE);
			renameenable = funcsubinfo.isValidButton(IFileSystemActionConst.RENAME);
		}
	}


	private void initUI() {
		this.setLayout(new BorderLayout());
//		add(getToolbar(), BorderLayout.NORTH);
		add(getMenuBarContainer(), BorderLayout.NORTH);
		add(getSplitpanel(), BorderLayout.CENTER);
		add(getStatusbar(), BorderLayout.SOUTH);
		
		IQueryFolderTreeNodeService service = NCLocator
				.getInstance().lookup(
						IQueryFolderTreeNodeService.class);
		
		//add by ZTH 赋值rootNode
		try {
			NCFileNode	node = service.getNCFileNodeTreeAndCreateAsNeed(
					rootDirStr, WorkbenchEnvironment.getInstance()
							.getLoginUser().getCuserid());
			rootNode = findNode(node, rootDirStr);
		} catch (BusinessException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		if(!StringUtil.isEmpty(rootDirStr)){
			// rootnode 放入缓存
			toCache(rootNode);
			//设置默认选中根节点
			TreePath path = new TreePath(rootNode);
			getPatchTree().setSelectionPath(path);
		}
		
	}

	/** 新建文件夹 action */
	private NewFolderAction newfolderaction;

	public NewFolderAction getNewfolderaction() {
		if (newfolderaction == null) {
			newfolderaction = new NewFolderAction();
			
		}
		return newfolderaction;
	}

	/** 重命名 action */
	private RenameFolderAction renamefolderaction;

	public RenameFolderAction getRenamefolderaction() {
		if (renamefolderaction == null) {
			renamefolderaction = new RenameFolderAction();
		}
		return renamefolderaction;
	}

	/** 删除文件夹（文件） action */
	private DelFolderAction delfolderaction;

	public DelFolderAction getDelfolderaction() {
		if (delfolderaction == null) {
			delfolderaction = new DelFolderAction();
		}
		return delfolderaction;
	}

	private JPanel statusbar;
	private UIPanel scaleSliderPane =null;
	UIPanel getScaleSliderPane(){
		if(scaleSliderPane == null){
			scaleSliderPane=new UIPanel();
//			scaleSlider.setPreferredSize(new Dimension(220,30));
//			scaleSlider.setBorder(new LineBorder(Color.RED));
			scaleSliderPane.setOpaque(false);
		}
		return scaleSliderPane ;
	}
	public JPanel getStatusbar() {
		if (statusbar == null) {
			statusbar = new JPanel();
			statusbar.setPreferredSize(new Dimension(0, 35));
			statusbar.setBorder(new LineBorder(Color.gray));
			statusbar.setBackground(FileColorConst.BOTTOMCOLOR);
//			FlowLayout mgr = new FlowLayout();
//			mgr.setAlignment(FlowLayout.LEFT);
			BorderLayout mgr = new BorderLayout();
			statusbar.setLayout(mgr);
			statusbar.add(getLblstatubar(),BorderLayout.WEST);
			statusbar.add(getScaleSliderPane(),BorderLayout.EAST);
		}
		return statusbar;
	}

	private JLabel lblstatubar;

	public JLabel getLblstatubar() {
		if (lblstatubar == null) {
			lblstatubar = new JLabel("");

		}
		return lblstatubar;

	}

	private class CMouseHandler extends MouseInputAdapter {
	

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

	public void showPopupMenu(MouseEvent e) {
		//根节点不弹出

		ArrayList<TreePath> list = new ArrayList<TreePath>();
		TreePath tp = getPatchTree().getPathForLocation(e.getX(), e.getY());
		
		
		if (tp != null) {			
			list.add(tp);
		}
		if (e.isControlDown()) {
			TreePath[] tps = getPatchTree().getSelectionPaths();
			if (tps != null && tps.length > 0) {
				list.addAll(Arrays.asList(tps));
			}
		}
		getPatchTree().setSelectionPaths(list.toArray(new TreePath[0]));
		if(tp!=null&&tp.getLastPathComponent().equals(rootNode)){
			return;
		}
		getTreepopMenu().show(getPatchTree(), e.getX(), e.getY());

	}

	/** 树的右键菜单 */
	private JPopupMenu treepopMenu;
	
	/** 树右键菜单 删除action*/
	private DelFolderPopupAction delfolderPopAction;
	/** 树右键菜单 删除action */
	public DelFolderPopupAction getDelfolderPopAction(){
		if(delfolderPopAction == null){
			delfolderPopAction = new DelFolderPopupAction();
		}
		return delfolderPopAction ;
	}
	/** 树右键菜单重命名action*/
	private  RenameFolderPopupAction renamefolderPopAction ;
	/** 树右键菜单重命名action*/
	public RenameFolderPopupAction  getRenamefolderPopAction(){
		if(renamefolderPopAction == null ){
			renamefolderPopAction =new RenameFolderPopupAction() ;
			
		}
		return renamefolderPopAction ;
	}
	/** 树右键菜单新建action*/
	private NewFolderPopupAction newfolderPopAction;
	/** 树右键菜单新建action*/
	public NewFolderPopupAction  getNewfolderPopAction(){
		if(newfolderPopAction == null){
			newfolderPopAction = new NewFolderPopupAction();
		}
		return newfolderPopAction ;
	}
	/** 获取树右键菜单*/
	private JPopupMenu getTreepopMenu() {
		if (treepopMenu == null) {
			treepopMenu = new JPopupMenu();
			treepopMenu.add(getNewfolderPopAction());
			treepopMenu.addSeparator();
			treepopMenu.add(getDelfolderPopAction());
			treepopMenu.add(getRenamefolderPopAction());
			
			
//			treepopMenu.add(new NewFolderPopupAction());
//			treepopMenu.addSeparator();
			// popMenu.add(getUploadFileAction());
			// popMenu.add(getUpscan());
			// popMenu.add(getDownLoadFileAction());
			// popMenu.addSeparator();
			// popMenu.add(getRefreshAction());
			// popMenu.add(getShowFileInWebAction());

		}
		return treepopMenu;
	}

	/** 上传action */
	private ThUploadAction uploadAction = new ThUploadAction(ThFileContentPanel.this);//上传附件类
	
	/**ocr识别*/
	private ThOCRAction thocrAction = new ThOCRAction(ThFileContentPanel.this);//ocr识别
	/**从发票云选择发票*/
	private ThSelectAction thSelectAction = new ThSelectAction(ThFileContentPanel.this);
	
	
	/** 引用文档ation */
	private ThUploadRefAction uprefaction = new ThUploadRefAction(ThFileContentPanel.this);
	private ThUploadURLAction uploadurlaction = new ThUploadURLAction(ThFileContentPanel.this);
	private ActionButton btnupdateURL;
	/** 引用文档 －－废弃了*/
	private JButton btnuploadrefcenter;
	public ActionButton getBtnupdateURL(){
		if(btnupdateURL==null){
			btnupdateURL = new ActionButton(uploadurlaction);
		}
		return btnupdateURL;
	}
	
	private JButton btnupload;
	
	private JButton btnocr;
	
	private JButton btnose;
	
	
	/* 2010-10-24    以下按照uif2 画button 工具栏***/
	ActionButton getupmenu(){
		if(btnupload==null){
			btnupload =new ActionButton(uploadAction);
		}
		return (ActionButton)btnupload;
	}
	
	
	ActionButton getocrmenu(){
		if(btnocr==null){
			btnocr =new ActionButton(thocrAction);
		}
		return (ActionButton)btnocr;
	}
	
	ActionButton getselectmenu(){
		if(btnose==null){
			btnose =new ActionButton(thSelectAction);
		}
		return (ActionButton)btnose;
	}
	
	
	
	
	ActionButton getuprefmenu(){
		if(btnuploadrefcenter==null){
			btnuploadrefcenter =new ActionButton(uprefaction);
		}
		return (ActionButton)btnuploadrefcenter;
	}
	ActionButton getGpyimenu(){
		if(btngpy==null){
			btngpy =new ActionButton(gpyaction);
		}
		return (ActionButton)btngpy;
	}
	ActionButton getPastemenu(){
		if(btnpaste==null){
			btnpaste =new ActionButton(pasteaction);
			//快捷键测试
			btnpaste.registerKeyboardAction(pasteaction, KeyStroke.getKeyStroke(KeyEvent.VK_V,KeyEvent.CTRL_DOWN_MASK ), JComponent.WHEN_IN_FOCUSED_WINDOW);
			//快捷键测试
			btnpaste.setMnemonic(KeyEvent.VK_V);
		}
		return (ActionButton)btnpaste;
	}
	ThScanAttachAction scanattachaction ;
	public ThScanAttachAction getScanattachaction(){
		if(scanattachaction == null){
			scanattachaction =(new ThScanAttachAction(ThFileContentPanel.this));
		}
		return scanattachaction;
	}
	private ThScanAttachAction scanpptaction;
	public  ThScanAttachAction getScanpptaction(){
		if(scanpptaction == null){
			scanpptaction = new ThScanAttachAction(ThFileContentPanel.this);
		}
		return scanpptaction;
	}
	private ThScanAttachAction scansingleaction;
	public  ThScanAttachAction getScansingleaction(){
		if(scansingleaction == null){
			scansingleaction = new ThScanAttachAction(ThFileContentPanel.this);
		}
		return scansingleaction;
	}
	private ThScanAttachAction scansmallaction;
	public  ThScanAttachAction getScansmallaction(){
		if(scansmallaction == null){
			scansmallaction = new ThScanAttachAction(ThFileContentPanel.this);
		}
		return scansmallaction;
	}
	
	MenuButton btnscanimage ;
	MenuButton getScangrpmenu(){
		if(btnscanimage==null){
			ActionDelegate pde = new ActionDelegate();
			pde.setAction(getBtnscanimage());
			
			ActionDelegate cde1 = new ActionDelegate();			
			ActionDelegate cde2 = new ActionDelegate();
			ActionDelegate cde3 = new ActionDelegate();
			ActionDelegate cde4 = new ActionDelegate();
			cde1.setAction(getScanattachaction());
			cde2.setAction(getScanpptaction());
			cde3.setAction(getScansingleaction());
			cde4.setAction(getScansmallaction());
			pde.addChild(cde1);
			pde.addChild(cde2);
			pde.addChild(cde3);
			pde.addChild(cde4);
			btnscanimage =new MenuButton(pde);
		}
		return btnscanimage;
	}
	private static ImageIcon menuBarBGIcon = ThemeResourceCenter.getInstance().getImage("themeres/control/menu/menu_bg.png");
	private static ImageIcon menuBarBGFrameIcon = ThemeResourceCenter.getInstance().getImage("themeres/control/menu/menu_bg_frame.png");
	private JPanel menuBarContainer ;
	JPanel getMenuBarContainer() {
		if(menuBarContainer == null){
			menuBarContainer = new JPanel(){
				
				private static final long serialVersionUID = 7130908951757832647L;
				@Override
				protected void paintComponent(Graphics g) {
					super.paintComponent(g);
					Dimension size = getSize();
					if(menuBarBGIcon != null && menuBarBGFrameIcon != null){
						int frameW = menuBarBGFrameIcon.getIconWidth();
						g.drawImage(menuBarBGIcon.getImage(), frameW, 0, size.width-2*frameW, size.height, this);
						menuBarBGFrameIcon.paintIcon(this, g, 0, 0);
						menuBarBGFrameIcon.paintIcon(this, g, size.width - frameW, 0);
					}
				}
				
			};
			menuBarContainer.setOpaque(false);
			menuBarContainer.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
			menuBarContainer.setLayout(new BorderLayout());
			menuBarContainer.add(getBar(), BorderLayout.CENTER);
			menuBarContainer.add(getComboxbilltype(),BorderLayout.EAST);
			getBar().setOpaque(false);
		}
		return menuBarContainer;
	}
	private UIComboBox comboxbilltype;
	public UIComboBox getComboxbilltype(){
		if(comboxbilltype == null){
			comboxbilltype = new UIComboBox();
			comboxbilltype.setPreferredSize(new Dimension(140,18));
			comboxbilltype.setVisible(false);
			
//			comboxbilltype.addItem("某单据类型1");
//			comboxbilltype.addItem("某单据类型2222");
			comboxbilltype.setSize(140,18);
			comboxbilltype.addItemListener(new ItemListener(){
				@Override
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() != ItemEvent.SELECTED){
						return ;
					}else{
						//浏览状态
						PAGE_STATE=BROWSELISTTABLE_STATE;
						
						treenodefilecacheMap.clear();
						treefileszieMap.clear();

						
						treemodel=null;
						ItemObj item =(ItemObj) getComboxbilltype().getSelectedItem();
						rootDirStr =item.getRootname();
						treemodel=getTreemodel();
						getPatchTree().setModel(treemodel);
						
						getPatchTree().updateUI();
						getfiletablemodel().clearTable();
						// rootnode 放入缓存
						toCache(rootNode);
					}
					
				}
			});
		}
		return comboxbilltype;
	}
	FuncletMenuBar bar ;
	public FuncletMenuBar getBar(){
		if(bar==null){
			bar =new FuncletMenuBar();
			bar.setPreferredSize(new Dimension(0,30));
			bar.addMenuComp(getupmenu());//上传按钮添加  zth
			bar.addMenuComp(getocrmenu());//ocr按钮添加  zth
			//bar.addMenuComp(getselectmenu());//发票获取  yy
			
			//bar.addMenuComp(getPastemenu());
			//bar.addMenuComp(getuprefmenu());
			//bar.addMenuComp(getGpyimenu());			
			//bar.addMenuComp(getBtnupdateURL());
			//ActionDelegate de =new ActionDelegate();
			//de.setAction(new SeparatorAction());
			//bar.addMenuComp(new SeparatorButton(de));
			//bar.setOpaque(false);
			//bar.addMenuComp(getScangrpmenu());//浏览
		}
		return bar;
	}
	/*2010-10-24    end 以下按照uif2 画button 工具栏***/
//	public JButton getBtnupload() {
//		if (btnupload == null) {
//			btnupload = new JButton("上传附件");
//			btnupload.addActionListener(uploadAction);
//		}
//		return btnupload;
//	}

	
//
//	public JButton getBtnuploadrefcenter() {
//		if (btnuploadrefcenter == null) {
//			btnuploadrefcenter = new JButton("引用文档");
//			btnuploadrefcenter.addActionListener(uprefaction);
//		}
//		return btnuploadrefcenter;
//	}

	private ThGaopaiyiAction gpyaction = new ThGaopaiyiAction(ThFileContentPanel.this);
	private JButton btngpy;

//	public JButton getBtngpy() {
//		if (btngpy == null) {
//			btngpy = new JButton("高拍仪");
//			btngpy.addActionListener(gpyaction);
//		}
//		return btngpy;
//	}

	private ThPasteAttachAction pasteaction = new ThPasteAttachAction(
			ThFileContentPanel.this);
	private JButton btnpaste;

//	public JButton getBtnpaste() {
//		if (btnpaste == null) {
//			btnpaste = new JButton("粘贴附件");
//			btnpaste.addActionListener(pasteaction);
//			//快捷键测试
//			btnpaste.registerKeyboardAction(pasteaction, KeyStroke.getKeyStroke(KeyEvent.VK_V,KeyEvent.CTRL_DOWN_MASK ), JComponent.WHEN_IN_FOCUSED_WINDOW);
//			//快捷键测试
//			btnpaste.setMnemonic(KeyEvent.VK_V);
//			
//		}
//		return btnpaste;
//	}
//	private MenuAction browseaction ;
//	public MenuAction getBrowseaction(){
//		return browseaction;
//	}
	private MenuAction btnscanimageaction;

	public MenuAction getBtnscanimage() {
		if (btnscanimageaction == null) {
			btnscanimageaction = new MenuAction("brow",NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0000")/*浏览*/);
			btnscanimageaction.addChildAction(getScanattachaction());
			btnscanimageaction.addChildAction(getScanpptaction());
			btnscanimageaction.addChildAction(getScansingleaction());
			btnscanimageaction.addChildAction(getScansmallaction());

		}
		return btnscanimageaction;
	}



//	private JToolBar toolbar = null;
//
//	public JToolBar getToolbar() {
//		if (toolbar == null) {
//			toolbar = new UIToolBar();
//			toolbar.setFloatable(false);
//			toolbar.add(getupmenu());
//			toolbar.add(getBtnuploadrefcenter());
//			toolbar.add(getBtngpy());
//			toolbar.add(getBtnpaste());
//			toolbar.add(getBtnscanimage());
//
//		}
//		return toolbar;
//	}

	/**
	 * 左树，右表分割
	 */

	private UISplitPane splitpanel = null;
	private JPanel lefttreepanel;

	public JPanel getLefttreepanel() {
		if (lefttreepanel == null) {
			lefttreepanel = new JPanel();
			lefttreepanel.setBorder(new LineBorder(Color.gray));
			lefttreepanel.setLayout(new BorderLayout());
			
			lefttreepanel.setPreferredSize(new Dimension(235, 0));
			lefttreepanel.setMinimumSize(new Dimension(235,0));
			lefttreepanel.add(getTreetoolpanel(), BorderLayout.NORTH); //新增文件夹按钮  重命名  删除按钮
			lefttreepanel.add(getTreepane(), BorderLayout.CENTER);
			//			
		}
		return lefttreepanel;
	}
	
	private JScrollPane treepane ;
	public JScrollPane getTreepane(){
		if(treepane == null ){
			treepane = new JScrollPane();
			treepane.setBorder(null);
			treepane.setName("treescrollpane");
			treepane.setViewportView(getPatchTree());
		}
		return treepane ;
	}
//	private JPanel treepanel ;	
//	public JPanel getTreepanel(){
//		if(treepanel==null){
//			treepanel = new JPanel();
//			treepanel.setBorder(new LineBorder(Color.red));
//			treepanel.setPreferredSize(new Dimension(235, 0));
//			SpringLayout springlayout = new SpringLayout();
//			treepanel.setLayout(springlayout);
//			treepanel.add(getPatchTree());
//			springlayout.putConstraint(SpringLayout.WEST, getPatchTree(), 10, SpringLayout.WEST, treepanel);
//			springlayout.putConstraint(SpringLayout.NORTH, getPatchTree(), 5, SpringLayout.NORTH, treepanel);
//			springlayout.putConstraint(SpringLayout.EAST, getPatchTree(), 10, SpringLayout.EAST, treepanel);
//		}
//			
//		return treepanel ;
//	}
	 
	private JPanel treetoolpanel;

	public JPanel getTreetoolpanel() {
		if (treetoolpanel == null) {
			treetoolpanel = new JPanel();
			treetoolpanel.setBorder(new BottomBorder(0,0,0,0));
			FlowLayout m = new FlowLayout();
			m.setAlignment(FlowLayout.RIGHT);
			treetoolpanel.setLayout(m);

			treetoolpanel.add(getTreetoolbar());
		}
		return treetoolpanel;
	}

	private ActionsBar treetoolbar;

	public ActionsBar getTreetoolbar() {
		if (treetoolbar == null) {
			treetoolbar = new ActionsBar();
			// treetoolbar.setBorder(new LineBorder(Color.gray));
			//	
			treetoolbar.setMinimumSize(new Dimension(100,22));
			treetoolbar.addAction(getNewfolderaction());
			treetoolbar.addAction(getRenamefolderaction());
			treetoolbar.addAction(getDelfolderaction());
			// treetoolbar.add(new HyperButton("test1","test1"));
		}
		return treetoolbar;
	}

	private class NewFolderAction extends AbstractNCAction {

		private static final long serialVersionUID = -4636774835978670803L;

		public NewFolderAction() {
			this.putValue(AbstractNCAction.SMALL_ICON, ClientToolKit
					.loadImageIcon("themeroot/blue/themeres/ui/toolbaricons/add-child.png"));
			this.setTooltip(NCLangRes.getInstance().getStrByID("sftemp", "FileInputNameDialog-0000")/*新建文件夹*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			createfolder();
		}

		
	}

	private class NewFolderPopupAction extends AbstractNCAction {

		private static final long serialVersionUID = -4636774835978670803L;

		public NewFolderPopupAction() {
			this.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0001")/*新建*/);
			this.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0001")/*新建*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			createfolder();
		}
	}

	private class DelFolderPopupAction extends AbstractNCAction {

		private static final long serialVersionUID = -1L;

		public DelFolderPopupAction() {
			this.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0002")/*删除*/);
			this.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0002")/*删除*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			delfolder();
		}
	}
	private void createfolder() {

		if (rootNode == null) {
			return;
		}
//		//规定只能在根目录下  建文件夹
//		TreePath path = getPatchTree().getSelectionPath();
		//修改为只在根目录下
		TreePath path =  new TreePath(rootNode.getPath()) ;

		NCFileNode node = (NCFileNode)path.getLastPathComponent();
		String str = null;
		FileInputNameDialog dialog = new FileInputNameDialog();
		if(dialog.showModal()==UIDialog.ID_OK){
			str = dialog.getFilename();
		}
//		String str = (String) MessageDialog.showInputDlg(FileContentPanel.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000005")/*新建文件夹*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000006")/*请输入文件夹名称*/, "newfolder");
		if (str != null && str.trim().length() > 0) {
			try {
				if(CheckTheSameFolderName(node,str))
				{	
					return;
				}
				IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
				NCFileNode newNode = service.createNewFileNode(node.getFullPath(), str, WorkbenchEnvironment.getInstance().getLoginUser().getCuserid());
				DefaultTreeModel model = getTreemodel();
				model.insertNodeInto(newNode, node, node.getChildCount());
				model.nodeStructureChanged(node);
				TreePath newPath = new TreePath(getTreePath(newNode));
				getPatchTree().setSelectionPath(newPath);
				getPatchTree().expandPath(newPath);
				
				getTreenodefilecacheMap().put(newNode.getFullPath(), new ArrayList<NCFileVO>());
			} catch (Exception ex) {
				Logger.error(ex.getMessage(), ex);
				MessageDialog.showErrorDlg(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, ex.getMessage());
			}
		}
	}
	private class RenameFolderPopupAction extends AbstractNCAction {

		private static final long serialVersionUID = -1L;

		public RenameFolderPopupAction() {
			this.putValue(AbstractAction.NAME, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0003")/*重命名*/);
			this.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0003")/*重命名*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			renamefoder();
		}
	}

	private class DelFolderAction extends AbstractNCAction {
		private static final long serialVersionUID = 3273091047549713804L;

		public DelFolderAction() {
			this.putValue(AbstractNCAction.SMALL_ICON, ClientToolKit
					.loadImageIcon("themeroot/blue/themeres/ui/toolbaricons/delete.png"));
			this.setTooltip(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0002")/*删除*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			delfolder();
		}
	}

	private class RenameFolderAction extends AbstractNCAction {
		private static final long serialVersionUID = -132307984647892932L;

		public RenameFolderAction() {
			this.putValue(AbstractNCAction.SMALL_ICON, ClientToolKit
					.loadImageIcon("themeroot/blue/themeres/ui/toolbaricons/edit.png"));
			this.setTooltip(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0003")/*重命名*/);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			renamefoder();
		}
	}

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

		getPatchTree().getUI().startEditingAtPath(getPatchTree(), treePath);
	}

	public void delfolder() {

		if (rootNode == null) {
			return;
		}
		
		TreePath[] paths = getPatchTree().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++) {
			NCFileNode node = (NCFileNode) paths[i].getLastPathComponent();
			//根节点 不能删除 ，删除就会出错
			if (node.equals(rootNode)) {
				MessageDialog.showOkCancelDlg(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("sftemp", "FilePatchAttrDialog-0012")/*错误*/,NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0016")/*根节点不能删除！*/);
				continue;
			}
			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(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000007")/*删除确认框*/, sb.toString()) == MessageDialog.ID_OK) {
					
					DefaultTreeModel model = getTreemodel();
					for (int i = 0; i < nodeList.size(); i++) {
						DefaultMutableTreeNode tempNode = nodeList.get(i);
						TreeNode parent = tempNode.getParent();
						
						NCFileNode fn =(NCFileNode)tempNode;
						HashMap<String, NCFileVO> mapfilevo = fn.getFilemap();
						String path = fn.getFullPath();
						
						//清理客户端，"全部"下的删除文件
						for(NCFileVO fvo :mapfilevo.values()){
							getTreenodefilecacheMap().get("root").remove(fvo);
						}
						//清理客户端，本页的缓存map
						if(getTreenodefilecacheMap().containsKey(path)){
							getTreenodefilecacheMap().remove(path);
						}
						
						//改变树结构
						model.removeNodeFromParent(tempNode);
						if (parent != null) {
							model.nodeStructureChanged(parent);
						}
					}
					//清理缓存 
					getfiletablemodel().clearTable();
//					for(String path :nodePathsList){
//					
//					}
					if(PAGE_STATE!=BROWSELISTTABLE_STATE){
						getTablepanel().removeAll();
						getTablepanel().updateUI();
					}
					service.deleteNCFileNodes(nodePathsList.toArray(new String[0]));
				}
			} catch (BusinessException ex) {
				Logger.error(ex.getMessage(), ex);
			}
		}

	
		
	}

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

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

		@Override
		public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
			Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
			if (value instanceof NCFileNode) {
				node = (NCFileNode) value;				
			}
			
			return c ;
		}
		@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();
				
				TreePath treePath = getPatchTree().getSelectionPath();
				if (treePath == null) {
					return oldValue;
				}
				Object obj = treePath.getLastPathComponent();
				if (obj.equals(rootNode)) {
					MessageDialog.showErrorDlg(ThFileContentPanel.this,
							NCLangRes.getInstance().getStrByID("pc",
									"FileManageUI-000000")/* 错误 */, NCLangRes
									.getInstance().getStrByID("pc",
											"FileManageUI-000011")/* 不能对根节点重命名 */);
					return oldValue;
				}
				
				node.setUserObject(newValue);
				String newPath = node.getFullPath();
				
				
				
				boolean b = false;
				try {
					if (newValue.indexOf("/") != -1 || newValue.indexOf("\\") != -1) {
						MessageDialog.showErrorDlg(ThFileContentPanel.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(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000002")/*提示*/, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000003")/*文件名重复*/);
							return oldValue;
						}else{
							//保存成功更新树缓存
							Collection<NCFileVO> c =getTreenodefilecacheMap().get(oldPath);
							getTreenodefilecacheMap().remove(oldPath);
							getTreenodefilecacheMap().put(newPath, c);
						}
					}
				} 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 UITree patchtree = null;
	/**
	 * 右边的附件详细信息
	 */
	private UITable patchinfotable = null;

	/**
	 * 左边树的model
	 */
	private DefaultTreeModel treemodel = null;
	/**
	 * 右边附件列表的model
	 */
	private FileVOTableModel tablemodel = null;

	public UISplitPane getSplitpanel() {
		if (splitpanel == null) {
			splitpanel = new UISplitPane(UISplitPane.HORIZONTAL_SPLIT);
//			splitpanel.add(getLefttreepanel(), UISplitPane.LEFT);
			
			splitpanel.add(getTablepanel(), UISplitPane.RIGHT);//右边框
			splitpanel.setDividerSize(3);
		}
		return splitpanel;
	}
	protected JPanel tablepanel;
	public JPanel getTablepanel(){
		if(tablepanel== null){
			
			tablepanel = new JPanel();
			tablepanel.setLayout(new BorderLayout());
			tablepanel.setPreferredSize(new Dimension(500, 400));
//			CardLayout cardlayout = new CardLayout();
//			tablepanel.setLayout(cardlayout);
			
			tablepanel.add(getJstablepanel(),BorderLayout.CENTER);
//			tablepanel.add(getJstablepanel(),"card2");
		}
		return tablepanel;
	}
	
	private JScrollPane jstablepanel;

	public JScrollPane getJstablepanel() {
		if (jstablepanel == null) {
			jstablepanel = new JScrollPane(getPatchInfoTable());
		}
		return jstablepanel;
	}

	@SuppressWarnings("unchecked")
	protected class FileVOTableModel extends VOTableModel {

		/**
		 * 
		 */
		private static final long serialVersionUID = -6001046311222516903L;
		String[] columnnames = { "", NCLangRes.getInstance().getStrByID("sftemp", "FilePatchAttrDialog-0004")/*附件名*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0004")/*大小*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0005")/*描述*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0006")/*上传时间*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0007")/*操作*/ };

		public FileVOTableModel(ValueObject[] vos) {
			super(vos);
		}

		@Override
		public String getColumnName(int col) {
			// 
			return columnnames[col];
		}

		@Override
		public int getColumnCount() {
			return columnnames.length;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			Object o = this.getVO(rowIndex);
			if (o instanceof NCFileVO) {
				NCFileVO file = (NCFileVO) o;

				if (columnIndex == 0) {
					return rowIndex + 1;
				} else if (columnIndex == 1) {
					return file.getName();
				} else if (columnIndex == 2) {
					return FileManageStringFormat.formatFileSize(file
							.getFileLen());
				} else if (columnIndex == 3) {
					return file.getFiledesc();
				} else if (columnIndex == 4) {
					return FileManageStringFormat.formatDateToString(file
							.getTime());
				} else if (columnIndex == 5) {
					return "";
				} else {
					return "";
				}
			}
			return "test";
		}

		@Override
		public boolean isCellEditable(int row, int column) {
			if (isColumnEditable(column)) {
				return true;
			} else {
				return false;
			}
		}

		@Override
		public boolean isColumnEditable(int col) {
			if (col == 1 || col == 5) {
				return true;
			}
			return false;
		}

		public boolean isRowEditable(int row) {

			return true;
		}

		@Override
		public boolean isAndEditable() {
			// 
			return true;
		}

	}

	private FileManageTreeRenderer filetreerender;

	public FileManageTreeRenderer getFiletreerender() {
		if (filetreerender == null) {
			filetreerender = new FileManageTreeRenderer();
		}
		return filetreerender;
	}


	
	private class MyFileTree extends UITree{
		/**
		 * 
		 */
		private static final long serialVersionUID = -3022453623914006697L;

		@Override
		public boolean isPathEditable(TreePath path) {
			if(path.getLastPathComponent().equals(rootNode)){
				return false ;
			}
			return super.isPathEditable(path);
		}
	}

	public UITree getPatchTree() {
		if (patchtree == null) {
			patchtree = new MyFileTree();
			patchtree.setUI(new FileManageTreeUI());
			
			patchtree.setRowHeight(28);
			patchtree.setBorder(new EmptyBorder(5,10,0,10));
			// patchtree.setBackground(FileManageUIConst.MCBOXTREEBG);
			patchtree.setCellRenderer(getFiletreerender());
			CTreeCellEditor ceditor = new CTreeCellEditor(patchtree);
			patchtree.setCellEditor(ceditor);
			patchtree.setModel(getTreemodel());
			patchtree.setEditable(true);
			
			patchtree.addMouseListener(new CMouseHandler());
			patchtree.setRootVisible(true);
			patchtree.setBounds(10,5,patchtree.getWidth()-20,patchtree.getHeight()-10);
			patchtree.addTreeSelectionListener(new TreeSelectionListener() {
				@Override
				public void valueChanged(TreeSelectionEvent e) {
					actionTree(e);
				}
			});
			
		}
		return patchtree;
	}

	private void actionTree(TreeSelectionEvent e) {
		refreshUIbyClickTree();

	}
	
	private void refreshUIbyClickTree() {
		if (getPatchTree().getSelectionPath() == null)
			return;
		
		selfoldernode = (NCFileNode) getPatchTree()
				.getSelectionPath().getLastPathComponent();
		if(selfoldernode.equals(rootNode)){
			getDelfolderaction().setEnabled(false);
			getRenamefolderaction().setEnabled(false);
		}else{
			getDelfolderaction().setEnabled(true);
			getRenamefolderaction().setEnabled(true);
		}
		if(PAGE_STATE==BROWSELISTTABLE_STATE){
			ThFileBrowseCreatePane.createListBrowsePane(ThFileContentPanel.this);

		}else if(PAGE_STATE==BROWSEPPTICON_STATE){
			ThFileBrowseCreatePane.createPPTBrowsePane(ThFileContentPanel.this, new ScaleSlider());
		}else if(PAGE_STATE==BROWSESINGLEICON_STATE){
			ThFileBrowseCreatePane.createSingleBrosePane(ThFileContentPanel.this, new ScaleSlider());
		}else if(PAGE_STATE==BROWSESMALLICON_STATE){
			ThFileBrowseCreatePane.createSmallImagePane(ThFileContentPanel.this);
		}
		
	}
	/**
	 * 更新状态栏 
	 */
	protected void refreshStatuBar(){
		//TODO （方法if else要重构）
		if(selfoldernode== null ||selfoldernode.getFullPath().equals(rootDirStr)){
			// 更新状态栏(几个附件，大小)
			int filecount = getTreenodefilecacheMap().get("root").size();
			Long filesize = 0l;
			for (NCFileVO fvo : getTreenodefilecacheMap().get("root")) {
				filesize += fvo.getFileLen();
			}
	
			if (filecount > 0 && filesize > 0) {
				StringBuffer sb = new StringBuffer();
				sb.append(filecount).append(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0008")/*个附件 :*/).append("   ");
				sb.append(FileManageStringFormat.formatFileSize(filesize));
				getLblstatubar().setText(sb.toString());
			} else {
				getLblstatubar().setText(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0009")/*附件信息*/);
			}
		}else{
			// 更新状态栏
			int filecount =0;
			Long filesize = 0l;
			if(getTreenodefilecacheMap().get(selfoldernode.getFullPath())!=null){
					filecount = getTreenodefilecacheMap().get(selfoldernode.getFullPath()).size();
					for (NCFileVO fvo : getTreenodefilecacheMap().get(selfoldernode.getFullPath())) {
						filesize += fvo.getFileLen();
					}
			}
			
			
			if (filecount > 0 && filesize > 0) {
				StringBuffer sb = new StringBuffer();
				sb.append(filecount).append(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0008")/*个附件 :*/).append("   ");
				sb.append(FileManageStringFormat.formatFileSize(filesize));
				getLblstatubar().setText(sb.toString());
			} else {
				getLblstatubar().setText(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0009")/*附件信息*/);
			}
		}
	}
	
	/**
	 * 树的model
	 * 
	 * @return
	 */
	protected DefaultTreeModel getTreemodel() {
		if (treemodel == null) {
			treemodel = new DefaultTreeModel(null);
			treemodel.setAsksAllowsChildren(true);
			
			try {
				if (rootDirStr != null) {
					IQueryFolderTreeNodeService service = NCLocator
							.getInstance().lookup(
									IQueryFolderTreeNodeService.class);
					NCFileNode node = service.getNCFileNodeTreeAndCreateAsNeed(
							rootDirStr, WorkbenchEnvironment.getInstance()
									.getLoginUser().getCuserid());
					rootNode = findNode(node, rootDirStr);
				} else {
					rootNode = null;
				}

				

				treemodel.setRoot(rootNode);
				treemodel.nodeStructureChanged(rootNode);

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

	private void toCache(NCFileNode rootNode) {
		if(rootNode==null){
			return ;
		}
		Enumeration<NCFileNode> enumer = rootNode.breadthFirstEnumeration();
//		NCFileNode retrNode = null;
		while (enumer.hasMoreElements()) {
			NCFileNode tempNode = (NCFileNode) enumer.nextElement();
			getTreenodefilecacheMap().put(tempNode.getFullPath(),
					tempNode.getFilemap().values());
		}
		// root 包含所有的文件
		if (getTreenodefilecacheMap().get("root") == null) {
			ArrayList<NCFileVO> arr = new ArrayList<NCFileVO>();
			for (Collection<NCFileVO> cvo : getTreenodefilecacheMap().values()) {
				arr.addAll(cvo);
			}
			getTreenodefilecacheMap().put("root", arr);
		}

	}

	@SuppressWarnings("unchecked")
	 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;
				// retrNode.setParent(null);
				break;
			}
		}
		return retrNode;
	}

	public UITable getPatchInfoTable() {
		if (patchinfotable == null) {
			patchinfotable = new UITable();
			patchinfotable.setModel(getfiletablemodel());
			patchinfotable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			TableColumnModel colmodel = patchinfotable.getColumnModel();
			TableColumn col0_rownum = colmodel.getColumn(0);
			col0_rownum.setPreferredWidth(30);
			col0_rownum.setCellRenderer(new RownumTableCellRender());
			TableColumn col1_filename = colmodel.getColumn(1);
			col1_filename.setCellRenderer(new BtnTableCellRender());
			col1_filename
					.setCellEditor(new BtnTableCellEditor(new JCheckBox()));
			col1_filename.setPreferredWidth(93);
			TableColumn col2 = colmodel.getColumn(2);
			col2.setPreferredWidth(66);
			TableColumn col4 = colmodel.getColumn(4);
			col4.setPreferredWidth(120);

			TableColumn btncol = colmodel.getColumn(5);
			btncol.setCellRenderer(new BtnTableCellRender());
			btncol.setCellEditor(new BtnTableCellEditor(new JCheckBox()));
			btncol.setPreferredWidth(190);
			patchinfotable.addMouseMotionListener( new FileMouseListener());
		}
		return patchinfotable;
	}
	
	private class FileMouseListener extends MouseMotionAdapter{
		@Override
		public void mouseMoved(MouseEvent e) {
			int col =patchinfotable.columnAtPoint(e.getPoint());
			if(col!=-1&&(col == colnumbtnpane ||col == colnumbtnbrow) ){
				patchinfotable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
				
			}else{
				patchinfotable.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			}
		}
		
	}

	private class RownumTableCellRender implements TableCellRenderer {

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			JLabel label = new JLabel();
			label.setText(String.valueOf(value));
			label.setOpaque(true);
			
			
			if(isSelected){
				label.setBackground(table.getSelectionBackground());
			}else{
				label.setBackground(table.getTableHeader().getBackground());
			}
			label.setHorizontalAlignment(SwingConstants.CENTER);
			return label;
		}

	}

	
	public FileVOTableModel getfiletablemodel() {

		if (tablemodel == null) {
			tablemodel = new FileVOTableModel(null);
		}
		return tablemodel;
	}
	
	
	/**
	 * @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 BtnPanel extends JPanel {
		
		private static final long serialVersionUID = 5460160935253553438L;
		HyperButton btndownload = new HyperButton(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0010")/*下载*/, "dowm");
		HyperButton btnupfpload = new HyperButton(NCLangRes.getInstance().getStrByID("sftemp", "传发票"), "upfp");
		HyperButton btnmove = new HyperButton(NCLangRes.getInstance().getStrByID("sftemp", "FileMoveDialog-0000")/*移动*/, "move");
		HyperButton btneidt = new HyperButton(NCLangRes.getInstance().getStrByID("sftemp", "FilePatchAttrDialog-0010")/*编辑属性*/, "edit");
		HyperButton btndelete = new HyperButton(NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0002")/*删除*/, "delete");
		int rowindex;

		// JButton test= new JButton("test");

		public BtnPanel(int row) {
			super();
			rowindex = row;
			
			SpringLayout layout = new SpringLayout();
			this.setLayout(layout);
			NCFileVO filevo = (NCFileVO) getfiletablemodel().getVO(row);
			
//			btnbdownload.setOpaque(true);
//			btnbdownload.setBackground(Color.red);
			BtnPanel.this.setOpaque(true);
//			BtnPanel.this.setBackground(Color.red);
			BtnPanel.this.add(btndownload);
//			BtnPanel.this.add(btnupfpload);
//			BtnPanel.this.add(btnmove);
			BtnPanel.this.add(btneidt);
			BtnPanel.this.add(btndelete);
			
			if(filevo!=null&&filevo.getFiletype()!=null&&filevo.getFiletype().equalsIgnoreCase(FileTypeConst.URL)){
//				btndownload.setEnabled(false);
				btndownload.setVisible(false);
			}else{
//				btndownload.setEnabled(true);
				btndownload.setVisible(true);
			}
			

			// springlayout 控制按钮间距离 15
			
			
			layout.putConstraint(SpringLayout.WEST, btndownload, 20,
					SpringLayout.WEST, BtnPanel.this);
		
			layout.putConstraint(SpringLayout.WEST, btneidt, 20,
					SpringLayout.EAST, btndownload);
			layout.putConstraint(SpringLayout.WEST, btndelete, 20,
					SpringLayout.EAST, btneidt);
			
		
			
			/*layout.putConstraint(SpringLayout.WEST, btndownload, 12,
					SpringLayout.WEST, BtnPanel.this);
			
			layout.putConstraint(SpringLayout.WEST, btnupfpload, 12,
					SpringLayout.EAST, btndownload);
			
			layout.putConstraint(SpringLayout.WEST, btneidt, 12,
					SpringLayout.EAST, btnupfpload);
			layout.putConstraint(SpringLayout.WEST, btndelete, 12,
					SpringLayout.EAST, btneidt);*/
			
			
/*			layout.putConstraint(SpringLayout.WEST, btndownload, 15,
			SpringLayout.WEST, BtnPanel.this);
			
			layout.putConstraint(SpringLayout.WEST, btnmove, 15,
					SpringLayout.EAST, btndownload);
			layout.putConstraint(SpringLayout.WEST, btneidt, 15,
					SpringLayout.EAST, btnmove);
			layout.putConstraint(SpringLayout.WEST, btndelete, 15,
					SpringLayout.EAST, btneidt);*/
			// layout.putConstraint(SpringLayout.WEST,test,15,SpringLayout.EAST,btndelete);

			//处理权限
			
				btndownload.setEnabled(downloadenable);
				btndelete.setEnabled(deleteenable);
			
			
			//注册事件
			btndownload.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					downloadFile();

				}

				private void downloadFile() {
					getPatchInfoTable().setRowSelectionInterval(rowindex,
							rowindex);
					int row = BtnPanel.this.rowindex;
					if (row == -1) {
						return;
					}
					NCFileVO filevo = (NCFileVO) getfiletablemodel().getVO(row);
					String filepath = filevo.getFullPath();

					if (filepath != null) {
						String path = filevo.getFullPath();
						String name = filevo.getName();
						String defaultType = getFileType(name);
						NCFileChooser chooser = new NCFileChooser();
						// 设置默认选中文件
						chooser.setSelectedFile(new File(name));

						if (chooser.showSaveDialog(ThFileContentPanel.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(
												ThFileContentPanel.this,
												NCLangRes
														.getInstance()
														.getStrByID("pc",
																"FileManageUI-000000")/* 错误 */,
												ex.getMessage());
							} finally {
								try {
									if (fos != null) {
										fos.close();
									}
								} catch (Exception e2) {
								}
							}
						}

					}
				}

			});
			
			
			btnupfpload.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					downloadFile();

				}

				private void downloadFile() {
					getPatchInfoTable().setRowSelectionInterval(rowindex,
							rowindex);
					int row = BtnPanel.this.rowindex;
					if (row == -1) {
						return;
					}
					NCFileVO filevo = (NCFileVO) getfiletablemodel().getVO(row);
					String filepath = filevo.getFullPath();

					if (filepath != null) {
						String path = filevo.getFullPath();
						String name = filevo.getName();
						String defaultType = getFileType(name);
	
						File file = new File("C:\\Users\\Administrator\\Desktop\\附件迁移rrr.txt");
						
						String dsName = WorkbenchEnvironment.getInstance()
								.getLoginBusiCenter().getDataSourceName();
						FileOutputStream fos = null;
						try {
							fos = new FileOutputStream(file);
							FileManageServletClient.downloadFile(dsName,
									path, fos);
							MessageDialog.showHintDlg(ThFileContentPanel.this, "提示", "传发票系统成功!");
						} catch (Exception ex) {
							Logger.error(ex.getMessage(), ex);
							MessageDialog
									.showErrorDlg(
											ThFileContentPanel.this,
											NCLangRes
													.getInstance()
													.getStrByID("pc",
															"FileManageUI-000000")/* 错误 */,
											ex.getMessage());
							} finally {
								try {
									if (fos != null) {
										fos.close();
									}
								} catch (Exception e2) {
								}
							}

					}
				}

			});
			
			
			btneidt.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					getPatchInfoTable().setRowSelectionInterval(rowindex,
							rowindex);
					ThFilePatchAttrDialog dialog = new ThFilePatchAttrDialog(
							ThFileContentPanel.this);
//					dialog.setSize(525, 350);
					dialog.showModal();
				}

			});
			btndelete.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					getPatchInfoTable().setRowSelectionInterval(rowindex,
							rowindex);
					if (MessageDialog.showOkCancelDlg(ThFileContentPanel.this,
							NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0011")/*确认删除*/,
							NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0012")/*确定要删除文件?*/) == MessageDialog.ID_OK) {
						int row = getPatchInfoTable().getSelectedRow();
						NCFileVO filevo = (NCFileVO) getfiletablemodel().getVO(
								row);
						String filepath = filevo.getFullPath();
						
						
						
						 String[] filname=filepath.split("/");
							
						 /**
						  * 
						  * 已经勾选了发票参照信息的不允许删除
						  * 
						  */
						
						int count =editor_.getBillCardPanel().getBodyPanel().getTable().getRowCount();//明细行条数
						//获取已经勾选的发票数据
						List<String> lisvdef20=new ArrayList<String>();
						for(int i=0;i<count;i++){
							Object objvbdef20=editor_.getBillCardPanel().getBodyValueAt(i, "vbdef20");//主键
							if(null!=objvbdef20){
								String vbdef20=objvbdef20.toString();
								String[] vbd20arry=vbdef20.split(",");
								for(int j=0;j<vbd20arry.length;j++){
									lisvdef20.add(vbd20arry[j]);
								}
							}
						 }
						
						List<String> memoarry= QryDefMemo(lisvdef20);
						
						if(null!=memoarry&&memoarry.size()>0){
							if(memoarry.contains(filname[1])){
								 MessageDialog.showErrorDlg(ThFileContentPanel.this, "提示","发票已经被勾选，不允许删除！");
								 return;
							}
						}
						
						
						try {
							// 删除文件
							IFileSystemService service = NCLocator
									.getInstance().lookup(
											IFileSystemService.class);

							service
									.deleteNCFileNodes(new String[] { filepath });
							
							
							
							

							// 刷新table
							getfiletablemodel().removeVO(row);
							getfiletablemodel().refreshTable();
							// 树上的缓存清理
							getTreenodefilecacheMap().get("root")
									.remove(filevo);
							getTreenodefilecacheMap().get(
									filevo.getParentpath()).remove(filevo);
							

							//// 更新状态栏(几个附件，大小)
							refreshStatuBar();
						} catch (BusinessException ex) {
							Logger.error(ex.getMessage(), ex);
						}
						
						//删除home发票文件夹里的对应发票 add by ZTH
						/*String deletefilepath =  RuntimeEnv.getInstance().getNCHome()
							      +File.separator +"uploadfile" + File.separator+ filepath; // 文件保存的路径
						
						 File file = new File(deletefilepath);
						
						 if (file.delete()) {
							 MessageDialog.showHintDlg(ThFileContentPanel.this, "提示","删除成功！");
					      } else {
					    	  MessageDialog.showErrorDlg(ThFileContentPanel.this, "提示","删除操作失败。");
					      }*/
						 IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
						 if (ocrservice.deleteFile(filepath)){
							 MessageDialog.showHintDlg(ThFileContentPanel.this, "提示","删除成功！");
					      } else {
					    	  MessageDialog.showErrorDlg(ThFileContentPanel.this, "提示","删除操作失败。");
					      }
						 
						 //由于删除太慢，改成自定义档案数据停用
						 DefdocVO[] deletevos=QryDefdocvoInfo(filname[1]);
						 IDefdocService idefservice = NCLocator.getInstance().lookup(IDefdocService.class);
						
						 try {
					//		idefservice.deleteDefdocs(InvocationInfoProxy.getInstance().getGroupId(),deletevos);
							 for (int i = 0; i < deletevos.length; i++) {
								 DefdocVO defvo =deletevos[i];
								 defvo.setAttributeValue("enablestate", 3);//停用
								 idefservice.updateDefdocs(InvocationInfoProxy.getInstance().getGroupId(),new DefdocVO[] {deletevos[i]});
								 //删除中间表数据
								 ocrservice.deleteORC(defvo.getCode(), defvo.getName6(),0);
							 }
						} catch (Exception e1) {
							// TODO 自动生成的 catch 块
							e1.printStackTrace();
							MessageDialog.showErrorDlg(ThFileContentPanel.this, "提示","停用OCR档案【"+filname[1]+"】:\n"+e1.getMessage());
						}
						 
					}
				}
			});
			btnmove.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					getPatchInfoTable().setRowSelectionInterval(rowindex,
							rowindex);
					ThFileMoveDialog fdlg = new ThFileMoveDialog(
							ThFileContentPanel.this);
					fdlg.showModal();
				}

			});
		}

	}
	
	
	
	@SuppressWarnings("unchecked")
	private List<String> QryDefMemo(List<String> lisvdef20){
	 String[] arraydef20=lisvdef20.toArray(new String[0]);
	 List<String> arrayvos=new ArrayList<String>();
	 if(null==arraydef20||arraydef20.length==0){
		 return arrayvos; 
	 }
	 
	 SqlBuilder	sqlb=new SqlBuilder();
	 sqlb.append("select memo  ");
	 sqlb.append("from  bd_defdoc ");
	 sqlb.append("where nvl(dr, 0) = 0 and pk_defdoclist= ");
	 sqlb.append("(select pk_defdoclist ");
	 sqlb.append("from bd_defdoclist ");
	 sqlb.append("where code='OCRTHNC' and nvl(dr,0)=0) ");
	 sqlb.append("and ");
	 sqlb.append("pk_defdoc", arraydef20);
	 
	
	 try {
		IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
		ArrayList<String> objts=(ArrayList<String>) iuap.executeQuery(sqlb.toString(), new ColumnListProcessor("memo"));
		 if(null!=objts&&objts.size()>0){
			 arrayvos= objts;
		 }
	 } catch (BusinessException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
		MessageDialog.showErrorDlg(ThFileContentPanel.this, "提示","查询OCR参照报错！");
	 }
	
		return arrayvos;
	
    } 
	
	
	private DefdocVO[]  QryDefdocvoInfo(String name){
    	String sql = "select * from  bd_defdoc where  nvl(dr, 0) = 0 and pk_defdoclist="
    			+ "(select pk_defdoclist from bd_defdoclist where code='OCRTHNC' and nvl(dr,0)=0) and memo='" + name + "' ";
    	ArrayList<Object> arrayvos=null;
    	try {
    		IUAPQueryBS iuap= (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
			arrayvos=(ArrayList<Object>) iuap.executeQuery(sql, new BeanListProcessor(DefdocVO.class));
		} catch (BusinessException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
    	
    	if (arrayvos==null) {
  			return new DefdocVO[0];
  		}else {
  			return arrayvos.toArray(new DefdocVO[0]);
  		}
    	
    } 

	private class BtnTableCellRender implements TableCellRenderer {
		public BtnTableCellRender() {
			// FileManageMainUI.this.btnpanel.setOpaque(true);
			// FileManageMainUI.this.btnpanel.btndelete.setOpaque(true);
			// FileManageMainUI.this.btnpanel.btneidt.setOpaque(true);

		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			// table.setRowSelectionInterval(row, row);
			if (column == 5) {
				BtnPanel bp =new BtnPanel(row);
				bp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

				bp.setOpaque(true);
				if(isSelected){
					bp.setBackground(table.getSelectionBackground());
				}
				
				return bp;
			} else if (column == 1) {
				String strbtn = (value == null) ? "" : value.toString();
				HyperButton btn1 = new HyperButton(strbtn, strbtn);
				if(isSelected){
					btn1.setOpaque(true);
					btn1.setBackground(table.getSelectionBackground());
				}
				btn1.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						JOptionPane.showMessageDialog(null, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0013")/*预览*/);

					}

				});
				return btn1;
			}
			return null;
		}

	}

	private class BtnTableCellEditor extends DefaultCellEditor {
		private static final long serialVersionUID = 103249569489177021L;

		public BtnTableCellEditor(JCheckBox checkBox) {
			super(checkBox);

		}

		JLabel label = new JLabel();

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			table.setRowSelectionInterval(row, row);
			if (column == 5) {
				return new BtnPanel(row);
			} else if (column == 1) {
				String strbtn = (value == null) ? "" : value.toString();
				
//				NCFileVO file = (NCFileVO) getfiletablemodel().getVO(
//						row);
//				file.getTime()
				HyperButton btn1 = new HyperButton(strbtn, strbtn);
			
				btn1.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						// JOptionPane.showMessageDialog(null, "预览");
						int row = getPatchInfoTable().getSelectedRow();
						NCFileVO file = (NCFileVO) getfiletablemodel().getVO(
								row);

						String dsName = WorkbenchEnvironment.getInstance()
								.getLoginBusiCenter().getDataSourceName();
						try {
							//更新浏览次数（前台调用，是否该下载后台？）
							IFileSystemService ser= NCLocator.getInstance().lookup(IFileSystemService.class);
							ser.updateBrowseTimes(file.getFullPath());
							//前台浏览次数＋1
							int size=0;
							if(file.getScantimes()==Integer.MAX_VALUE){
								size=file.getScantimes();
							}else{
								size=file.getScantimes()+1;
							}
							file.setScantimes(size);
							//下载文件（）
							//如果URL直接打开
							if(file.getFiletype()!=null&&file.getFiletype().equalsIgnoreCase(FileTypeConst.URL)){
								//没必要在自己系统里判断自己附件安全，让加上就加上//TODO 捎个URL的DNS解析IP判断，不写了真没必要检查
								URL url = new URL(file.getPk_doc());
								List<String> list =null;
								list = getHostNameIP();
								//判断URL IP或者hostname,是否在本地IP list,或者 name list 中,
								//不在本地提示再打开
								if(!IsStrInListIgnoreCase( url.getHost(),list)){								
									if(MessageDialog.showOkCancelDlg(ThFileContentPanel.this,NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0018")/*警告*/,NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0017")/**/)== MessageDialog.ID_OK){
										ClientToolKit.showDocument(new URL(file.getPk_doc()), "_blank");
									}
								}else{//本地直接打开
									ClientToolKit.showDocument(new URL(file.getPk_doc()), "_blank");
								}
							}else{//如果文件下载打开
								FileManageServletClient.showFileInWeb(dsName, file
									.getFullPath(), file.getTime());
							}
						} catch (Exception e1) {
							MessageDialog.showErrorDlg(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("sftemp", "PasteAttachAction-0001")/*错误*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0014")/*浏览错误请查看日志！*/);
							Logger.error(e1);
						}

					}

				});
				return btn1;
			} else {
				label.setText((value == null) ? "" : value.toString());
				return label;
			}
		}

		@Override
		public void addCellEditorListener(CellEditorListener l) {

//			System.out.println("addCellEditorListener");
			super.addCellEditorListener(l);
		}

		@Override
		public void cancelCellEditing() {
//			System.out.println("cancelCellEditing");
			super.cancelCellEditing();
		}

		@Override
		public Object getCellEditorValue() {
			return "";
		}

		@Override
		public boolean isCellEditable(EventObject anEvent) {
			// 
			return super.isCellEditable(anEvent);
		}

		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			// 
			super.removeCellEditorListener(l);
		}

		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
//			System.out.println("cancelCellEditing");
			return super.shouldSelectCell(anEvent);
		}

		@Override
		public boolean stopCellEditing() {
			// 
			return super.stopCellEditing();
		}
		
	}
	public boolean CheckTheSameFileName(NCFileNode node ,String filename)
	{
		//加入 前台校验 ,判断是否存在同名 文件,同名不允许添加
		String nodepath = node.getFullPath();
		String combinepath =nodepath;
		if(!nodepath.endsWith("/")){
			combinepath=combinepath+"/";
		}
		Collection<NCFileVO> cltvo = getTreenodefilecacheMap().get(nodepath);
		if(cltvo!=null){
			for(NCFileVO filevo :cltvo){
				if(filevo.getFullPath().equalsIgnoreCase(combinepath+filename)){
					MessageDialog.showErrorDlg(this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("sftemp", "FileContentPanel-0015", null, new String[]{filename})/*文件名{0}重复，不能该文件上传！*/);
					return  true;
				}
			}
		}
		return false;
		
	}
	/**
	 * 新建文件夹，文件夹改名时，检查重复
	 * @param node
	 * @param foldername
	 * @return
	 */
	public boolean CheckTheSameFolderName(TreeNode node ,String foldername)
	{
		//加入 前台校验 ,判断是否存在同名 文件,同名不允许添加
		for(int noden=0; noden<node.getChildCount();noden++)
		{
			TreeNode subnode =node.getChildAt(noden);
			//如果选择node下有同名的node
			if(foldername.trim().equalsIgnoreCase(subnode.toString().trim()))
			{
				MessageDialog.showErrorDlg(ThFileContentPanel.this, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/, NCLangRes.getInstance().getStrByID("sfbase", "FileManageUI-000000", null, new String[]{foldername})/*文件存在:{0}*/);
				return  true;
			}
		}
		return false;
		
	}
	protected 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 (!getPatchTree().isRootVisible())
			index = 1;
		for (int i = index; i < count; i++) {
			if (sb.length() > 0)
				sb.append("/");
			sb.append(nodes[i]);
		}
		return sb.toString();
	}
	
	/**
	 * 不管用何种方式上传后，刷新树和表
	 * @param parentfoldernode
	 * @param newaddfilevo
	 */
	protected void nodeToFileVO(NCFileNode parentfoldernode, NCFileNode newaddfilevo) {
		NCFileVO newfilevo = new NCFileVO();
		String newpath = "";
		if(parentfoldernode.getFullPath().endsWith("/")){
			newpath=parentfoldernode.getFullPath();
		}else{
			newpath=parentfoldernode.getFullPath()+"/";
		}
		
		newfilevo.setPath(newpath+newaddfilevo.getFullPath());
		newfilevo.setCreator(newaddfilevo.getCreator());
		newfilevo.setTime(newaddfilevo.getTime());
		newfilevo.setFileLen(newaddfilevo.getFileLen());
		newfilevo.setFiletype(FileTypeConst.getFileTypeByFileName(newaddfilevo.getFullPath()));
		//刷新界面
		refreshUI(parentfoldernode, newfilevo);
	}

	protected void refreshUI(NCFileNode parentfoldernode, NCFileVO newfilevo) {
		//加入树缓存 
		ArrayList<NCFileVO> arr = new ArrayList<NCFileVO>();
		
		if(getTreenodefilecacheMap().get(parentfoldernode.getFullPath())!=null){
			arr.addAll(getTreenodefilecacheMap().get(parentfoldernode.getFullPath()));
		}
		arr.add(newfilevo);
		parentfoldernode.getFilemap().put(newfilevo.getFullPath(),newfilevo);
		getTreenodefilecacheMap().put(parentfoldernode.getFullPath(),arr);
		//如果不是根的话，选根时也能查看到，加入跟缓存	
		ArrayList<NCFileVO> arrroot = new ArrayList<NCFileVO>();
		if(getTreenodefilecacheMap().get("root")!=null){
		arrroot.addAll(getTreenodefilecacheMap().get("root"));
		}
		arrroot.add(newfilevo);
		getTreenodefilecacheMap().put("root",arrroot);
		if(!parentfoldernode.getFullPath().equalsIgnoreCase(rootDirStr)){
			// ... 不是根的操作？？？
			
		}else{			
			arr =(ArrayList<NCFileVO>) getTreenodefilecacheMap().get("root");
		}
		//刷新table
		if(PAGE_STATE==BROWSELISTTABLE_STATE){
			getfiletablemodel().clearTable();
			getfiletablemodel().addVO(arr.toArray(new NCFileVO[0]));
		}else{
			refreshUIbyClickTree();
		}
		//状态栏
		refreshStatuBar();
	}
	private class BottomBorder extends AbstractBorder{
		private static final long serialVersionUID = 1L;
		protected int left, right, top, bottom;
		public BottomBorder(int top, int left, int bottom, int right)   {
	        this.top = top; 
	        this.right = right;
	        this.bottom = bottom;
	        this.left = left;
	    
		}
		@Override
		public void paintBorder(Component c, Graphics g, int x, int y,int width, int height) {
		
			Color oldColor = g.getColor();
			g.setColor(Color.gray);
			g.drawLine(x, y+height-1, x+width, y+height-1);	
			g.setColor(oldColor);
//			g.drawLine(0, height, width, height);
			
		}
		 public Insets getBorderInsets(Component c)       {
		        return getBorderInsets();
		    }

		  
		    public Insets getBorderInsets(Component c, Insets insets) {
		        insets.left = left;
		        insets.top = top;
		        insets.right = right;
		        insets.bottom = bottom;
		        return insets;
		    }

		   
		    public Insets getBorderInsets() {
		        return new Insets(top, left, bottom, right);
		    }

		 
		    public boolean isBorderOpaque() { return true; }
		
	}
	
	
	/* begin 权限处理*/
	
	private boolean uploadenable= true;
		
	private boolean downloadenable = true;
		
	private boolean  deleteenable = true;
		
	private boolean  browseenable = true;
		
	private boolean  renameenable = true;
	private boolean  showenable = true;
	
	
	/**
	 * 
	 * @param validButton
	 */	
	public void setUploadFileEnable(boolean validButton) {
		uploadenable=validButton ;
		this.uploadAction.setEnabled(validButton);
		this.uprefaction.setEnabled(validButton);
		this.gpyaction.setEnabled(validButton);
		this.pasteaction.setEnabled(validButton);
		this.uploadurlaction.setEnabled(validButton);
		
	}

	public void setCreateNewFolderEnable(boolean validButton) {
		this.getNewfolderaction().setEnabled(validButton);
		this.getNewfolderPopAction().setEnabled(validButton);
	}

	public void setDeleteNodeEnable(boolean validButton) {
		
		//对于文件夹操作
		this.getDelfolderaction().setEnabled(validButton);
		getDelfolderPopAction().setEnabled(validButton);
		// 对于文件 删除怎么办
		//1(对于文件)设置全局标志 表示 是否可删除？？
		//2（对于文件） 刷新table？？
		this.deleteenable = validButton ;
	}

	public void setDownloadFileEnable(boolean validButton) {
		//1设置全局标志 表示 是否可删除？？
		//2 刷新table？？ 
		this.downloadenable = validButton;
		
		
	}

	public void setShowFileEnable(boolean validButton) {
		//1设置全局标志 表示 是否可删除？？
		//2 刷新table？？
		showenable = validButton;
		
	}

	public void setRenameNodeEnable(boolean validButton) {
		//
		this.renameenable = validButton ;
		this.getRenamefolderaction().setEnabled(validButton);
		this.getRenamefolderPopAction().setEnabled(validButton);
		this.getPatchTree().setEditable(validButton);
		//1设置全局标志 表示 是否可删除？？ 删除时判断提示
		//2 刷新table？？
		
	}
	/* end 权限处理*/
	
	public void setBilltypeComBoxEnable(boolean validButton){
		this.getComboxbilltype().setVisible(validButton);
	}
	/**
	 * 
	 * @param map 显示名，根路径值
	 */
	public void setBilltypeComBoxData(Map<String,String> map){
		this.getComboxbilltype().removeAllItems();
		for(String disname :map.keySet()){
			ItemObj item = new ItemObj(disname,map.get(disname));
			this.getComboxbilltype().addItem(item);
		}
		
	}
	public List<String> getHostNameIP(){
		List<String>  list = new ArrayList<String>();
		InetAddress addr;
		String hostname =null  ;
		try {
			addr = InetAddress.getLocalHost();
			hostname= addr.getHostName();
		} catch (UnknownHostException e) {
			Logger.error(e);
		}		
		
		list.add("127.0.0.1");
		list.add("localhost");
		if(hostname!=null){
			
			list.add(hostname);
			String [] arrip = getAllLocalHostIP(hostname);
			if(arrip!=null){
				list.addAll(Arrays.asList(arrip));
			}
		}
		return list ;
	}
	public String[] getAllLocalHostIP(String hostName) {
	    String[] ret = null;
	    try {
	        
	        if (hostName.length() > 0) {
	            InetAddress[] addrs = InetAddress.getAllByName(hostName);
	            if (addrs.length > 0) {
	                ret = new String[addrs.length];
	                for (int i = 0; i < addrs.length; i++) {
	                    ret[i] = addrs[i].getHostAddress();
	                }
	            }
	        }	 
        } catch (Exception ex) {
            ret = null;
        }
        return ret;
	}
	
	public boolean IsStrInListIgnoreCase(String str,List<String> list){
		boolean flag = false ;
		if(str==null||list==null){
			return flag ;
		}
		for(String s :list){
			if(s.equalsIgnoreCase(str)){
				flag = true ;
				break ;
			}
		}
		return flag ;
	}
}
