package com.engine.htsc.workflowFile.web;


import com.api.doc.detail.util.DocDownloadCheckUtil;
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.activation.MimetypesFileTypeMap;
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.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 SysDownloadAction {
    @GET
    @Path("/download")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response download(@Context HttpServletRequest req, @Context HttpServletResponse res){
        BaseBean bs = new BaseBean();
        String imagefileid = req.getParameter("imagefileid");
        String type = req.getParameter("type");
        bs.writeLog("imagefileid:"+imagefileid);
        bs.writeLog("type:"+type);
        if("1".equals(type)){
            int imagefileid_ = DocDownloadCheckUtil.getDownloadfileid(imagefileid);
            imagefileid = Util.null2String(imagefileid_);
        }
        RecordSet rs = new RecordSet();
        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.imagefileid =  " + imagefileid;
        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);

//        String imageFileName ="" ;
//        imageFileName = "426de927-2d9b-4fb7-9179-9ab8e78ac1ca.zip";
//        String fileRealPath = "/app/ecology/filesystem/202104/I/426de927-2d9b-4fb7-9179-9ab8e78ac1ca.zip";

        try {
            FileStream fileStream = new FileStream(fileRealPath,iszip);
            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();
                }
            }

//            ByteArrayOutputStream output = new ByteArrayOutputStream();
//            byte[] buffer = new byte[4096];
//            int n = 0;
//            while (-1 != (n = inputStream.read(buffer))) {
//                output.write(buffer, 0, n);
//            }

//            ByteArrayOutputStream output = new ByteArrayOutputStream();
//            byte buff[] = new byte[4096];
//            int len = 0;
//            while ((len = inputStream.read(buff)) != -1) {
//                output.write(buff, 0, len);
//            }
//            output.flush();
//            output.toByteArray();

//            byte[] bytes = IOUtils.toByteArray(inputStream);
//            byte[] array = inputStream.readAllBytes();

//            DataInputStream dis = new DataInputStream(inputStream);
//            dis.readFully(bytes);
            return Response
                    .ok(fileStream)
                    .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("/downloadforzw")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadForZw(@Context HttpServletRequest req, @Context HttpServletResponse res){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        String docid = Util.null2String(req.getParameter("docid"));
        String imagefileid = "" ;
        if(!"".equals(docid)){
            String sql = " select imagefileid from docimagefile where docid = "+docid;
            rs.execute(sql);
            if(rs.next()){
                imagefileid = Util.null2String(rs.getString("imagefileid"));
            }
        }
        bs.writeLog("imagefileid:"+imagefileid);

        String iszip = "";
        String imageFileName = "";
        String fileRealPath = "";
        if(!"".equals(imagefileid))
        {
            String type = req.getParameter("type");
            bs.writeLog("imagefileid:"+imagefileid);
            bs.writeLog("type:"+type);
            if("1".equals(type)){
                int imagefileid_ = DocDownloadCheckUtil.getDownloadfileid(imagefileid);
                imagefileid = Util.null2String(imagefileid_);
            }

            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.imagefileid =  " + imagefileid;
            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);
        }

//        String imageFileName ="" ;
//        imageFileName = "426de927-2d9b-4fb7-9179-9ab8e78ac1ca.zip";
//        String fileRealPath = "/app/ecology/filesystem/202104/I/426de927-2d9b-4fb7-9179-9ab8e78ac1ca.zip";

        try {
            FileStream fileStream = new FileStream(fileRealPath,iszip);
            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(fileStream)
                    .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("/downloadzip")
    public Response downloadzip(@Context HttpServletRequest req, @Context HttpServletResponse res){
        BaseBean bs = new BaseBean();

        String imagefileid = req.getParameter("imagefileid");
        String type = req.getParameter("type");
        bs.writeLog("imagefileid:"+imagefileid);
        bs.writeLog("type:"+type);
        if("1".equals(type)){
            int imagefileid_ = DocDownloadCheckUtil.getDownloadfileid(imagefileid);
            imagefileid = Util.null2String(imagefileid_);
        }
        RecordSet rs = new RecordSet();
        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.imagefileid =  " + imagefileid;
        rs.execute(sql);
        if (rs.next())
        {
            fileRealPath = Util.null2String(rs.getString("fileRealPath"));
        }
        if(!"".equals(fileRealPath)){
            imageFileName = imageFileName.substring(imageFileName.lastIndexOf("/")+1);
            bs.writeLog("imageFileName:"+imageFileName);
        }
        File file = new File(fileRealPath);
        String mt = new MimetypesFileTypeMap().getContentType(file);
        bs.writeLog("mt:"+mt);
        try {
            return Response
                    .ok(file,mt)
                    .header("Content-disposition","attachment;filename=" +URLEncoder.encode(imageFileName, "UTF-8"))
                    .header("ragma", "No-cache")
                    .header("Cache-Control", "no-cache").build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }




    @GET
    @Path("/downloadbyte")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public byte[] downloadbyte(@Context HttpServletRequest req, @Context HttpServletResponse res){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        BufferedInputStream inputStream = null;
        try {
            String imagefileid = Util.null2String(req.getParameter("imagefileid"));
            String type = Util.null2String(req.getParameter("type"));
            bs.writeLog("imagefileid:"+imagefileid);
            bs.writeLog("type:"+type);
            if("1".equals(type)){
                int imagefileid_ = DocDownloadCheckUtil.getDownloadfileid(imagefileid);
                imagefileid = Util.null2String(imagefileid_);
            }
            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.imagefileid =  " + imagefileid;
            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("iszip:"+iszip);
            bs.writeLog("fileRealPath:"+fileRealPath);

            if (fileRealPath != null && !fileRealPath.equals(""))
            {
                File file = new File(fileRealPath);
                if (iszip.equals("1")) {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        inputStream = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                }
            }

            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();
                }
            }

            // 读取文件流
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[4096];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();
            byte[] byteArray = buffer.toByteArray();

            res.setHeader("Content-Disposition", "attachment" + "; filename=\"" + imageFileName +"\"");
            res.addHeader("content-type","application/octet-stream");

            inputStream.close();
            buffer.close();
            return byteArray;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if(inputStream !=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @GET
    @Path("/downloadsg")
    @Produces({MediaType.APPLICATION_OCTET_STREAM})
    public Response downloadsg(@Context HttpServletRequest req, @Context HttpServletResponse res){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        String imagefileid = req.getParameter("imagefileid");
        if(!"".equals(imagefileid)){
            String type = req.getParameter("type");
            bs.writeLog("imagefileid:"+imagefileid);
            bs.writeLog("type:"+type);
            if("1".equals(type)){
                int imagefileid_ = DocDownloadCheckUtil.getDownloadfileid(imagefileid);
                imagefileid = Util.null2String(imagefileid_);
            }
            //InputStream is = null;
            try {
//                ImageFileManager imageFileManager = new ImageFileManager();
//                imageFileManager.getImageFileInfoById(Util.getIntValue(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.imagefileid =  " + imagefileid;
                bs.writeLog("sql:"+sql);
                rs.execute(sql);
                if (rs.next())
                {
                    imageFileName = Util.null2String(rs.getString("imageFileName"));
                    if (imageFileName.equals("")) {
                        imageFileName = Util.null2String(rs.getString("realname"));
                    }
                }

//                ImageFileManager imageFileManager = new ImageFileManager();
//                imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid));
//                InputStream is = imageFileManager.getInputStreamById(Util.getIntValue(imagefileid));



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

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


//                boolean bool = QC969424Util.openQc969424();
//                if (bool) {
//                    QC969424SyncauthRequestUtil qC969424SyncauthRequestUtil = new QC969424SyncauthRequestUtil();
//                    inputStream = qC969424SyncauthRequestUtil.download(fileid);
//                    if (inputStream != null)
//                        return inputStream;
//                }

                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();
            }finally {
//                if(is !=null){
//                    try {
//                        is.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
            }
        }else{
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }


//    public static byte[] toByteArray(InputStream input) throws IOException {
//        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
//        int nRead;
//        byte[] data = new byte[1024];
//        while ((nRead = input.read(data, 0, data.length)) != -1) {
//            buffer.write(data, 0, nRead);
//        }
//        buffer.flush();
//        byte[] byteArray = buffer.toByteArray();
//        return byteArray;
//    }

}
