package cc.smtweb.framework.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Created by Akmm at 2022/7/4 21:37
 * 文件操作处理
 */
@Slf4j
public class FileUtil {
    /**
     * 文件fn是否存在
     *
     * @param fn fileName
     * @return boolean
     */
    public static boolean isFileExist(String fn) {
        return !(fn == null || fn.length() < 1) && (new File(fn)).exists();
    }

    /**
     * 从fn中读取所有内容
     *
     * @param fn 源文件名
     * @return byte[]
     */
    public static byte[] readFileByte(String fn) {
        File f = new File(fn);
        if (!f.exists()) return null;
        try {
            return FileUtils.readFileToByteArray(f);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static String readFileStr(String fn) {
        return readFileStr(fn, StandardCharsets.UTF_8);
    }

    public static String readFileStr(String fn, Charset encode) {
        File f = new File(fn);
        if (!f.exists()) return null;
        try {
            return FileUtils.readFileToString(f, encode);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


    /**
     * 将图片转换为base64编码后的字符串
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String imgToBase64(String path) throws Exception {
        return imgToBase64(new FileInputStream(path));
    }

    public static String imgToBase64(File file) throws Exception {
        return imgToBase64(new FileInputStream(file));
    }

    public static String imgToBase64(InputStream in) throws Exception {
        byte[] data = null;
        data = new byte[in.available()];
        in.read(data);
        in.close();
        Base64 encoder = new Base64();
        return encoder.encodeAsString(data);
    }

    public static String imgToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/png;base64," + png_base64;
    }

    /**
     * 判断是否是图片
     *
     * @param base64Str
     * @return
     */
    public static boolean isImageFromBase64(String base64Str) {
        try {
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(base64Str)));
            if (null == bufImg) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean copyFile(File oldfile, String newPath, boolean isDelOld) {
        if (!oldfile.exists()) return true;
        int byteread;
        try {
            File f = new File(newPath);
            f.getParentFile().mkdirs();
            try (FileOutputStream fs = new FileOutputStream(newPath); InputStream inStream = new FileInputStream(oldfile)) {
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
            }
            if (isDelOld) oldfile.delete();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
