package cn.com.qmth.examcloud.core.questions.base;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author chenken
 * @date 2017年7月17日 上午9:36:32
 * @company QMTH
 * @description FileUtil.java
 */
public class FileDisposeUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileDisposeUtil.class);

    /**
     * 将网络文件保存到本地
     *
     * @param fileUrl       网络文件URL
     * @param localFilePath 例如D:/123.txt
     * @return
     */
    public static boolean saveUrlAs(String fileUrl, String localFilePath) {
        HttpURLConnection connection = null;
        FileOutputStream fileOutputStream = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;
        try {
            URL url = new URL(fileUrl);
            connection = (HttpURLConnection) url.openConnection();
            dataInputStream = new DataInputStream(connection.getInputStream());
            fileOutputStream = new FileOutputStream(localFilePath);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = dataInputStream.read(buffer)) > 0) {
                dataOutputStream.write(buffer, 0, count);
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    fileOutputStream = null;
                }
                if (dataOutputStream != null) {
                    dataOutputStream.flush();
                    dataOutputStream.close();
                    dataOutputStream = null;
                }
                if (dataInputStream != null) {
                    dataInputStream.close();
                    dataInputStream = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
        }
    }

    /**
     * 下载服务器上的文件
     *
     * @param filename     文件名称
     * @param fullFilePath 文件全路径
     * @param response
     */
    public static void downloadFile(String filename, String fullFilePath, HttpServletResponse response) {
        InputStream in = null;
        OutputStream out = null;
        try {
            //设置编码
            response.setCharacterEncoding("UTF-8");
            //设置文件MIME类型
            response.setContentType(getContentType(filename));
            //设置Content-Disposition,名称强制为UTF-8
            //String fileEncode = System.getProperty("file.encoding");
            //response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(fileEncode),"UTF-8"));
            //response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")
                    .replace("%28", "(")
                    .replace("%29", ")"));
            // 设置强制下载不打开
            response.setContentType("application/octet-stream;charset=utf-8");
            //读取目标文件，通过response将目标文件写到客户端
            //获取目标文件的绝对路径
            //读取文件
            in = new FileInputStream(fullFilePath);
            out = response.getOutputStream();
            //写文件
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            response.flushBuffer();
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                    out = null;
                }
                if (null != in) {
                    in.close();
                    in = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

    }

    /**
     * 获得文件MIME类型
     *
     * @param filename
     * @return
     */
    public static String getContentType(String filename) {
        String type = null;
        Path path = Paths.get(filename);
        try {
            type = Files.probeContentType(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return type;
    }

    /**
     * 将存放在sourceFilePath目录下的源文件，打包成fileName名称的zip文件，并存放到zipFilePath路径下
     *
     * @param sourceFilePath :待压缩的文件夹路径
     * @param zipFilePath    :压缩后zip文件的存放路径
     * @param fileName       :zip文件的名称
     * @return
     */
    public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
        logger.info("压缩" + sourceFilePath + "目录开始");
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if (sourceFile.exists() == false) {
            logger.error("待压缩的文件目录：" + sourceFilePath + "不存在.");
        } else {
            try {
                File zipFile = new File(zipFilePath + File.separator + fileName + ".zip");
                if (zipFile.exists()) {
                    logger.error(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
                } else {
                    File[] sourceFiles = sourceFile.listFiles();
                    if (null == sourceFiles || sourceFiles.length < 1) {
                        logger.error("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
                    } else {
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
                            File file = sourceFiles[i];
                            if (!file.isFile()) {
                                continue;
                            }
                            try {
                                //创建ZIP实体，并添加进压缩包
                                String fileEncode = System.getProperty("file.encoding");
                                String name = new String(file.getName().getBytes(fileEncode), "UTF-8");
                                ZipEntry zipEntry = new ZipEntry(name);
                                zos.putNextEntry(zipEntry);
                                //读取待压缩的文件并写进压缩包里
                                fis = new FileInputStream(file);
                                bis = new BufferedInputStream(fis, 1024 * 10);
                                int read = 0;
                                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                                    zos.write(bufs, 0, read);
                                }
                                zos.flush();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                IOUtils.closeQuietly(bis);
                                IOUtils.closeQuietly(fis);
                            }
                        }
                        flag = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(fis);
                IOUtils.closeQuietly(zos);
                IOUtils.closeQuietly(fos);
            }
        }
        logger.info("压缩" + sourceFilePath + "目录完成");
        return flag;
    }

    public static void createDirectory(String downloadDirectory) {
        File directory = new File(downloadDirectory);
        if (!directory.exists()) {
            directory.mkdirs();
        } else {
            FileUtils.deleteQuietly(directory);
            directory.mkdirs();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
//		System.out.println(System.getProperty("sun.jnu.encoding"));
//		System.out.println(System.getProperty("file.encoding"));
        String fileName = "梦想(2)";

        System.out.println(URLEncoder.encode(fileName, "UTF-8")
                .replace("%28", "(")
                .replace("%29", ")"));
    }
}
