<%@ page import="java.io.*, java.util.zip.*, java.util.Map, java.util.HashMap" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.StringUtil" %>
<%@ page import="com.weaver.general.BaseBean" %>

<%
    //rootpath  根路径
    String rootpath = "/opt/weaver/ecology";
    // 文件路径和名称映射
    Map<String, String> files = new HashMap<>();
    RecordSet recordSet = new RecordSet();
    recordSet.executeQuery("select * from hrmresource where messagerurl is not null");
    while (recordSet.next()){
        String messagerurl = rootpath + recordSet.getString("messagerurl");
        String Format = messagerurl.substring(messagerurl.lastIndexOf(".")+1);
        String lastname = recordSet.getString("lastname");
        String loginid = recordSet.getString("loginid");
        if (!StringUtil.isEmpty(messagerurl)){
            files.put(lastname+"_"+loginid+"."+Format,messagerurl);
        }
    }


    new BaseBean().writeLog(files+":"+files);
    // files.put("example1.zip", "/opt/oadata/archivesFile/20240530/togd_20240530000000.zip");
    // files.put("example2.zip", "/opt/oadata/archivesFile/20240530/togd660720.zip");

    // 设置响应类型为ZIP文件
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment;filename=files.zip");

    // 创建ZIP输出流
    try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
        for (Map.Entry<String, String> fileEntry : files.entrySet()) {
            String fileName = fileEntry.getKey();
            String filePath = fileEntry.getValue();

            File fileToZip = new File(filePath);
            if (fileToZip.exists() && fileToZip.isFile()) {
                try (FileInputStream fis = new FileInputStream(fileToZip)) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOut.putNextEntry(zipEntry);

                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                    zipOut.closeEntry();
                }
            } else {
                System.err.println("File not found or not a file: " + filePath);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download ZIP</title>
</head>
<body>
<h1>Download ZIP File</h1>
<p>If the download does not start automatically, <a href="/weavernorth/custom/avatar/zipAvatar.jsp">click here</a>.</p>
</body>
</html>
