package com.ruoyi.mqtt.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import org.springframework.web.multipart.MultipartFile;

/**
 * Base64转MultipartFile工具类
 */
public class Base64ToMultipartFile implements MultipartFile {

    private final byte[] bytes;
    private final String originalFilename;
    private final String contentType;

    public Base64ToMultipartFile(byte[] bytes, String originalFilename, String contentType) {
        this.bytes = bytes;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
    }

    @Override
    public String getName() {
        return originalFilename;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

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

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

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

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

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

    @Override
    public void transferTo(java.io.File dest) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * 将base64字符串转换为MultipartFile
     */
    public static MultipartFile base64ToMultipart(String base64Data, String fileName) {
        String base64WithoutPrefix = base64Data;
        String contentType = "image/jpeg";

        if (base64Data.startsWith("data:image/")) {
            int endIndex = base64Data.indexOf(";");
            contentType = base64Data.substring(5, endIndex);
            base64WithoutPrefix = base64Data.substring(endIndex + 8);
        }

        byte[] decodedBytes = Base64.getDecoder().decode(base64WithoutPrefix);
        return new Base64ToMultipartFile(decodedBytes, fileName, contentType);
    }
}
