package com.om.utils;

import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.model.HeaderResponse;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
@Data
public class HuaweiObsUtil {

    //Access Key Id
    @Value("${obs.ak}")
    private String ak;

    //Secret Access Key
    @Value("${obs.sk}")
    private String sk;

    //桶名称
    @Value("${obs.bucketName}")
    private String bucketName;

    // 终端节点访问Endpoint
    @Value("${obs.endpoint}")
    private String endpoint;

    // 访问域名 在域名后面或文件目录前加“/”
    @Value("${obs.path}")
    private String path;

    /**
     * 文件上传
     *
     * @param file 要上传的文件
     * @return 文件在OBS中的URL
     * @throws IOException IO异常
     */
    public String upload(MultipartFile file,String prefix) throws IOException {
        ObsClient obsClient = null;
        try {
            String originalFilename = file.getOriginalFilename();
            // 拼接文件在OBS中的路径
            String objectName = prefix + "/"+ originalFilename;
            // 初始化OBS客户端
            obsClient = new ObsClient(ak, sk, endpoint);
            // 上传文件到OBS
            HeaderResponse response = obsClient.putObject(bucketName, objectName, file.getInputStream());
            log.info(JSONObject.toJSONString(response));
            // 判断上传是否成功
            int statusCode = response.getStatusCode();
            if (200 == statusCode) {
                // 拼接文件在OBS中的URL并返回
                String uploadUrl = getUploadUrl(originalFilename, prefix);
                //String objectUrl = "https://"+path + "/" + objectName;
                return uploadUrl;
            }

        } finally {
            // 关闭OBS客户端
            obsClient.close();
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param file 要上传的文件
     * @return 文件在OBS中的URL
     * @throws IOException IO异常
     */
    public String upload(File file, String prefix) throws IOException {
        ObsClient obsClient = null;
        try {
            String yyyyMMdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String originalFilename = file.getName();
            // 拼接文件在OBS中的路径
            String objectName = prefix + "/"+ originalFilename;
            // 初始化OBS客户端
            obsClient = new ObsClient(ak, sk, endpoint);
            // 上传文件到OBS
            FileInputStream fileInputStream = new FileInputStream(file);
            HeaderResponse response = obsClient.putObject(bucketName, objectName, fileInputStream);
            log.info(JSONObject.toJSONString(response));
            // 判断上传是否成功
            int statusCode = response.getStatusCode();
            if (200 == statusCode) {
                // 拼接文件在OBS中的URL并返回
                String uploadUrl = getUploadUrl(originalFilename, prefix);
                //String objectUrl = "https://"+path + "/" + objectName;
                return uploadUrl;
            }

        } finally {
            // 关闭OBS客户端
            obsClient.close();
        }
        return null;
    }



    /**
     * 下载文件
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public String getDownloadUrl(String fileName, FileType fileType) {
        ObsClient obsClient = null;
        obsClient = new ObsClient(ak, sk, endpoint);
        // URL有效期，378432000秒. 一年
        long expireSeconds = 378432000L;
        String objectName = fileType.getType().concat("/").concat(fileName);
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
        request.setBucketName(bucketName);
        request.setObjectKey(objectName);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名称
     * @param prefix 文件路径
     * @return
     */
    public String getDownloadUrl(String fileName, String prefix) {
        ObsClient obsClient = null;
        obsClient = new ObsClient(ak, sk, endpoint);
        // URL有效期，378432000秒 * 2. 二年
        long expireSeconds = 378432000L * 2;
        String objectName = prefix.concat("/").concat(fileName);
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
        request.setBucketName(bucketName);
        request.setObjectKey(objectName);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }

    /**
     * 获取上传地址
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public String getUploadUrl(String fileName, FileType fileType) {
        try {
            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            // URL有效期，378432000秒. 一年
            long expireSeconds = 378432000L;
            String objectName = fileType.getType().concat("/").concat(fileName);
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
            request.setBucketName(bucketName);
            request.setObjectKey(objectName);
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            return response.getSignedUrl();
        } catch (Exception e) {
            log.error("获取上传地址异常：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取上传地址
     *
     * @param fileName 文件名称
     * @param prefix 文件路径
     * @return
     */
    public String getUploadUrl(String fileName, String prefix) {
        try {
            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            // URL有效期，378432000秒. 一年
            long expireSeconds = 378432000L;
            String objectName = prefix.concat("/").concat(fileName);
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
            request.setBucketName(bucketName);
            request.setObjectKey(objectName);
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            return response.getSignedUrl();
        } catch (Exception e) {
            log.error("获取上传地址异常：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 上传视频
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public boolean uploadFileVideo(String fileName, FileType fileType, InputStream is) {
        try {
            String objectName = fileType.getType().concat("/").concat(fileName);
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            // 添加 ContentType (添加后可在浏览器中直接浏览，而非下载链接)
            obsClient.putObject(bucketName, objectName, is);
            obsClient.close();
            return true;
        } catch (Exception e) {
            log.error("上传视频文件异常：{}", e.getMessage(), e);
        }
        return false;
    }






    public enum FileType {

        TEST("test", "测试");
        private String type;
        private String desc;

        FileType(String type, String desc) {
            this.type = type;
            this.desc = desc;
        }

        public String getType() {
            return type;
        }

        public String getDesc() {
            return desc;
        }
    }
}

