package com.cusc.nirvana.user.rnr.fp.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] fileContent;

    private final String extension;
    private final String contentType;
    private final String fileName;


    /**
     * @param base64
     * @param dataUri 格式类似于: data:image/png;base64
     */
    public Base64ToMultipartFile(String base64, String dataUri, String fileName) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        if (StringUtils.isNotBlank(dataUri)) {
            this.extension = dataUri.split(";")[0].split("/")[1];
            this.contentType = dataUri.split(";")[0].split(":")[1];
        } else {
            this.extension = "jpg";
            this.contentType = "image";
        }
        this.fileName = fileName;
    }

//    public Base64ToMultipartFile(String base64, String extension, String contentType) {
//        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
//        this.extension = extension;
//        this.contentType = contentType;
//    }

    @Override
    public String getName() {
        if (StringUtils.isBlank(fileName)) {
            return "param_" + System.currentTimeMillis();
        } else {
            return fileName.split(".")[0];
        }
    }

    @Override
    public String getOriginalFilename() {
        if (StringUtils.isBlank(fileName)) {
            return "file_" + System.currentTimeMillis() + "." + extension;
        } else {
            return fileName;
        }
    }

    @Override
    public String getContentType() {
        return contentType;
    }

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

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

    @Override
    public byte[] getBytes() throws IOException {
        return fileContent;
    }

    @Override
    public ByteArrayInputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
        }
    }

}
