package com.jiayue.ipp.idp.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64OutputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;

/**
 * @author wll
 * @date 2020-04-20 10:55:39
 */
@Slf4j
public class GzipUtil {

    private static int packSize = 800;

    public static List<String> zipList(String result) throws IOException {
        return zipList(result, packSize);
    }

    private static List<String> zipList(String result, int packSize) throws IOException {

        String zipResult = zip(result);
        zipResult = zipResult.replace("\r\n", "");

        double length = zipResult.length();
        int packageNumber = (int) Math.ceil(length / packSize);

        List<String> list = new ArrayList<String>();

        for (int i = 0; i < packageNumber; i++) {
            if (i == packageNumber - 1) {
                list.add(zipResult.substring(i * packSize, (int) length));
            } else if (i == 0) {
                list.add(zipResult.substring(0, packSize));
            } else {
                list.add(zipResult.substring(i * packSize, (i + 1) * packSize));
            }
        }


        return list;
    }

    public static String zip(String result) throws IOException {
        log.info("qrCode默认编码:"+Charset.defaultCharset().name());
        log.info("file.encoding:"+System.getProperty("file.encoding"));
        byte[] bytes = result.getBytes("utf-8");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(bos);
        GZIPOutputStream gout = new GZIPOutputStream(b64os);
        gout.write(bytes);
        gout.close();
        b64os.close();

        byte b1[] = bos.toByteArray();
        bos.close();
        return new String(b1, "utf-8");
    }

}
