package com.infoepoch.pms.dispatchassistant.controller.system;

import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.constant.StoreKeys;
import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.DateTool;
import com.infoepoch.pms.dispatchassistant.common.utils.ListUtils;
import com.infoepoch.pms.dispatchassistant.controller.basic.Auth;
import com.infoepoch.pms.dispatchassistant.domain.basic.store.KeyValueStoreService;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.system.uploadFile.UploadFile;
import com.infoepoch.pms.dispatchassistant.domain.system.uploadFile.UploadFileService;
import com.infoepoch.pms.dispatchassistant.infractructure.system.file.UploadFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 上传文件Controller
 *
 * @author pengh
 */
@Controller
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    Auth auth;

    @Autowired
    UploadFileService uploadFileService;
    @Autowired
    UploadFileRepository uploadFileRepository;

    @Autowired
    private KeyValueStoreService keyValueStoreService;


    /**
     * 上传文件保存路径
     */
    @Value("${custom.upload-file.save-path}")
    private String savePath;
    @Value("${custom.upload-file.save-path2}")
    private String savePath2;


    /**
     * 上传文件
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException, NotLoginException {
        /**
         * @Date 2021-07-08
         * @Desc 上传文件时，若用户未登录，默认为管理员上传的文件
         */
        User user;
        UploadFile uploadFile;
        try {
            user = auth.getUserReq();
            uploadFile = uploadFileService.saveFile(file, user.getId(), user.getDisplayName());
        } catch (NotLoginException nle) {
            uploadFile = uploadFileService.saveFile(file, "1", "admin");
            nle.printStackTrace();
        }

        return Result.successData(uploadFile);
    }

    /**
     * 直接输出文件，主要用于图片显示
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public void response(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException, ValidationException {
        UploadFile uploadFile = uploadFileRepository.selectById(id);
        if (uploadFile == null)
            throw new ValidationException("");

        File file;
        String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
        if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
            file = new File(savePath + uploadFile.getSavePath());
        } else {
            file = new File(savePath2 + uploadFile.getSavePath());
        }
        if (!file.exists() || !file.canRead())
            throw new ValidationException("");

        FileInputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(file);
            data = new byte[(int) file.length()];
            inputStream.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (data == null)
                data = new byte[0];
        }

        response.setContentType(uploadFile.getContentType());
        String fileName = uploadFile.getFullname();
        //解决文件名乱码
        String header = request.getHeader("User-Agent").toUpperCase();
        //IE下载文件名乱码
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            fileName = URLEncoder.encode(fileName, "utf-8");
            //IE下载文件名空格变+号问题
            fileName = fileName.replace("+", "%20");
        } else {
            //其他浏览器下载文件名乱码
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }

    /**
     * 下载文件
     */
    @RequestMapping(value = "/download/{id}")
    @ResponseBody
    public void download(@PathVariable String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        UploadFile uploadFile = uploadFileRepository.selectById(id);
        request.setCharacterEncoding("UTF-8");
        if (uploadFile == null)
            return;

        File file;
        String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
        if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
            file = new File(savePath + uploadFile.getSavePath());
        } else {
            file = new File(savePath2 + uploadFile.getSavePath());
        }
        if (!file.exists() || !file.canRead())
            return;

        FileInputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(file);
            data = new byte[(int) file.length()];
            inputStream.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (data == null)
                data = new byte[0];
        }

        response.setContentType(uploadFile.getContentType());
        String fileName = uploadFile.getFullname();
        //解决文件名乱码
        String header = request.getHeader("User-Agent").toUpperCase();
        //IE下载文件名乱码
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            fileName = URLEncoder.encode(fileName, "utf-8");
            //IE下载文件名空格变+号问题
            fileName = fileName.replace("+", "%20");
        } else {
            //其他浏览器下载文件名乱码
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }

    /**
     * 下载前校验文件是否存在
     */
    @RequestMapping(value = "/verify/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result verifyFiles(@PathVariable String id) throws ValidationException {
        UploadFile uploadFile = uploadFileRepository.selectById(id);
        if (uploadFile == null)
            throw new ValidationException("文件不存在");

        File file;
        String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
        if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
            file = new File(savePath + uploadFile.getSavePath());
        } else {
            file = new File(savePath2 + uploadFile.getSavePath());
        }
        if (!file.exists() || !file.canRead())
            throw new ValidationException("服务器不存在文件：" + uploadFile.getFullname());
        return Result.success();
    }

    /**
     * 批量下载文件
     */
    @RequestMapping(value = "/download-zip", method = RequestMethod.POST)
    @ResponseBody
    public void downloadZip(String ids, HttpServletResponse response, HttpServletRequest request) throws IOException {
        if (StringUtils.isBlank(ids))
            return;
        List<String> idsList = ListUtils.splitString(ids, ",");
        List<UploadFile> uploadFiles = uploadFileRepository.selectByIds(idsList);
        request.setCharacterEncoding("UTF-8");
        if (uploadFiles.isEmpty())
            return;
        Date now = new Date();
        String separator = File.separator;
        //按日期存放
        SimpleDateFormat format = new SimpleDateFormat(separator + "yyyy" + separator + "MM" + separator + "dd");
        String datePath = format.format(now);

        String saveDirectoryPath = savePath2 + separator + datePath;
        //创建目录
        File saveDirectory = new File(saveDirectoryPath);
        if (!saveDirectory.exists())
            saveDirectory.mkdirs();
        File zipFile = new File(saveDirectoryPath + "\\[批量下载]" + uploadFiles.get(0).getFileName() + "等.zip");
        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        try {
            //构造最终压缩包的输出流
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
            //暂存文件名，防止重名文件打包报错
            List<String> fileNames = new ArrayList<>();
            for (UploadFile uploadFile : uploadFiles) {
                String fileName = uploadFile.getFileName();
                //相同文件名打包报错处理
                if (fileNames.contains(fileName)) {
                    UUID id = UUID.randomUUID();
                    String[] idd = id.toString().split("-");
                    fileName += idd[1];
                }
                fileNames.add(fileName);
                //解码获取真实路径与文件名
                String realFileName = java.net.URLDecoder.decode(fileName + uploadFile.getExtension(), "UTF-8");
                String realFilePath;
                String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
                if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
                    realFilePath = java.net.URLDecoder.decode(savePath + uploadFile.getSavePath(), "UTF-8");
                } else {
                    realFilePath = java.net.URLDecoder.decode(savePath2 + uploadFile.getSavePath(), "UTF-8");
                }
                File file = new File(realFilePath);
                if (file.exists()) {
                    zipSource = new FileInputStream(file);//将需要压缩的文件格式化为输入流
                    /**
                     * 压缩条目不是具体独立的文件，而是压缩包文件列表中的列表项，称为条目，就像索引一样这里的name就是文件名,
                     * 文件名和之前的重复就会导致文件被覆盖
                     */
                    ZipEntry zipEntry = new ZipEntry(realFileName);//在压缩目录中文件的名字
                    zipStream.putNextEntry(zipEntry);//定位该压缩条目位置，开始写入文件到压缩包中
                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                    int read = 0;
                    byte[] buf = new byte[1024 * 10];
                    while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
                        zipStream.write(buf, 0, read);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (null != bufferStream) bufferStream.close();
                if (null != zipStream) {
                    zipStream.flush();
                    zipStream.close();
                }
                if (null != zipSource) zipSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileInputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(zipFile);
            data = new byte[(int) zipFile.length()];
            inputStream.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (data == null)
                data = new byte[0];
        }
        response.setContentType("application/x-zip-compressed");
        String fileName = "[批量下载]" + uploadFiles.get(0).getFileName() + "等.zip";
        //解决文件名乱码
        String header = request.getHeader("User-Agent").toUpperCase();
        //IE下载文件名乱码
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            fileName = URLEncoder.encode(fileName, "utf-8");
            //IE下载文件名空格变+号问题
            fileName = fileName.replace("+", "%20");
        } else {
            //其他浏览器下载文件名乱码
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
        //删除该压缩文件
        if (zipFile.exists()) {
            zipFile.delete();
        }
    }

    /**
     * 根据Id查询多个文件，返回值为uploader组件格式
     */
    @RequestMapping(value = "/query-by-ids", method = RequestMethod.GET)
    @ResponseBody
    public Result query(@RequestParam(value = "ids[]", required = false) List<String> ids) {
        if (ids == null)
            return Result.success();
        List<UploadFile> uploadFiles = uploadFileRepository.selectByIds(ids);

        //测试数据
        if (ids.contains("0"))
            uploadFiles.add(new UploadFile(
                            "0",
                            "测试文件0",
                            ".txt",
                            "",
                            1L,
                            "",
                            new Date(),
                            false,
                            null,
                            null,
                            "",
                            "1",
                            "管理员",
                            "",
                            ""
                    )
            );

        List<Map<String, Object>> list = new ArrayList<>();
        for (UploadFile uploadFile : uploadFiles) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", uploadFile.getId());
            map.put("name", uploadFile.getFullname());
            map.put("size", uploadFile.getContentLength());
            map.put("uploadUserId", uploadFile.getUploadUserId());
            map.put("uploadUserName", uploadFile.getUploadUserName());
            map.put("uploadTime", uploadFile.getUploadTime());
            list.add(map);
        }
        return Result.successData(list);
    }

    // region pdf+file.zip

    /**
     * 根据pdf+附件下载集合压缩包
     * //     * @param pdfBase64Val
     * pdf base64值
     *
     * @param ids     附件id数组
     * @param pdfName 压缩包中pdf文件的名称
     * @param zipName 压缩包名称
     */
    @RequestMapping(value = "/download-pdf-zip", method = RequestMethod.POST)
    @ResponseBody
    public void downloadZip(@RequestParam("pdfName") String pdfName, @RequestParam("zipName") String zipName,
                            @RequestParam("ids[]") String[] ids, HttpServletResponse response, HttpServletRequest request) throws IOException {
        byte[] pdfDecode = StringUtils.isEmpty(request.getParameter("pdfBase64Val")) ? null : Base64.getDecoder().decode(request.getParameter("pdfBase64Val"));
        List<UploadFile> uploadFiles = uploadFileService.queryByIds(Arrays.asList(ids));
        //1.创建字节数组输出流，用于返回压缩后的输出流字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //2.创建压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        //暂存文件名，防止重名文件打包报错
        List<String> fileNames = new ArrayList<>();
        BufferedInputStream bufferStream = null;
        try {
            for (UploadFile uploadFile : uploadFiles) {
                String fileName = uploadFile.getFileName();
                //相同文件名打包报错处理
                if (fileNames.contains(fileName)) {
                    UUID id = UUID.randomUUID();
                    String[] idd = id.toString().split("-");
                    fileName += idd[1];
                }
                fileNames.add(fileName);
                //解码获取真实路径与文件名
                String realFileName = java.net.URLDecoder.decode(fileName + uploadFile.getExtension(), "UTF-8");
                String realFilePath;
                String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
                if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
                    realFilePath = java.net.URLDecoder.decode(savePath + uploadFile.getSavePath(), "UTF-8");
                } else {
                    realFilePath = java.net.URLDecoder.decode(savePath2 + uploadFile.getSavePath(), "UTF-8");
                }
                File file = new File(realFilePath);
                if (!file.exists()) {
                    continue;
                }
                ZipEntry zipEntry = new ZipEntry(realFileName);
                zipOutputStream.putNextEntry(zipEntry);
                FileInputStream fileInputStream = new FileInputStream(realFilePath);
                bufferStream = new BufferedInputStream(fileInputStream, 1024 * 10);
                int read = 0;
                byte[] buf = new byte[1024 * 10];
                while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
                    zipOutputStream.write(buf, 0, read);
                }
                zipOutputStream.closeEntry();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bufferStream) {
                bufferStream.close();
            }
        }

        if (StringUtils.isNotEmpty(pdfName) && pdfDecode != null) {
            zipOutputStream.putNextEntry(new ZipEntry(pdfName + ".pdf"));
            zipOutputStream.write(pdfDecode, 0, pdfDecode.length);
            zipOutputStream.closeEntry();
        }

        zipOutputStream.close();

        String fileName = zipName;
        //解决文件名乱码
        String header = request.getHeader("User-Agent").toUpperCase();
        //IE下载文件名乱码
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            fileName = URLEncoder.encode(fileName, "utf-8");
            //IE下载文件名空格变+号问题
            fileName = fileName.replace("+", "%20");
        } else {
            //其他浏览器下载文件名乱码
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.reset();
        response.setContentType("application/zip");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".zip");
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        outputStream.write(bytes, 0, bytes.length);
        outputStream.flush();
        outputStream.close();
    }

    // endregion

    /**
     * 下载项目静态资源
     */
    @RequestMapping(value = "/download-static", method = RequestMethod.GET)
    public Result downloadProjectStaticFile(@RequestParam("path") String path, HttpServletResponse response) throws ValidationException {
        try {
            ClassPathResource classPathResource = new ClassPathResource(path);

            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                String[] split = classPathResource.getPath().split("/");
                inputStream = classPathResource.getInputStream();
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(split[split.length - 1], "UTF-8"));
                response.setContentType("content-type:octet-stream");

                outputStream = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != inputStream) {
                    inputStream.close();
                }
                if (null != outputStream) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            throw new ValidationException("文件处理异常！");
        }
        return Result.success();
    }

    /**
     * 批量下载文件
     */
    @RequestMapping(value = "/download-zips", method = RequestMethod.POST)
    @ResponseBody
    public void downloadZips(String ids, String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException {
        if (StringUtils.isBlank(ids))
            return;
        List<String> idsList = ListUtils.splitString(ids, ",");
        List<UploadFile> uploadFiles = uploadFileRepository.selectByIds(idsList);
        request.setCharacterEncoding("UTF-8");
        if (uploadFiles.isEmpty())
            return;
        Date now = new Date();
        String separator = File.separator;
        //按日期存放
        SimpleDateFormat format = new SimpleDateFormat(separator + "yyyy" + separator + "MM" + separator + "dd");
        String datePath = format.format(now);

        String saveDirectoryPath = savePath2 + separator + datePath;
        //创建目录
        File saveDirectory = new File(saveDirectoryPath);
        if (!saveDirectory.exists())
            saveDirectory.mkdirs();
        File zipFile = new File(saveDirectoryPath + fileName + ".zip");
        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        try {
            //构造最终压缩包的输出流
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
            //暂存文件名，防止重名文件打包报错
            List<String> fileNames = new ArrayList<>();
            for (UploadFile uploadFile : uploadFiles) {
                String fileName1 = uploadFile.getFileName();
                //相同文件名打包报错处理
                if (fileNames.contains(fileName1)) {
                    UUID id = UUID.randomUUID();
                    String[] idd = id.toString().split("-");
                    fileName1 += idd[1];
                }
                fileNames.add(fileName1);
                //解码获取真实路径与文件名
                String realFileName = java.net.URLDecoder.decode(fileName1 + uploadFile.getExtension(), "UTF-8");
                String realFilePath;
                String nasDateStr = keyValueStoreService.queryValueByKey(StoreKeys.NAS_DATE);
                if (uploadFile.getUploadTime() != null && uploadFile.getUploadTime().before(DateTool.getDate(StringUtils.isEmpty(nasDateStr) ? "2023-09-15 18:12:26" : nasDateStr))) {
                    realFilePath = java.net.URLDecoder.decode(savePath + uploadFile.getSavePath(), "UTF-8");
                } else {
                    realFilePath = java.net.URLDecoder.decode(savePath2 + uploadFile.getSavePath(), "UTF-8");
                }
                File file = new File(realFilePath);
                if (file.exists()) {
                    zipSource = new FileInputStream(file);//将需要压缩的文件格式化为输入流
                    /**
                     * 压缩条目不是具体独立的文件，而是压缩包文件列表中的列表项，称为条目，就像索引一样这里的name就是文件名,
                     * 文件名和之前的重复就会导致文件被覆盖
                     */
                    ZipEntry zipEntry = new ZipEntry(realFileName);//在压缩目录中文件的名字
                    zipStream.putNextEntry(zipEntry);//定位该压缩条目位置，开始写入文件到压缩包中
                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                    int read = 0;
                    byte[] buf = new byte[1024 * 10];
                    while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
                        zipStream.write(buf, 0, read);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (null != bufferStream) bufferStream.close();
                if (null != zipStream) {
                    zipStream.flush();
                    zipStream.close();
                }
                if (null != zipSource) zipSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileInputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(zipFile);
            data = new byte[(int) zipFile.length()];
            inputStream.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (data == null)
                data = new byte[0];
        }
        response.setContentType("application/x-zip-compressed");
        String name = fileName + ".zip";
        //解决文件名乱码
        String header = request.getHeader("User-Agent").toUpperCase();
        //IE下载文件名乱码
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            name = URLEncoder.encode(fileName, "utf-8");
            //IE下载文件名空格变+号问题
            name = name.replace("+", "%20");
        } else {
            //其他浏览器下载文件名乱码
            name = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"");
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
        //删除该压缩文件
        if (zipFile.exists()) {
            zipFile.delete();
        }
    }

}
