package org.tio.sitexxx.service.utils;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.tio.sitexxx.service.vo.OssConfig;

import java.io.ByteArrayInputStream;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-01-15 23:49
 *    desc   :
 * </pre>
 */
@Slf4j
public class OssUtils {

    /**
     * oss 工具客户端
     */
    private static OSSClient ossClient = null;

    /**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     * @param file 待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(OssConfig config, String fileName, ByteArrayInputStream file, String fileDir, String customBucket) {
        OSSClient ossClient = initOSS(config);
        if (ossClient == null) {
            return "";
        }
        StringBuilder fileUrl = new StringBuilder();
        String newBucket = config.getBucketName();
        if(StringUtils.isNotEmpty(customBucket)){
            newBucket = customBucket;
        }
        try {
            //判断桶是否存在,不存在则创建桶
            if(!ossClient.doesBucketExist(newBucket)){
                ossClient.createBucket(newBucket);
            }
            // 获取文件名
            String newFileName = System.currentTimeMillis() +"."+ FileUtil.getSuffix(fileName);
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            fileUrl = fileUrl.append(fileDir).append(newFileName);
            ossClient.putObject(newBucket, fileUrl.toString(), file);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return fileUrl.toString();
    }

    /**
     * 删除文件
     * @param fileName
     */
    public void delete(OssConfig config, String fileName) {
        ossClient.deleteObject(config.getBucketName(), fileName);
    }

    /**
     * 初始化 oss 客户端
     *
     * @return
     */
    private static OSSClient initOSS(OssConfig config) {
        if (ossClient == null) {
            ossClient = new OSSClient(config.getEndpoint(),
                    new DefaultCredentialProvider(config.getAccessKeyId(), config.getAccessKeySecret()),
                    new ClientConfiguration());
        }
        return ossClient;
    }

    public static String getFileName(String fileName){
        //判断是否带有盘符信息
        // Check for Unix-style path
        int unixSep = fileName.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = fileName.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (Math.max(winSep, unixSep));
        if (pos != -1)  {
            // Any sort of path separator found...
            fileName = fileName.substring(pos + 1);
        }
        //替换上传文件名字的特殊字符
        fileName = fileName.replace("=","").replace(",","").replace("&","").replace("#", "");
        return fileName;
    }
}

