package com.njzscloud.common.oss.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.core.ex.SysThrowable;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.mvc.util.ServletUtil;
import com.njzscloud.common.oss.util.AliOSS;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Slf4j
public class AliService implements OSSService {
    @Override
    public Tuple2<String, List<String>> startMltUpload(String objectName, String contentType, int partNum) {
        throw Exceptions.error("暂未实现");
    }

    @Override
    public void endMltUpload(String objectName, String uploadId, int partNum) {
        throw Exceptions.error("暂未实现");
    }

    @Override
    public Map<String, String> obtainPresignedUrl(String filename) {
        String objectName = IdUtil.fastSimpleUUID();
        if (StrUtil.isNotBlank(filename)) {
            objectName = objectName + "." + FileUtil.extName(filename);
        }
        return AliOSS.obtainPresignedUrl(objectName);
    }

    @Override
    public void obtainFile(String bucketName, String objectName, HttpServletResponse response) {
        Tuple2<InputStream, String> tuple2 = AliOSS.obtainFile(bucketName, objectName);
        ServletUtil.download(response, tuple2.get_0(), tuple2.get_1(), objectName);
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String contentType = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        String objectName = IdUtil.fastSimpleUUID() + "." + FileUtil.extName(originalFilename);

        try {
            InputStream inputStream = file.getInputStream();
            return AliOSS.uploadFile(objectName, contentType, inputStream);
        } catch (SysThrowable e) {
            throw e;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw Exceptions.error("上传文件失败");
        }
    }
}
