package market.Com.pb;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import market.Com.pb.fdfs.SpeOptService;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Download extends HttpServlet {    
	private static final long serialVersionUID = 123456L;   
	private String uploadDir = "c:/"; // 文件上传目录
	/**  
     * @see HttpServlet#HttpServlet()  
     */    
    public Download() {    
        super();    
    }    
    
    private ApplicationContext context;
    private SpeOptService IspeOptService;
    
    public void init() throws ServletException {
    	String uploadDir =this.getInitParameter("UploadDir");
    	// 给变量赋值
        this.uploadDir = uploadDir;
        
        context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		IspeOptService = (SpeOptService)context.getBean("speOptService");
    }
    
    /*public void setDefaultValue(String optType){
 	   if(optType=="default"){
 		   //默认的文件管理目录
 		  this.uploadDir=this.getInitParameter("uploadDir");
 	   }else if(optType=="knowledge"){
 		   //知识库文件管理目录
 		  this.uploadDir =this.getInitParameter("UploadDir");
 	   }
    }*/
    
   
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	try{
    		if (request.getCharacterEncoding() == null) {
                request.setCharacterEncoding("UTF-8");
            }
			request.setCharacterEncoding("UTF-8");
			String path=request.getParameter("path");
			String filename=request.getParameter("filename");
			String[] pathSplit = path.split("/");
			String str=URLDecoder.decode(path,"UTF-8");
			String strFileName=filename;//URLDecoder.decode(pathSplit[pathSplit.length-1],"UTF-8");
			String strSuffix=strFileName.split("\\.")[1];
			String range=request.getHeader("Range");
			/*
			String str=URLDecoder.decode(request.getParameter("fid"),"UTF-8");
			String strFileName=URLDecoder.decode(request.getParameter("oglName"),"UTF-8");
			String strSuffix=strFileName.split("\\.")[1];
			String range=request.getHeader("Range");
			//*/
			byte[] buffer=IspeOptService.downloadFile(str);  //FdfsTool.extByteData(str);
			
			if(range!=""&&range!=null){
				InputStream is=new ByteArrayInputStream(buffer);
				range=range.split("=")[1].split("-")[0];
        		long ran = Long.parseLong(range);
        		is.skip(ran);
        		buffer =new byte[(int) (is.available()-ran)];
        		is.read(buffer);
        		is.close();
			}
			// 清空response
	        response.reset();
	        // 设置response的Header
	        //response.addHeader("Content-Disposition", "attachment; filename="+new String(filename.getBytes("GBK"),"ISO8859_1"));
	        response.addHeader("Content-Disposition", "attachment; filename="+new String(strFileName.getBytes("GBK"),"ISO8859_1"));
	        response.addHeader("Content-Length", "" + buffer.length);
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        String contentType="application/octet-stream";
	        if(strSuffix.equals("ppt") || strSuffix.equals("pptx"))
	        	contentType="appication/powerpoint";
	        if(strSuffix.equals("doc") || strSuffix.equals("docx"))
	        	contentType="application/msword";
	        if(strSuffix.equals("pdf"))
	        	contentType="application/pdf";
	        response.setContentType(contentType);
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
		}catch(Exception e){
			e.printStackTrace();
		}
    }
    
    /*
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	//String optType = request.getParameter("optType");
 	   	//setDefaultValue(optType);
    	
    	request.setCharacterEncoding("UTF-8");
    	String path=URLDecoder.decode(request.getParameter("path"),"UTF-8");
    	//String path=strPath.replace("\\", "/");
    	try {
            // path是指欲下载的文件的路径。
            File file = new File(uploadDir+path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(uploadDir+path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment; filename="+new String(filename.getBytes("GBK"),"ISO8859_1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    //*/
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    }

}
