package com.fuint.common.util;

/**
 * HuaweiObsUtil 类。
 * <p>
 * 描述：
 *
 * @author huangwenwen
 * @date 2025/2/28
 */




import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DeleteObjectRequest;
import com.obs.services.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

/**
 * 华为云OBS存储工具
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
public class HuaweiObsUtil {

    private static final Logger logger = LoggerFactory.getLogger(HuaweiObsUtil.class);

    /**
     * 获取华为云OBS客户端对象
     *
     * @param accessKeyId 访问键值
     * @param accessKeySecret 访问秘钥
     * @param endpoint 存储endPoint
     * @return obsClient
     */
    public static ObsClient getObsClient(String accessKeyId, String accessKeySecret, String endpoint) {
        return new ObsClient(accessKeyId, accessKeySecret, endpoint);
    }

    /**
     * 创建存储空间
     *
     * @param obsClient OBS连接
     * @param bucketName 存储空间名称
     * @return 存储空间名称
     */
    public static String createBucket(ObsClient obsClient, String bucketName) {
        try {
            if (!obsClient.headBucket(bucketName)) {
                obsClient.createBucket(bucketName);
                logger.info("创建存储空间成功");
            }
        } catch (ObsException e) {
            logger.error("创建存储空间失败: " + e.getMessage(), e);
        }
        return bucketName;
    }

    /**
     * 创建文件夹
     *
     * @param obsClient obs连接
     * @param bucketName 存储bucket
     * @param folder 文件夹路径
     * @return 文件夹路径
     */
    public static String createFolder(ObsClient obsClient, String bucketName, String folder) {
        String folderName = folder.endsWith("/") ? folder : folder + "/"; // 确保以"/"结尾
        try {
            if (!obsClient.doesObjectExist(bucketName, folderName)) {
                InputStream emptyStream = new FileInputStream(new File(""));
                obsClient.putObject(new PutObjectRequest(bucketName, folderName, emptyStream));
                logger.info("创建文件夹成功");
            }
        } catch (ObsException e) {
            logger.error("创建文件夹失败: " + e.getMessage(), e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return folderName;
    }

    /**
     * 上传文件至OBS
     *
     * @param obsClient obs连接
     * @param file 上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @param bucketName 存储空间
     * @param folder 文件夹
     * @return String 返回文件url
     */
    public static String upload(ObsClient obsClient, File file, String bucketName, String folder) {
        String resultStr = null;

        // 创建存储空间和文件夹
        createBucket(obsClient, bucketName);
        createFolder(obsClient, bucketName, folder);

        try {
            InputStream is = new FileInputStream(file);
            String fileName = file.getName();
            String date = DateUtil.formatDate(new Date(), "yyyyMMdd");
            PutObjectRequest request = new PutObjectRequest(bucketName, folder + "/" + date + "/" + fileName, is);
            obsClient.putObject(request);
            resultStr = "/" + folder + "/" + date + "/" + fileName;
        } catch (Exception e) {
            logger.error("上传华为云OBS服务器异常: " + e.getMessage(), e);
        }

        return resultStr;
    }

    /**
     * 根据key删除OBS上的文件
     *
     * @param obsClient obs连接
     * @param bucketName 存储空间
     * @param folder 文件夹
     * @param key 文件路径（包括文件名，如 "uploads/cake.jpg"）
     */
    public static void deleteFile(ObsClient obsClient, String bucketName, String folder, String key) {
        try {
            DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, folder + key);
            obsClient.deleteObject(deleteObjectRequest);
            logger.info("删除 " + bucketName + " 下的文件 " + folder + key + " 成功");
        } catch (ObsException e) {
            logger.error("删除文件失败: " + e.getMessage(), e);
        }
    }
}
