package com.ruoyi.platform.service.impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.service.MinioService;
import com.ruoyi.platform.utils.FileUtil;
import com.ruoyi.platform.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("MinioService")
public class MinioServiceImpl implements MinioService {

    private final MinioUtil minioUtil;

    public MinioServiceImpl(MinioUtil minioUtil) {
        this.minioUtil = minioUtil;
    }

    @Override
    public ResponseEntity<InputStreamResource> downloadFile(String bucketName , String url) throws Exception {
        try {
            // 使用ByteArrayOutputStream来捕获下载的数据
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            minioUtil.downloadObject(bucketName, url, outputStream);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            InputStreamResource resource = new InputStreamResource(inputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + extractFileName(url) + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("下载文件错误");
        }
    }

    private String extractFileName(String urlStr) {
        return urlStr.substring(urlStr.lastIndexOf('/') + 1);
    }


    @Override
    public ResponseEntity<InputStreamResource> downloadZipFile(String bucketName,String path) {
        try {
            // 使用ByteArrayOutputStream来捕获下载的数据
            InputStream inputStream = minioUtil.downloadAndZip(bucketName, path);
            Path p = Paths.get(path);
            String fileName = p.getFileName().toString()+".zip";
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(inputStreamResource);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @Override
    public Map<String, String> uploadFile(String bucketName, String objectName, MultipartFile file ) throws Exception {
            if (file.isEmpty()) {
                throw new Exception("文件为空，无法上传");
            }
            // 获取文件大小并转换为可读形式
            long sizeInBytes = file.getSize();
            String formattedSize = FileUtil.formatFileSize(sizeInBytes); // 格式化文件大小
            Map<String, String> result = new HashMap<>();
            // 上传文件到MinIO并将记录新增到数据库中
            try (InputStream inputStream = file.getInputStream()){
                minioUtil.uploadObject(bucketName, objectName, inputStream);
                result.put("fileName", file.getOriginalFilename());
                int lastIndex = objectName.lastIndexOf('/');
                String url = objectName.substring(0, lastIndex);
                result.put("url", url); // objectName根据实际情况定义
                result.put("fileSize", formattedSize);
            } catch (Exception e) {
                throw new Exception("上传文件失败: " + e.getMessage(), e);
            }
        return result;
    }

    @Override
    public void uploaInputStream(String bucketName, String objectName, InputStream inputStream ) throws Exception {
        minioUtil.uploadObject(bucketName, objectName, inputStream);
    }
}
