package nc.pub.filesystem.newui;

import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import nc.itf.th.IThOcrService;
import nc.bs.framework.common.RuntimeEnv;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.funcnode.ui.action.AbstractNCAction;
import nc.log.NcLog;
import nc.ui.ml.NCLangRes;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pub.filesystem.FileManageServletClient;
import nc.vo.pub.filesystem.NCFileNode;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;


public class ThUploadAction extends AbstractNCAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ThFileContentPanel parentpanel ;
	public ThUploadAction(ThFileContentPanel para){
		parentpanel = para;
		this.putValue(AbstractAction.NAME,NCLangRes.getInstance().getStrByID("sftemp", "UploadAction-0000")/*上传附件*/);
		this.putValue(Action.SHORT_DESCRIPTION, NCLangRes.getInstance().getStrByID("sftemp", "UploadAction-0000")/*上传附件*/);
//		this.putValue(AbstractAction.SMALL_ICON, ClientToolKit.loadImageIcon("images/filesystem/newfolder.png"));
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (parentpanel.rootNode == null) {
			return;
		}
		TreePath path = parentpanel.getPatchTree().getSelectionPath();
		if (path == null) {
			path = new TreePath(parentpanel.rootNode.getPath());
		}
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
		
		JFileChooser chooser = new JFileChooser();
		//要求上传多个文件
		chooser.setMultiSelectionEnabled(true);
		if (chooser.showOpenDialog(parentpanel) == JFileChooser.APPROVE_OPTION) {
			String pPath = "";
			if (node instanceof NCFileNode) {
				pPath = ((NCFileNode) node).getFullPath();
			}
//			File file = chooser.getSelectedFile();
			//多文件上传
			File[] arrfiles = chooser.getSelectedFiles();
			if(arrfiles==null ||arrfiles.length==0){
				//没有选择文件退出
				return;
			}
			
			String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter().getDataSourceName();
			
			String creator = WorkbenchEnvironment.getInstance().getLoginUser().getCuserid();
			FileInputStream input = null;
			FileInputStream testinput = null;
			
			IThOcrService  ocrservice=(IThOcrService) NCLocator.getInstance().lookup(IThOcrService.class.getName());
				
			
			try {
				for(File file :arrfiles){
					String fileName = file.getName();
					//校验是否同名
					if(parentpanel.CheckTheSameFileName((NCFileNode)node, fileName)){
						continue ;
					}
					//检查 附件大小 ,文件超过  参数设置的大小不能上传
					long size =(long)FileBroseConst.getfilelimit()*1024L*1024L;
					if(size<file.length()){
						MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("sftemp", "UploadAction-0001")/*文件超过限制*/, NCLangRes.getInstance().getStrByID("sftemp", "UploadAction-0002", null, new String[]{fileName})/*{0}大小超过限制不能上传！*/);
						continue ;
					}
					input = new FileInputStream(file);
					testinput = new FileInputStream(file);
//					String absolutePath = file.getAbsolutePath();
//					MessageDialog.showHintDlg(parentpanel, "提示","absolutePath:"+absolutePath);
//					String pathww = file.getPath();
//					MessageDialog.showHintDlg(parentpanel, "提示","pathww:"+pathww);
					/***********************发票图片保存到文件夹 home/uploadfile/"+vdef17+"  ****************************/
					BillCardPanel cpanel=parentpanel.editor_.getBillCardPanel();
					String vdef17 = (String) cpanel.getHeadItem("vdef17").getValueObject();
					//add by pcy
					//把附件保存到文件资源管理器
//					String filepath = ocrservice.UploadFile(vdef17, file);
//					String filepath =  ocrservice.getNCHomePath()
//						      +File.separator +"uploadfile" + File.separator+ vdef17; // 文件保存的路径
//					File folder = new File(filepath);
//					if(!folder.exists() && !folder.isDirectory()){
//						folder.mkdirs();
//					}
//					String newFileName = filepath + File.separator + fileName;
//					FileOutputStream outputStream = new FileOutputStream(newFileName);
//					FileInputStream fis = new FileInputStream(file);
//			        byte[] buffer = new byte[1024];
//			        int len;
//			        while ((len = fis.read(buffer)) != -1) {
//			            outputStream.write(buffer, 0, len);
//			        }
//			        outputStream.close();
//			        fis.close();
					
					NCFileNode newNode = FileManageServletClient.uploadFile(dsName, pPath, fileName, testinput, creator, file.length());
					if (newNode != null) {
//						NCFileVO  newfilevo = new NCFileVO();
//						newfilevo.set
//						newfilevo.setPath(newpath+newaddfilevo.getFullPath());
//						newfilevo.setCreator(newaddfilevo.getCreator());
//						newfilevo.setTime(newaddfilevo.getTime());
//						newfilevo.setFileLen(newaddfilevo.getFileLen());
						parentpanel.nodeToFileVO((NCFileNode)node, newNode);
					}
					
					//转为byte传输
					BufferedInputStream bis=new BufferedInputStream(input);
                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
					int date=-1;
					while ((date = bis.read()) != -1) {
						bos.write(date);
			        }
					byte[] 	bytes=	bos.toByteArray();
					
					String patch=ocrservice.saveUploadFile(vdef17, fileName, bytes);//保存发票到home里
			
				}
			} catch (Exception ex) {
				Logger.error(ex.getMessage(), ex);
				MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/,ex.getMessage()/*上传时发生错误！*/);
				//MessageDialog.showErrorDlg(parentpanel, NCLangRes.getInstance().getStrByID("pc", "FileManageUI-000000")/*错误*/,NCLangRes.getInstance().getStrByID("sftemp", "UploadAction-0003")/*上传时发生错误！*/);
			} finally {
				try {
					if (input != null) {
						input.close();
					}
				} catch (Exception e2) {
				}
			}
		}
	
	}
}
