package com.njyunzhi.pet_identity.common;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.io.outputstream.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class ZipUtil {

    @Autowired
    HttpUtils httpUtils;

    private String today() {
        String formatterStr = "yyyy-MM-dd";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatterStr);
        return LocalDateTime.now(ZoneId.of("Asia/Shanghai")).format(formatter);
    }

    private void zipStream(List<RFile> files, OutputStream outputStream) throws IOException {
        ZipOutputStream zos = new ZipOutputStream(outputStream);
        ZipParameters zipParameters = new ZipParameters();

        for (RFile f : files) {
            zipParameters.setFileNameInZip(f.getName());
            zos.putNextEntry(zipParameters);
            byte[] data = httpUtils.download(f.getUrl());
            zos.write(data);
            zos.closeEntry();
        }
        zos.close();
    }

    public void flush(HttpServletResponse response, List<RFile> files) throws IOException {
        try {
            if (files == null || files.size() < 1) {
                throw new Exception("导出内容为空");
            }

            String fileName = today() + ".zip";
            response.setContentType("application/zip");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+StringUtils.urlEncode(fileName));
            zipStream(files, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();

            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            ResponseBean res = ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
            response.getWriter().println(JSON.toJSONString(res));
        }
    }

    @Data
    public static class RFile {
        String url;
        String name;
    }
}
