package com.chinada.dms.controller.common;

import com.chinada.dms.configure.BootdoConfig;
import com.chinada.dms.utils.FileUtil;
import com.chinada.dms.utils.UploadUtils;
import com.sys.lib.exception.ServiceErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
/*import sun.misc.BASE64Encoder;*/


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 下载--公共接口
 *  ysp
 *  2019-6-2
 */
@RestController
@RequestMapping(value = "/img/common")
public class DownloadController {
    @Autowired
    private BootdoConfig bootdoConfig;
    public static   List<String> filelist;
    //【第一版批量下载】
    @RequestMapping(value = "/downloadList", method = RequestMethod.GET)
    @ResponseBody
    public void downloadList(HttpServletRequest request, HttpServletResponse response, String filePath){
        filelist=new ArrayList<>();;//全局变量置空
        String filePlace=bootdoConfig.getUploadPath()+"inquisitorMgr";
        String zipName = "download.zip";
        String zipFilePath = filePlace+zipName;
       List<String> list=getFileList(filePlace);
        try{
            //压缩文件
            File zip = new File(zipFilePath);
            if (!zip.exists()){
                zip.createNewFile();
            }
            //创建zip文件输出流
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
            this.zipFile(filePlace,zipName, zipFilePath,list,zos);
            zos.close();
            response.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
            OutputStream out = response.getOutputStream();
            //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            bis.close();
            out.write(buff);//输出数据文件
            out.flush();//释放缓存
            out.close();//关闭输出流
        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
    //【获取目录下所有文件】
    public static List<String> getFileList(String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
                }  else {
                    String strFileName = files[i].getAbsolutePath();
                    //System.out.println("---" + strFileName);
                    filelist.add(strFileName);
                }
            }

        }
        return filelist;
    }
    //【文件遍历,压缩打包】
    private String zipFile(String zipBasePath, String zipName, String zipFilePath, List<String> filePaths,ZipOutputStream zos) throws IOException {
        //循环读取文件路径集合,获取每一个文件的路径
        for(String filePath : filePaths){
            File inputFile = new File(filePath);  //根据文件路径创建文件
            if(inputFile.exists()) { //判断文件是否存在
                if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹
                    //创建输入流读取文件
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
                    //将文件写入zip内,即将文件进行打包
                    zos.putNextEntry(new ZipEntry(inputFile.getName()));
                    //写入文件的方法,同上
                    int size = 0;
                    byte[] buffer = new byte[1024];  //设置读取数据缓存大小
                    while ((size = bis.read(buffer)) > 0) {
                        zos.write(buffer, 0, size);
                    }
                    //关闭输入输出流
                    zos.closeEntry();
                    bis.close();

                } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip
                    try {
                        File[] files = inputFile.listFiles();
                        List<String> filePathsTem = new ArrayList<String>();
                        for (File fileTem:files) {
                            filePathsTem.add(fileTem.toString());
                        }
                        return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem,zos);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
    //【最初版-下载】
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response, String filePath) throws UnsupportedEncodingException {
        //String filePlace=bootdoConfig.getUploadPath()+filePath.replace("/files/","");
        File file = new File(filePath);
        String fileName  = URLEncoder.encode(file.getName(),"utf-8");
        try{
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            OutputStream outputStream = response.getOutputStream();
            InputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[2048];
            int i = -1;
            while ((i = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, i);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }

    }
    //【删除】
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Map<String,String> del(HttpServletRequest request, HttpServletResponse response, String path){
        System.out.println("删除-"+path);
        Map<String,String> map=new HashMap<>();
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                map.put("code","0");
                map.put("message","删除成功");
                return map;
            } else {
                map.put("code","1");
                map.put("message","删除失败");
                return map;
            }
        } else {
            map.put("code","1");
            map.put("message","删除失败");
            return map;
        }
    }
    //【第一版批量下载】
    @RequestMapping(value = "/downloadListTest", method = RequestMethod.GET)
    @ResponseBody
    public void downloadListTest(HttpServletRequest request, HttpServletResponse response, String createTime,String batchNo,String taskNo){
        filelist=new ArrayList<>();;//全局变量置空
        String path= UploadUtils.returnAbsPath(createTime,batchNo,taskNo);
        String filePlace=bootdoConfig.getUploadPath()+"files/"+path.substring(0,path.lastIndexOf("/"));
        System.out.println("place="+filePlace);
        String zipName = "download.zip";
        String zipFilePath = filePlace+zipName;
        List<String> list=getFileList(filePlace);
        byte[] buff=null;
        try{
            //压缩文件
            File zip = new File(zipFilePath);
            if (!zip.exists()){
                zip.createNewFile();
            }
            //创建zip文件输出流
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
            this.zipFile(filePlace,zipName, zipFilePath,list,zos);
            zos.close();
            response.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
            OutputStream out = response.getOutputStream();
            //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
            int count = 0;
            while (count == 0) {
                count = bis.available();
            }
            buff = new byte[count];
            bis.read(buff);
  /*          byte[] buff = new byte[bis.available()];
            bis.read(buff);*/
            bis.close();
            out.write(buff);//输出数据文件
            out.flush();//释放缓存
            out.close();//关闭输出流
            zip.delete();//删除下载zip
        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
    //【预览】
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    @ResponseBody
    public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response,String fileName) {
        if(fileName==null||"".equals(fileName)){
            throw new ServiceErrorException("没有相关文件,请联系管理员查询");
        }else{
           // File file = new File("d:/var/test.pdf");
            File file = new File(fileName);
            if (file.exists()){
                byte[] data = null;
                try {
                    FileInputStream input = new FileInputStream(file);
                    int count = 0;
                    while (count == 0) {
                        count = input.available();
                    }
                      data = new byte[count];
                    input.read(data);
                    OutputStream out = response.getOutputStream();
                    out.write(data);
                    out.flush();//释放缓存
                    out.close();//关闭输出流
                    input.close();
                } catch (Exception e) {
                    System.out.println("pdf文件处理异常:" + e);
                }

            }
        }
    }

    //【头像】
    @RequestMapping(value = "/photo", method = RequestMethod.GET)
    @ResponseBody
    public static String GetImageStr(String fileName) {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try{
            fileName="d:/var/1.png";
            in = new FileInputStream(fileName);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}