package com.hfkj.common.obs;

import com.hfkj.config.CommonSysConst;
import com.obs.services.ObsClient;
import com.obs.services.model.*;

import java.io.File;
import java.io.IOException;

/**
 * 华为云obs 对象存储
 * @author hurui
 */
public class HuaWeiYunObs {

    public static String url = CommonSysConst.getSysConfig().getObsUrl();
    private static String endPoint = CommonSysConst.getSysConfig().getObsEndPoint();
    private static String accessKey = "CZVO7VAT8UV2RPYJUBD2";
    private static String secretKey = "gyjrR8rYq9w2maPq9VmpRqoMqCJzQMH8vMctg7eE";
    public static String bucketName = CommonSysConst.getSysConfig().getObsUrl();

    /**
     * 创建请求
     * @return
     */
    private static ObsClient createClient() {
        return new ObsClient(accessKey, secretKey, endPoint);
    }

    /**
     * 关闭请求
     * @param obsClient
     */
    private static void closeClient(ObsClient obsClient) {
        try {
            if (obsClient != null) {
                obsClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     * @param bucketName 桶名称
     * @param objectName 对象名称  例如：1.jpg
     * @param file 文件路径
     * @return
     */
    public static PutObjectResult putObject(String bucketName,String objectName, File file) {
        ObsClient client = createClient();
        try {
            return client.putObject(bucketName, objectName, file);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeClient(client);
        }
        return null;
    }

    /**
     * 上传文件
     * @param fileUrl 文件路径
     * @param bucketName 桶名称
     * @param objectName 对象路径名称  例如：temporary/1.jpg
     * @return
     */
    public static void obsUtilPutObject(String fileUrl,String bucketName,String objectName) throws IOException {
        // 执行上传命令
        new ProcessBuilder("/bin/bash", "-c", "obsutil cp "+ fileUrl + " obs://"+bucketName +"/"+ objectName).start();
    }

    /**
     * 获取图片临时路径
     * @param bucketName 桶名称
     * @param objectName 对象名称  例如：1.jpg
     * @return
     */
    public static String getImgSignedUrl(String bucketName,String objectName) {
        ObsClient client = createClient();
        try {
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 1800L);
            request.setBucketName(bucketName);
            request.setObjectKey(objectName);

            TemporarySignatureResponse response = client.createTemporarySignature(request);
            return response.getSignedUrl();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeClient(client);
        }
        return null;
    }


}
