package com.xjrsoft.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xjrsoft.common.factory.OssFactory;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class UploadUtil {

    //单文件上传
    public static String  uploadFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        //上传文件
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(StringPool.DOT));
        return Objects.requireNonNull(OssFactory.build()).uploadSuffix(file.getBytes(), suffix);
    }

    //多文件上传
    public  static List<String> uploadFiles(List<MultipartFile> files) throws Exception {
        if (CollectionUtils.isNotEmpty(files)) {
            throw new RuntimeException("上传文件不能为空");
        }
        List<String> urls = new ArrayList<>();
        //上传文件
        for (MultipartFile file : files) {
            urls.add(uploadFile(file));
        }
        return urls;
    }

    public static InputStream download(String path) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request req = new Request.Builder().url(path).build();
            InputStream inputStream = null;
                okhttp3.Response resp = client.newCall(req).execute();
                if (resp.isSuccessful()) {
                    ResponseBody body = resp.body();
                    inputStream = body.byteStream();
                }
            return inputStream;
        } catch (Exception e){
            throw new RuntimeException("获取文件失败，请检查配置信息", e);
        }
    }

    public static boolean delete(String path) {
     return Objects.requireNonNull(OssFactory.build()).delete(path);
    }


    public static String  uploadFileByte(String fileName, byte[] file) throws Exception {
        if (file.length == 0) {
            throw new RuntimeException("上传文件不能为空");
        }
        //上传文件
        String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(StringPool.DOT));
        return Objects.requireNonNull(OssFactory.build()).uploadSuffix(file, suffix);
    }
}
