package com.ruoyi.test;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.HexUtil;
import com.ruoyi.TestSuper;
import com.ruoyi.file.FileService;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.dromara.x.file.storage.core.Downloader;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.dromara.x.file.storage.core.tika.TikaFactory;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.time.LocalDate;

@NoArgsConstructor
public class XFileStorageTest extends TestSuper {

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Autowired
    private FileService fileService;

    @Autowired
    private TikaFactory tikaFactory;


    public InputStream getInstream() {
        return this.getClass().getResourceAsStream("/test.png");
    }


  @Test
  @DisplayName("上传获取hash值")
  @Disabled
  @SneakyThrows
  public void testUploadAndHash() {
    out("保存随机文件名:" + fileService.setMd5().setSha256().setFilename("test.png").save(getInstream()));
    out("md5:"+fileService.getMd5());//7edbdf71867c45ca4f15b4025fc6a5dc
    out("sha256:"+fileService.getSha256());//29f57210ca91b193272e4695adefe356a2f1586b07d3845c85afbf7708134a0a
  }

  @Test
  @DisplayName("下载获取hash值")
  @Disabled
  @SneakyThrows
  public void testDownloadAndHash() {
    Downloader downloader = fileService.setMd5().setSha256().download("/files/default/2024/11/13/u6h22sja9w9p.png");
    downloader.file(File.createTempFile("aaaa","bbbbb"));//必须先下载完成
    out("md5:"+downloader.getHashCalculatorManager().getHashInfo().getMd5());//d41d8cd98f00b204e9800998ecf8427e
    out("sha256:"+downloader.getHashCalculatorManager().getHashInfo().getSha256());//e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
  }


  @Test
  @DisplayName("分片上传获取hash值")
  @Disabled
  @SneakyThrows
  public void testMultipartUploadAndHash() {
   out("分片上传不能获取hash值");
  }
  @Test
  @DisplayName("分片上传")
  @Disabled
  @SneakyThrows
  public void testMultipartUpload() {
    File file = new File("D:\\test.mp4");
    String uploadId = fileService.setPlatform("aliyun").setUri("/test.mp4").multipartUploadInit();
    try (
      InputStream in = new FileInputStream(file);
    ) {
      byte[] bs = new byte[5 * 1024 * 1024];//每一片5MB
      int len = 0;
      int partNumber = 0;
      try {
        while ((len = in.read(bs)) > 0) {
          partNumber++;
          ByteArrayInputStream bin = new ByteArrayInputStream(bs, 0, len);
          fileService.multipartUpload(uploadId, partNumber, bin);
          out("上传分片成功：" + partNumber + " len:" + len);

        }
        out("分片上传成功：" + fileService.multipartUploadComplete(uploadId));
      } catch (Exception e) {
        out("分片上传失败", e);
        fileService.multipartUploadAbort(uploadId);
      }

    }
  }


    @Test
    @DisplayName("分片上传")
    @Disabled
    @SneakyThrows
    public void testMultipartUpload1() {
        File file = new File("D:\\test.mp4");//文件大概6M
//        File file = new File("D:\\VMware-images\\CentOS-7-x86_64-Minimal-2009.iso");;//900M+
        FileInfo fileInfo = fileStorageService.initiateMultipartUpload().setPlatform("aliyun").setPath("default/").setSaveFilename(file.getName()).init();
        try (
                InputStream in = new FileInputStream(file);
        ) {
            byte[] bs = new byte[5 * 1024 * 1024];//每一片5MB
            int len = 0;
            int partNumber = 1;
            try {
                while ((len = in.read(bs)) > 0) {
                    partNumber++;
                    ByteArrayInputStream bin = new ByteArrayInputStream(bs, 0, len);
                    fileStorageService.uploadPart(fileInfo, partNumber, bin).upload();
                    out("上传分片成功：" + partNumber + " len:" + len);

                }
                out("分片上传成功：" + fileStorageService.completeMultipartUpload(fileInfo).complete().getUrl());
            } catch (Exception e) {
                out("分片上传失败", e);
                fileStorageService.abortMultipartUpload(fileInfo).abort();
            }
        }
    }


    @Test
    @Disabled
    @DisplayName("读取配置信息")
    public void testConfig() throws Exception {
        out(fileStorageService.getProperties());
    }

    @Test
    @Disabled
    @DisplayName("保存文件")
    @SneakyThrows
    public void saveTest() {
//    out("保存随机文件名:" + fileService.setFilename("test.png").save(getInstream()));
//    out("保存文件名:" + fileService.setKeepFilename().setFilename("test.png").save(getInstream()));
//    out("指定保存规则:" + fileService.setFilename("test.png").setRule("/{yyyy}/{MM}/{dd}/{id}.{ext}").save(getInstream()));
        out("指定保存路径:" + fileService.setUri("/aa/bb/cc/a.png").save(getInstream()));
        out("aliyun指定保存路径:" + fileService.setPlatform("aliyun").setUri("/aa/bb/cc/a.png").save(getInstream()));
        out("local指定保存路径:" + fileService.setPlatform("local").setUri("/aa/bb/cc/a.png").save(getInstream()));
//    out("指定路径前缀保存随机文件名:" + fileService.setPrefix("test").setFilename("test.png").save(getInstream()));
//    out("指定平台保存随机文件名:" + fileService.setPlatform("local").setFilename("test.png").save(getInstream()));

    }

    @Test
    @Disabled
    @DisplayName("保存图片")
    @SneakyThrows
    public void saveImage() {
//    out("保存图片:" + fileService.saveImage(getInstream()));
//    out("保存图片+缩略图:" + fileService.setThumbnail().saveImage(getInstream()));
//    out("保存图片+调整大小+缩略图:" + fileService.setSize(500,500).setThumbnail().saveImage(getInstream()));
//        out("保存图片+水印+调整大小+缩略图:" + fileService.setPlatform("aliyun").setWatermark().setSize(700, 700).setThumbnail().saveImage(getInstream()));
        out("保存图片+水印+调整大小+缩略图+源文件:" + fileService.setPlatform("local").setFilename("test.png").setSaveSrc().setWatermark().setSize(700, 700).setThumbnail().saveImage(getInstream()));
    }


    private String uri = "/files/default/aa/bb/cc/a.png";

    private String aliyun = "https://base-2024.oss-cn-shenzhen.aliyuncs.com/default/aa/bb/cc/a.png";


    @Test
    @Disabled
    @DisplayName("删除文件")
    @SneakyThrows
    public void deleteTest() {
//    fileService.delete(uri);
//    fileService.setPlatform("local").delete("/upload/default/aa/bb/cc/a.png");
        fileService.setPlatform("aliyun").delete(aliyun);
    }

    @Test
    @Disabled
    @DisplayName("下载文件")
    @SneakyThrows
    public void downloadTest() {
//    FileInfo fileInfo = new FileInfo();
//    fileInfo.setPath("default/aa/bb/cc/");
//    fileInfo.setFilename("a.png");
//    fileInfo.setPlatform(fileStorageService.getFileStorage("aliyun").getPlatform());
//    out(HexUtil.encodeHex(fileStorageService.download(fileInfo).bytes()));
//    out(HexUtil.encodeHex(fileService.download(uri).bytes()));
        out(HexUtil.encodeHex(fileService.setPlatform("aliyun").download(aliyun).bytes()));
    }

    @Test
    @Disabled
    @DisplayName("生成预签名URL")
    @SneakyThrows
    public void generatePresignedUrlTest() {
        out(fileService.generatePresignedUrl(uri, Duration.ofMinutes(30)));
        out(fileService.setPlatform("aliyun").generatePresignedUrl(aliyun, Duration.ofMinutes(30)));
        try {
            out(fileService.setPlatform("local").generatePresignedUrl(uri, Duration.ofMinutes(30)));
        } catch (Exception e) {
            out("不支持预签名", e);
        }
    }

    @Test
    @Disabled
    @DisplayName("类型检测")
    @SneakyThrows
    public void contentTypeTest() {
        System.out.println(tikaFactory.getTika().detect(getInstream()));
    }

    @Test
    @Disabled
    @DisplayName("转换格式")
    @SneakyThrows
    public void testWebp() {
        BufferedImage image = ImageIO.read(getInstream());
        ImageIO.write(image, "webp", new File("/test.webp"));
    }
}
