package com.dcsoft.file.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

public class Base64MultipartFile implements MultipartFile {

	private final byte[] fileContent;
	private final String fileName;
	private final String contentType;

	public Base64MultipartFile(String base64Data, String fileName) {
		// 清理Base64数据
		String cleanedBase64 = base64Data.contains(",")
			? base64Data.substring(base64Data.indexOf(",") + 1)
			: base64Data;

		this.fileContent = Base64.getDecoder().decode(cleanedBase64);
		this.fileName = fileName;
		this.contentType = extractContentType(base64Data);
	}

	private String extractContentType(String base64Data) {
		if (base64Data.startsWith("data:image/jpeg")) {
			return "image/jpeg";
		} else if (base64Data.startsWith("data:image/png")) {
			return "image/png";
		} else if (base64Data.startsWith("data:image/gif")) {
			return "image/gif";
		}
		return "application/octet-stream";
	}

	@Override
	public String getName() {
		return "file";
	}

	@Override
	public String getOriginalFilename() {
		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 InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(fileContent);
	}

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