package org.lym.pom.service.impl;

import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.lym.pom.service.ImageStorageService;
import org.shoulder.core.util.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.UUID;

/**
 * 本地文件管理图片存储
 *
 * @author lym
 */
@Service
public class LocalImageStorageService implements ImageStorageService {
    private static final String fileDir           = "/data/myImageStore";
    private static final String downloadUrlPrefix = "http://localhost:8080/api/images/";

    @SneakyThrows @Override public String uploadImage(MultipartFile file) {
        String targetPath = file.getContentType() + "/" + UUID.randomUUID() + "." + FileUtil.extName(
                file.getOriginalFilename());
        file.transferTo(FileUtil.file(fileDir, targetPath));
        return downloadUrlPrefix + targetPath;
    }

    @SneakyThrows @Override public void downloadImage(String resourceIdOrPath, HttpServletResponse response) {
        String realFilePath = fileDir + parsePath(resourceIdOrPath);
        // 设置响应头并输出图片流, 根据实际情况设置内容类型);
        response.setContentType(parseContentType(parsePath(resourceIdOrPath)));
        File realFile = new File(realFilePath);
        if (!realFile.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }
        try (RandomAccessFile fileToDownload = new RandomAccessFile(realFile, "r")) {
            FileChannel fileChannel = fileToDownload.getChannel();
            WritableByteChannel responseChannel = Channels.newChannel(response.getOutputStream());
            fileChannel.transferTo(0, fileChannel.size(), responseChannel);
        }
    }

    public String parseContentType(String resourceIdOrPath) {
        String[] parts = resourceIdOrPath.split("/");
        return parts[1];
    }

    public String parsePath(String resourceIdOrPath) {
        if (resourceIdOrPath.startsWith(fileDir)) {
            return resourceIdOrPath.replaceFirst(fileDir, "");
        }
        return resourceIdOrPath;
    }

    @Override public boolean deleteImage(String resourceIdOrPath) {
        String realFilePath = fileDir + resourceIdOrPath;
        return FileUtils.del(realFilePath);
    }
}
     