package weaver.file;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

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

import com.api.doc.detail.util.DocDownloadCheckUtil;
import weaver.conn.RecordSet;
import weaver.docs.docs.util.DesUtils;
import weaver.general.BaseBean;
import weaver.general.Util;


public class FileDownloadForOutDoc extends HttpServlet {
	private static final long serialVersionUID = 1L;
	

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	this.doGet(req,res);
    }
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		BaseBean bb = new BaseBean();
		String fileidStr = req.getParameter("fileid");
		bb.writeLog("FileDownloadForOutDoc-------->come in---->fileid:"+fileidStr);
		try{

			String isFromOutImg = Util.null2String(req.getParameter("isFromOutImg"));
			if("1".equals(isFromOutImg)){  //此为登录前POI预览转的图片预览，兼容历史数据，fileid未加密
				// 1.查询转html图片表  2.判断是否是登录前文档 3.判断附件来源是否为转html图片的
				RecordSet rs = new RecordSet();
				rs.executeQuery("select docId from DocPreviewHtmlImage where picFileId=?",fileidStr);
				if(rs.next()){
					//是poi转换后的图片，判断是否是登录前文档
					int docId = Util.getIntValue(rs.getString("docId"));
					if(docId > 0) {
						rs.executeQuery("select id from DocDetail d where d.id= ? and d.docpublishtype= 2",docId); //登录前门户，只取新闻类型
						if(rs.next()){
							//是登录前的
							rs.executeQuery("select COMEFROM from imagefile where imagefileid=?",fileidStr);
							if(rs.next()){
								String comefrom = Util.null2String(rs.getString(1));
								if(!"DocPreviewHtmlImage".equals(comefrom)){
									//如果不是通过html转换的图片，返回。
									bb.writeLog("FileDownloadForOutDoc-------->isFromOutImg---->comefrom:"+comefrom);
									return;
								}
							}else {
								bb.writeLog("FileDownloadForOutDoc-------->isFromOutImg---->imagefile表中无数据");
								return;
							}
						}else {
							bb.writeLog("FileDownloadForOutDoc-------->isFromOutImg---->不是登录前文档");
							return;
						}
					}else {
						bb.writeLog("FileDownloadForOutDoc-------->isFromOutImg---->DocPreviewHtmlImage查询文档id<=0");
						return;
					}
				}else {
					bb.writeLog("FileDownloadForOutDoc-------->isFromOutImg---->DocPreviewHtmlImage查询无数据");
					return;
				}
			}else {
				DesUtils des = new DesUtils();
				fileidStr = des.decrypt(fileidStr);
			}
			
			int fileid = 0;
			int docid = 0;
			
			if(fileidStr.contains("-")){
				fileid = Util.getIntValue(fileidStr.split("-")[0]);
				docid = Util.getIntValue(fileidStr.split("-")[1]);
			}else{
				fileid = Util.getIntValue(fileidStr.split("-")[0]);
			}
			if(fileid<=0){
				String fileidStr2=DocDownloadCheckUtil.getDownloadfileidstr(fileidStr.split("-")[0]);
				//new weaver.general.BaseBean().writeLog("--------------fileidStr2="+fileidStr2);
				fileid=Util.getIntValue(fileidStr2,-1);
			}
			
			doload(fileid,docid,req,res);
		}catch(Exception e){
			 new BaseBean().writeLog("^^^^^^^^^^^^^^^^^^^^^^^("+fileidStr+")error=" + e);
		}

	}
	
	
	public void doload(int fileid,int docid, HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException{
		RecordSet rs = new RecordSet();
		boolean isskip = "wechat".equals(Util.null2String(req.getParameter("downloadfrom")));
		//过滤 查看登录前文档时，html中的图片等内容无法加载
		boolean isFromOutDoc = "1".equals(Util.null2String(req.getParameter("isFromOutDoc")));

		boolean fromhtmlview = "1".equals(Util.null2String(req.getParameter("fromhtmlview")));
		String isFromOutImg = Util.null2String(req.getParameter("isFromOutImg"));

		String sql = "select f.isextfile,f.docfiletype from DocImageFile f,DocDetail d where d.id=f.docid and f.imagefileid=?";
		sql += " and d.docpublishtype=? and (d.ishistory is null or d.ishistory = 0) and d.docstatus in(1,2,5)";   //登录前门户，只取新闻类型
		
		rs.executeQuery(sql,fileid,"2");
		
		if(!rs.next()){  //原开发已离职，经沟通，根据isskip参数判断是否为图片
			sql = " select 1 from docdetail where id = ? and themeshowpic=? ";
			RecordSet rs2 = new RecordSet();
			rs2.executeQuery(sql,docid,fileid);
			if(!rs2.next()){
				if(isFromOutDoc){
					//登录前文档中的html图片，增加 登录前文档的前提校验
					String docidStr = Util.null2String(req.getParameter("docid"));
					rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^isFromOutDoc--- docidStr:"+docidStr);
					try {
						DesUtils des = new DesUtils();
						String _docid = des.decrypt(docidStr);
						rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^isFromOutDoc--- _docid:"+_docid);
						sql = "select id from DocDetail d where d.id=? and d.docpublishtype=? and (d.ishistory is null or d.ishistory = 0) and d.docstatus in(1,2,5) union all select  docid from docshareoutrecord where docid=?";   //登录前门户，只取新闻类型与外部分享文档
						rs.executeQuery(sql,_docid,"2",_docid);
						if(!rs.next()){
							rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^isFromOutDoc 没有权限 (" + fileid + ")(" + docid + ")^^^^^^^^^^^^");
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if("1".equals(isFromOutImg)){
					rs.executeQuery("select t2.imagefileid from DocPreviewHtmlImage t1, imagefile t2 where t1.picFileId = ? and t1.imageFileId = t2.imagefileid",fileid);
					if(!rs.next()){
						rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^isFromOutImg 没有权限 (" + fileid + ")^^^^^^^^^^^^");
						return;
					}
				}else if(fromhtmlview){
					rs.executeQuery("select t2.imagefilename from DocPreviewHtml t1, imagefile t2 where t1.htmlFileId = ? and t1.imageFileId = t2.imagefileid", fileid);
					if(!rs.next()){
						rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^fromhtmlview 没有权限 (" + fileid + ")(" + docid + ")^^^^^^^^^^^^");
						return;
					}
				}else if(isskip){
                    ImageFileManager ifm = new ImageFileManager();
                    ifm.resetParameter();
                    ifm.getImageFileInfoById(fileid);
                    String imageFileName = ifm.getImageFileName();
                    String extname = imageFileName.contains(".") ? imageFileName.substring(imageFileName.lastIndexOf(".") + 1) : "";
                    extname = extname.toLowerCase();
                    if(extname.equals("jpg") || extname.equals("jpeg") || extname.equals("gif") || extname.equals("png")
                            || extname.equals("bmp") || extname.equals("bpm")){
                        //图片跳过
                    }else {
                        rs.writeLog("FileDownloadForOutDoc^^^^^^^^^^^isskip^^^^^^没有权限 (" + fileid + ")(" + docid + ")^^^^extname:"+extname);
                        return;
                    }
                }else {
					rs.writeLog("^^^^^^^^^^^ 没有权限 (" + fileid + ")(" + docid + ")^^^^^^^^^^^^");
					return;
				}
			}
		}
		sql = "select f.isextfile,f.docfiletype from DocImageFile f,DocDetail d where d.id=f.docid and f.imagefileid=?";
		rs.executeQuery(sql,fileid);
		boolean inline = false;
		if(rs.next()){
          inline = !"1".equals(rs.getString("isextfile")) && "1".equals(rs.getString("docfiletype"));
		}
		String frompdfview = Util.null2String(req.getParameter("frompdfview"),"0");
		if(!inline){
			if(frompdfview.equals("1") || fromhtmlview ){
				inline = true;
			}
		}

		String htmlCharset = "GBK";
		if(fromhtmlview){
			inline = true;
			rs.executeQuery("select t2.imagefilename from DocPreviewHtml t1, imagefile t2 where t1.htmlFileId = ? and t1.imageFileId = t2.imagefileid", fileid);
			if(rs.next()){
				String imagefilename = Util.null2String(rs.getString(1));
				htmlCharset = imagefilename.toLowerCase().endsWith(".docx")?"utf-8":htmlCharset;
			}

		}
		
		ImageFileManager ifm = new ImageFileManager();
		ifm.resetParameter();
		ifm.getImageFileInfoById(fileid);
		InputStream imagefile = ifm.getInputStream();
		String filename = ifm.getImageFileName();
		
		
		String agent = req.getHeader("user-agent");
//    	res.addHeader("Content-Length", "" + ifm.getFilesize());
		String contenttype = "application/octet-stream";
		
		if(inline){
			 if(filename.toLowerCase().endsWith(".gif")) {
                 contenttype = "image/gif";
                 res.addHeader("Cache-Control", "private, max-age=8640000");
             }else if(filename.toLowerCase().endsWith(".png")) {
                 contenttype = "image/png";
                 res.addHeader("Cache-Control", "private, max-age=8640000");
             }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) {
                 contenttype = "image/jpg";
                 res.addHeader("Cache-Control", "private, max-age=8640000");
             }else if(filename.toLowerCase().endsWith(".bmp")) {
                 contenttype = "image/bmp";
                 res.addHeader("Cache-Control", "private, max-age=8640000");
             }else if(filename.toLowerCase().endsWith(".svg")){
                 contenttype = "image/svg+xml";
                 res.addHeader("Cache-Control", "private, max-age=8640000");
             }else if(filename.toLowerCase().endsWith(".pdf")){
				 contenttype = "application/pdf";
			 }else if(filename.toLowerCase().endsWith(".html") || filename.toLowerCase().endsWith(".htm")){
				 contenttype = "text/html;charset="+htmlCharset;
			 }
		}
		
        try {
             if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){
                 res.setHeader("content-disposition", (inline ? "inline" : "attachment") + "; filename*=UTF-8''" +  URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")"));
             }else{
                 res.setHeader("content-disposition", (inline ? "inline" : "attachment") + "; filename=\"" +
                         URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\"");
             }
         } catch (Exception ecode) {
         }
		
        if(imagefile != null){
			ServletOutputStream out = null;
	        try {
	             out = res.getOutputStream();
	             res.setContentType(contenttype);
	             int byteread = 0;
	             byte []data = new byte[2048];
	             while ((byteread = imagefile.read(data)) != -1) {
	                 out.write(data, 0, byteread);
	                 out.flush();
	             }
	        }catch(Exception e) {
	        	 rs.writeLog("^^^^^^^^^^^^^^^^^^^^^^^error=" + e);
	             e.printStackTrace();
	        }finally {
	             if(imagefile!=null) imagefile.close();
	             if(out!=null) out.flush();
	             if(out!=null) out.close();
	        }
        }
		
	}
	
}
