package com.jiayue.insu.incloud.utils;

import com.obs.services.ObsClient;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.net.URLDecoder;

@Slf4j
public class HuaWeiObsUtil {

    private static ObsClient obsClient = null;
    private static final String ak = "HPUATL5UW2WP9UQOZFZQ";
    private static final String sk = "P3CARHUhzyV0uJyMuYq8Hi50edJRrKfchJRruGAA";
    private static final String endpoint = "https://obs.cn-north-1.myhuaweicloud.com";

    static {
        obsClient = new ObsClient(ak, sk, endpoint);
    }

    /**
     * 上传文件到华为云OBS
     *
     * @param bucketName
     * @param filePath
     * @param bytes
     * @return
     */
    public static synchronized String uploadFile(String bucketName, String filePath, byte[] bytes) {
        try {
            if (null == obsClient) {
                obsClient = new ObsClient(ak, sk, endpoint);
            }
            // 上传文件
            PutObjectResult putObjectResult = obsClient.putObject(bucketName, filePath, new ByteArrayInputStream(bytes));
            return URLDecoder.decode(putObjectResult.getObjectUrl(),"UTF-8");
        } catch (Exception e) {
            log.error("上传文件到华为云OBS失败", e);
        }
        log.info("上传文件:{} 到华为云OBS成功", filePath);
        return "";
    }

    /**
     * 从华为云OBS下载文件
     *
     * @param bucketName
     * @param filePath
     * @return
     */
    public static synchronized ObsObject getFile(String bucketName, String filePath) {
        try {
            if (null == obsClient) {
                obsClient = new ObsClient(ak, sk, endpoint);
            }
            // 流式下载
            return obsClient.getObject(bucketName, filePath);
        } catch (Exception e) {
            log.error("从华为云OBS下载文件:{}失败:{}", filePath, e);
        }
        return null;
    }

}
