package com.zzsn.obs;



import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
public class ObsUpload {

    private static ObsConfig configProperties;
    private static ObsClient obsClient;

    static {
        configProperties =new ObsConfig();
        obsClient = new ObsClient(configProperties.getAk(), configProperties.getSk(), configProperties.getEndPoint());
        log.info("初始化 obsClient");
    }
    public  ObsUpload() {

    }

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl
     *            网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 从输入流中获取数据
     *
     * @param inStream
     *            输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
    //流上传，上传内容大小不能超过5GB。
    public static HashMap uploadMultipartFile(MultipartFile file) throws IOException {
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ak = configProperties.getAk();
        String sk = configProperties.getSk();
        String endPoint = configProperties.getEndPoint();
        log.error("========"+sd.format(new Date())+"=====obs上传图片==BBB=");
        ObsClient obsClient = new ObsClient(ak,sk,endPoint);
        log.error("========"+sd.format(new Date())+"=====obs上传图片==CCC=");
        HashMap map = new HashMap();
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "");
        log.error("========"+sd.format(new Date())+"=====obs上传图片==uuidName==="+uuidName);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        PutObjectResult result = obsClient.putObject(configProperties.getBucketName(), uuidName, file.getInputStream(), metadata);
        log.error("========"+sd.format(new Date())+"=====obs上传图片==DDD=");
        map.put("bucketName",result.getBucketName());
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        map.put("originalName",uuidName + suffixName);
        map.put("objectKey",result.getObjectKey());
        map.put("objectUrl",result.getObjectUrl());
        log.error("========"+sd.format(new Date())+"=====obs上传图片==map==="+map);
        return map;
    }


    //流上传，上传内容大小不能超过5GB。
    public static HashMap uploadInputStream(InputStream inputStream,String tag) throws IOException {
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ak = configProperties.getAk();
        String sk = configProperties.getSk();
        String endPoint = configProperties.getEndPoint();
        log.error("========"+sd.format(new Date())+"=====obs流上传==BBB=");
        ObsClient obsClient = new ObsClient(ak,sk,endPoint);
        log.error("========"+sd.format(new Date())+"=====obs流上传==CCC=");
        HashMap map = new HashMap();
        ObjectMetadata metadata = new ObjectMetadata();
        if(StringUtils.isEmpty(tag)) {
            tag = "jpeg";
        }
        metadata.setContentType("image/"+tag);
        metadata.setContentDisposition("inline");
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "");
        PutObjectResult result = obsClient.putObject(configProperties.getBucketName(), uuidName+"."+tag, inputStream);
        log.error("========"+sd.format(new Date())+"=====obs流上传==DDD=");
        map.put("bucketName",result.getBucketName());
        String suffixName = "."+tag;
        map.put("originalName",uuidName + suffixName);
        map.put("objectKey",result.getObjectKey());
        map.put("objectUrl",result.getObjectUrl());
        log.error("========"+sd.format(new Date())+"=====obs流上传==map===="+map);
        return map;
    }


    //文件上传，上传内容大小不能超过5GB。
    public static HashMap uploadFile(File file,String tag) throws IOException {
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ak = configProperties.getAk();
        String sk = configProperties.getSk();
        String endPoint = configProperties.getEndPoint();
        log.error("========"+sd.format(new Date())+"=====obs流上传==BBB=");
        ObsClient obsClient = new ObsClient(ak,sk,endPoint);
        log.error("========"+sd.format(new Date())+"=====obs流上传==CCC=");
        HashMap map = new HashMap();
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "");
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/"+tag);
        PutObjectResult result = obsClient.putObject(configProperties.getBucketName(), uuidName, file);
        log.error("========"+sd.format(new Date())+"=====obs流上传==DDD=");
        map.put("bucketName",result.getBucketName());
        String suffixName = "."+tag;
        map.put("originalName",uuidName + suffixName);
        map.put("objectKey",result.getObjectKey());
        map.put("objectUrl",result.getObjectUrl());
        log.error("========"+sd.format(new Date())+"=====obs流上传==map===="+map);
        return map;
    }

    //下载文件
    public static InputStream downFile(String objectKey) {
        ObsObject obsObject = obsClient.getObject(configProperties.getBucketName(), objectKey);
        return obsObject.getObjectContent();
    }

    //文件删除
    public static void deleteFile(String objectKey) {
        obsClient.deleteObject(configProperties.getBucketName(), objectKey);
    }

    //获取对象信息
    public static ObsObject getObject(String objectKey) {
        try {
            return obsClient.getObject(configProperties.getBucketName(), objectKey);
        } catch (ObsException e) {
        	log.error(e.getMessage(),e);
            return null;
        }
    }


}
