package com.jkcredit.invoice.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author lihua@kuaihuoyun.com
 * @version 2.2.0
 * @date 2023/8/2
 */
@Slf4j
public class FileBase64Util {

    private static final Base64.Decoder DECODER_64 = Base64.getDecoder();
    private static final Base64.Encoder ENCODER_64 = Base64.getEncoder();

    public static String fileUrlToBase64Str(String url, String fileName){
        if(StringUtils.isEmpty(url)){
            return null;
        }
        String savePathName = System.getProperty("user.home") + File.separator + fileName;
        File file = new File(savePathName);
        try{
            FileUtils.copyURLToFile(new URL(url), file);
        }catch (IOException e){
            log.error("JiaoKe, fileUrlToBase64Str error, message:{}", e.getMessage());
        }
        String base64Str = fileToBase64Str(file);
        //file.deleteOnExit();
        return base64Str;
    }

    public static String getFileName(String url, String num){
        if(StringUtils.isEmpty(url)){
            return null;
        }
        return num + getFileExt(url);
    }

    private static String getFileExt(String url){
        return url.substring(url.lastIndexOf("."));
    }


    public static String fileToBase64Str(File file) {
        String base64Str = null;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            // io
            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();
            // Base64字符编码
            base64Str = ENCODER_64.encodeToString(bytes).trim();
        } catch (IOException e) {
            log.error("JiaoKe fileToBase64Str error, message:{}", e.getMessage());
        } finally {
            try {
                if(fin != null){
                    fin.close();
                }
                if(bin != null){
                    bin.close();
                }
                if(bout != null){
                    bout.close();
                }
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return base64Str;
    }

    public static void base64ContentToFile(String base64Content, String filePath) throws IOException {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            // 将空格替换为+
            base64Content = base64Content.replaceAll(" ", "+");
            // Base64解码到字符数组
            byte[] bytes = DECODER_64.decode(base64Content);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            // io
            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 (IOException e) {
            e.getMessage();
        } finally {
            try {
                bis.close();
                fos.close();
                bos.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
    }

    public static void main(String[] args)throws Exception {
        String url = "http://wlhyos-prod.oss-cn-hangzhou.aliyuncs.com/537d0dc6-fb87-45a5-8cc7-b0a352eb31f4.pdf";

        System.out.println(fileUrlToBase64Str(url, "f4.pdf"));

        String basePath = System.getProperty("user.home") + "/temp/";
        String filePath =  basePath + "02.txt";
        JSONObject jsonObject = JSONUtil.readJSONObject(new File(filePath), StandardCharsets.UTF_8);

        String base64Str = jsonObject.getStr("base64Str");
        base64ContentToFile(base64Str, basePath + "002.pdf");
        System.out.println("over");
    }

}
