package jnpf.util;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.MockMultipartFile;
import jnpf.constant.FileTypeConstant;
import jnpf.file.FileApi;
import jnpf.file.FileUploadApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * base64工具
 *
 * @author yanwenfu
 * @create 2025-09-08
 */
@Component
@Slf4j
public class Base64Util {

    @Autowired
    private FileUploadApi fileUploadApi;
    @Autowired
    private FileApi fileApi;

    /**
     * 将 Base64 转换为图片文件并上传
     * @param base64Str Base64 字符串
     * @return 上传后的 URL
     */
    public String convertAndUpload(String base64Str) {
        try {
            // 1. 获取系统临时目录
            String tempDir = System.getProperty("java.io.tmpdir");
            // 文件名用时间戳，避免重复
            String suffix = ".jpg";
            String fileName = "temp_" + System.currentTimeMillis() + suffix;
            File file = new File(tempDir, fileName);
            // 2. Base64 解码并写入文件
            byte[] imageBytes = Base64.getDecoder().decode(base64Str);
            try (OutputStream out = new FileOutputStream(file)) {
                out.write(imageBytes);
            }
            // 3. 上传
            String url = uploadFile(file, suffix);
            // 4. 删除临时文件（可选，看你是否需要保留）
            file.delete();
            return url;
        } catch (Exception e) {
            log.error("转换并上传base64图片失败, {}", e.getMessage());
            return null;
        }
    }

    private String uploadFile(File file, String suffix) throws IOException {

        FileInputStream input = new FileInputStream(file);
        String uuid = UUID.randomUUID().toString();
        MultipartFile multiFile = new MockMultipartFile(uuid + TemplateExcelUtils.SUFFIX, file.getName(), MediaType.MULTIPART_FORM_DATA_VALUE, input);
        input.close();
        FileInfo fileInfo = fileUploadApi.uploadFileCustomName(multiFile, fileApi.getPath(FileTypeConstant.TEMPORARY), uuid + suffix);
        return fileInfo.getUrl().replace(ConstantUtil.EXTRA_PATH, "");
    }
}
