package com.sptg.common.core.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * title: Base64DecodeMultipartFileUtils
 * package: com.sptg.common.core.util
 * description: aaa
 *
 *             
 *                 
 */
public class Base64DecodeMultipartFileUtils implements MultipartFile {
    private final byte[] imgContent;
    private final String header;

    public Base64DecodeMultipartFileUtils(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.nanoTime() +  "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes(){
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) {
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream(dest);
            stream.write(imgContent);
            stream.close();
        }catch (IOException e){
            if (null != stream){
                try {
                    stream.close();
                }catch (IOException err){
                    stream = null;
                }
            }
            stream = null;
        }
    }

    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b =decoder.decodeBuffer(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodeMultipartFileUtils(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 功能描述: 把图片的格式转成png格式
     * @param base64  图片的base64字符串
     * @return base64
     *               
     *                      
     */
    public static String imageFormatToPng(String base64){
        String png = "data:image/png;";
        String[] strs = base64.split(";");
        base64 = png + strs[1];
        return base64;
    }
}
