package com.engine.htsc.workflowFile.web;

import weaver.conn.RecordSet;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424SyncauthRequestUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.download.FileStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipInputStream;

public class UrlDownloadAction {

    @GET
    @Path("/download")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadByField(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        String fileId = request.getParameter("fileid");
        String iszip = "";
        String imageFileName = "";
        String fileRealPath = "";
        String sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.fileid = '"+fileId+"'";
        bs.writeLog("sql:"+sql);
        rs.execute(sql);
        if (rs.next())
        {
            imageFileName = Util.null2String(rs.getString("realname"));
            if (imageFileName.equals("")) {
                imageFileName = Util.null2String(rs.getString("imageFileName"));
            }
            fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            iszip = Util.null2String(rs.getString("isZip"));
        }

        bs.writeLog("imageFileName:"+imageFileName);
        bs.writeLog("fileRealPath:"+fileRealPath);
        bs.writeLog("iszip:"+iszip);
        InputStream is = null;
        try {

            if(!"".equals(imageFileName)){
                try {
                    imageFileName = URLEncoder.encode(imageFileName.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            File file = new File(fileRealPath);
            if(file.exists())
            {
                if (iszip.equals("1")) {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        is = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    is = new BufferedInputStream(new FileInputStream(file));
                }
            }else{
                boolean bool = QC969424Util.openQc969424();
                bs.writeLog("bool:"+bool);
                if (bool) {
                    QC969424RequestBaseUtil QC969424RequestBaseUtil = new QC969424RequestBaseUtil();
                    String token = QC969424Util.getToken();
                    if (token == null || "".equals(token)) {
                        QC969424RequestBaseUtil.getToken();
                    }
                    QC969424SyncauthRequestUtil qC969424SyncauthRequestUtil = new QC969424SyncauthRequestUtil();
                    is = qC969424SyncauthRequestUtil.download(fileId);
                }
            }

            return Response
                    .ok(is)
                    .header("Content-disposition","attachment;filename=" +imageFileName)
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }


    @GET
    @Path("/download1")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadByField1(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();

        String fileId = request.getParameter("fileid");
        String imageFileId = "";
        String imageFileName = "";
        String sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.fileid = '"+fileId+"'";
        bs.writeLog("sql:"+sql);
        rs.execute(sql);
        if (rs.next())
        {
            imageFileId = Util.null2String(rs.getString("imageFileId"));
            imageFileName = Util.null2String(rs.getString("imageFileName"));
            if (imageFileName.equals("")) {
                imageFileName = Util.null2String(rs.getString("realname"));
            }
        }
        bs.writeLog("imageFileId:"+imageFileId);
        try {


            QC969424RequestBaseUtil QC969424RequestBaseUtil = new QC969424RequestBaseUtil();
            String token = QC969424Util.getToken();
            if (token == null || "".equals(token)) {
                QC969424RequestBaseUtil.getToken();
            }

            InputStream is = ImageFileManager.getInputStreamById(Util.getIntValue(imageFileId));

            if(!"".equals(imageFileName)){
                try {
                    imageFileName = URLEncoder.encode(imageFileName.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return Response
                    .ok(is)
                    .header("Content-disposition","attachment;filename=" +imageFileName)
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }


    @GET
    @Path("/download2")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadByField2(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();

        String fileId = request.getParameter("fileid");
        String imageFileId = "";
        String imageFileName = "";
        String sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.fileid = '"+fileId+"'";
        bs.writeLog("sql:"+sql);
        rs.execute(sql);
        if (rs.next())
        {
            imageFileId = Util.null2String(rs.getString("imageFileId"));
            imageFileName = Util.null2String(rs.getString("imageFileName"));
            if (imageFileName.equals("")) {
                imageFileName = Util.null2String(rs.getString("realname"));
            }
        }

        bs.writeLog("imageFileId:"+imageFileId);
        try {

            QC969424RequestBaseUtil QC969424RequestBaseUtil = new QC969424RequestBaseUtil();
            String token = QC969424Util.getToken();
            if (token == null || "".equals(token)) {
                QC969424RequestBaseUtil.getToken();
            }

            ImageFileManager imageFileManager = new ImageFileManager();
            imageFileManager.getImageFileInfoById(Util.getIntValue(imageFileId));
            InputStream is = imageFileManager.getInputStreamById(Util.getIntValue(imageFileId));
            if(!"".equals(imageFileName)){
                try {
                    imageFileName = URLEncoder.encode(imageFileName.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return Response
                    .ok(is)
                    .header("Content-disposition","attachment;filename=" +imageFileName)
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }


    @GET
    @Path("/download3")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadByField3(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();

        String fileId = request.getParameter("fileid");
        String imageFileId = "";
        String imageFileName = "";
        String sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.fileid = '"+fileId+"'";
        bs.writeLog("sql:"+sql);
        rs.execute(sql);
        if (rs.next())
        {
            imageFileId = Util.null2String(rs.getString("imageFileId"));
            imageFileName = Util.null2String(rs.getString("imageFileName"));
            if (imageFileName.equals("")) {
                imageFileName = Util.null2String(rs.getString("realname"));
            }
        }

        bs.writeLog("imageFileId:"+imageFileId);
        try {

            QC969424RequestBaseUtil QC969424RequestBaseUtil = new QC969424RequestBaseUtil();
            String token = QC969424Util.getToken();
            if (token == null || "".equals(token)) {
                QC969424RequestBaseUtil.getToken();
            }

            InputStream is = null;
            boolean bool = QC969424Util.openQc969424();
            bs.writeLog("bool:"+bool);
            if (bool) {
                QC969424SyncauthRequestUtil qC969424SyncauthRequestUtil = new QC969424SyncauthRequestUtil();
                is = qC969424SyncauthRequestUtil.download(fileId);
            }

            if(!"".equals(imageFileName)){
                try {
                    imageFileName = URLEncoder.encode(imageFileName.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return Response
                    .ok(is)
                    .header("Content-disposition","attachment;filename=" +imageFileName)
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();

        } catch (Exception e) {
            e.printStackTrace();
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }


}
