package com.ced.sip.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletException;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.base.utils.GlobalSettingBase;
import com.ced.sip.common.biz.IAttachmentBiz;
import com.ced.sip.common.entity.Attachment;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.FtpUtil;

public class AttachmentDownloadAction extends BaseAction {
						
	private static final Log log = LogFactory.getLog(AttachmentDownloadAction.class);
    //上传文件存放路径   
    private final static String UPLOADDIR = "upload/";
	private IAttachmentBiz iAttachmentBiz ;
	private Attachment attach ;
	
	private File uploadify;   
	private String uploadifyContentType;   
	private String uploadifyFileName; 
	private static String fileType = "";
	private static String uuId = "";
	
	private File fileLocation;
	
	/**   
	  * 配合swfupload插件使用的上传方法。   
	  * @author luguanglei   
	  * @return   
	  * @throws Exception    
	*/   
	public String uploadify() throws BaseException {   
    	PrintWriter out;
		try {
			
			String attachmentType=this.getRequest().getParameter("attachmentType");
			out = this.getResponse().getWriter(); 
			if(uploadify!=null){
			FtpUtil ftpUtil = new FtpUtil();
			ftpUtil.uploadFile(getAttachmentPath(attachmentType),new FileInputStream(uploadify), getOperatorFileName(uploadifyFileName));
			}
			JSONObject node = new JSONObject(); 
			node.put("fileType", fileType);
			node.put("uuId", uuId);
			node.put("fileName", uploadifyFileName);
			out.print(node.toString());
			
		} catch (Exception iox) {
			log(" 上传附件错误！", iox);
			throw new BaseException(" 上传附件错误！", iox);

		}		
    	return null;   
    }   
	/**   
	  * 配合swfupload插件使用的上传方法。   
	  * @author luguanglei   
	  * @return   
	  * @throws Exception    
	*/   
	public String uploadifyImg() throws BaseException {   
   	PrintWriter out;
		try {
			
			String attachmentType=this.getRequest().getParameter("attachmentType");
			out = this.getResponse().getWriter(); 
			String imgUrl="",fileType="",path=getAttachmentImgPath(UPLOADDIR+attachmentType);  
            if(uploadify!=null){
				InputStream in = new FileInputStream(uploadify);   
	            String dir = GlobalSettingBase.getFilePath()+path;
	            isExist(dir);
	            int index = uploadifyFileName.lastIndexOf(".");
	    		if (index > -1) {
	    			fileType =uploadifyFileName.substring(index);
	    		}
	    		fileType=fileType.toLowerCase().substring(1);
	    		Random random = new Random();
	    		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数 
				String cjrq = new SimpleDateFormat("HHmmss")
						.format(new Date());
				String fjTpName = cjrq+rannum + "." + fileType;// 文件的名字
	            File uploadFile = new File(dir, fjTpName);   
	            imgUrl=path+fjTpName;
	            OutputStream outs = new FileOutputStream(uploadFile);   
	            byte[] buffer = new byte[1024 * 1024];   
	            int length;   
	            while ((length = in.read(buffer)) > 0) {   
	            	outs.write(buffer, 0, length);   
	            }   
	            in.close();   
	            outs.close();   
            }
            //System.out.println(imgUrl);
			out.print(imgUrl);
			
		} catch (Exception iox) {
			log(" 上传图片错误！", iox);
			throw new BaseException(" 上传图片错误！", iox);

		}		
   	return null;   
   }
	/**
	 * 下载附件-公用方法
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws Exception
	 */
	public String download( ) throws BaseException { 
		
		FtpUtil ftpUtil = new FtpUtil();
		try {
			
			this.getRequest().setCharacterEncoding("utf-8");
			
			String filerealpath = "";
			String filename = "";
			if ( attach != null) {
				Attachment attachment = iAttachmentBiz.getAttachment( attach.getAttachmentId() ) ; 
				filerealpath = iAttachmentBiz.getAttachmentPath( attachment );
				filename = FtpUtil.getOperatorFileName(attachment);
							
				if(!ftpUtil.downloadFile(filerealpath, filename,attachment.getAttachmenetName(),this.getResponse())){
					//下载失败，文件不存在
					getResponse().sendError(404, "文件不存在");
				}
				
			}
			log.debug("开始返回 了");
		} catch (Exception iox) {
			log(" 下载附件错误！", iox);
			throw new BaseException(" 下载附件错误！", iox);

		}
		
		return null ;
	}

	/**
	 * 获取附件的上传路径-相对 
	 * @param attachment
	 * @return
	 */
	public String getAttachmentPath(String attachmentType) {

		StringBuffer path = new StringBuffer( GlobalSettingBase.getAttachmentUploadLoaction() ) ;

		String year  = DateUtil.getYear(new Date());
		String month = DateUtil.getMonth(new Date());

		// 附件存放在以时间命名的文件夹中,
		path.append( File.separator ) ;
		path.append( attachmentType ) ;
		path.append( File.separator ) ;
		path.append( year ) ;
		path.append( File.separator ) ;
		path.append( month ) ;
		path.append( File.separator ) ;
		
		return path.toString() ;
	}
	/**
	 * 获取附件的上传路径-相对 
	 * @param attachment
	 * @return
	 */
	public String getAttachmentImgPath(String attachmentType) {

		StringBuffer path = new StringBuffer("") ;

		String year  = DateUtil.getYear(new Date());
		String month = DateUtil.getMonth(new Date());

		// 附件存放在以时间命名的文件夹中,
		path.append( attachmentType ) ;
		path.append( "/" ) ;
		path.append( year ) ;
		path.append( "/" ) ;
		path.append( month ) ;
		path.append( "/" ) ;
		
		return path.toString() ;
	}
	/**
	 * 
	 * @param attachment
	 * @return
	 */
	public static String getOperatorFileName(String  uploadifyFileName) {
		int index = uploadifyFileName.lastIndexOf(".");
		if (index > -1) {
			fileType =uploadifyFileName.substring(index);
		}
		fileType=fileType.toLowerCase().substring(1);
		uuId=UUID.randomUUID()+"";
		return uuId +"."+ fileType;

	}
	/**
     * 判断文件夹是否存在
     * @param path 文件夹路径
     * true 文件不存在，false 文件存在不做任何操作
     */
    public void isExist(String filePath) {
        String paths[] = filePath.split("/");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
                dir = dir + "/" + paths[i + 1];
                fileLocation = new File(dir);
                if (!fileLocation.exists()) {
                	fileLocation.mkdir();
                }
        }
    }
	public IAttachmentBiz getIAttachmentBiz() {
		return iAttachmentBiz;
	}

	public void setIAttachmentBiz(IAttachmentBiz attachmentBiz) {
		iAttachmentBiz = attachmentBiz;
	}

	public Attachment getAttach() {
		return attach;
	}

	public void setAttach(Attachment attach) {
		this.attach = attach;
	}

	public IAttachmentBiz getiAttachmentBiz() {
		return iAttachmentBiz;
	}

	public void setiAttachmentBiz(IAttachmentBiz iAttachmentBiz) {
		this.iAttachmentBiz = iAttachmentBiz;
	}
    
	public File getUploadify() {
		return uploadify;
	}

	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	public String getUploadifyContentType() {
		return uploadifyContentType;
	}

	public void setUploadifyContentType(String uploadifyContentType) {
		this.uploadifyContentType = uploadifyContentType;
	}

	public String getUploadifyFileName() {
		return uploadifyFileName;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}
	
	
	
	
}