package com.yeejoin.precontrol.common.service.impl;

import com.yeejoin.precontrol.common.service.PdfService;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author sqy
 */
@Service
public class PdfServiceImpl implements PdfService {

    @Override
    public void base64StringToPdf(String base64Content, String filePath) {
        BASE64Decoder decoder = new BASE64Decoder();
        File file = new File(filePath);
        try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(decoder.decodeBuffer(base64Content));
             BufferedInputStream bis = new BufferedInputStream(byteInputStream);
             FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String pdfToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        try (FileInputStream fin = new FileInputStream(file);
             BufferedInputStream bin = new BufferedInputStream(fin);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             BufferedOutputStream bout = new BufferedOutputStream(baos);) {
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while (len != -1) {
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
