package com.nbclass.aliyun.sdk;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.nbclass.exception.ParameterException;
import com.nbclass.exception.ServiceException;
import com.nbclass.util.CommonUtils;

/**
 * 阿里云OSS操作
 * @author leiyun
 * @datetime 2017年1月17日 下午3:58:16
 */
public class AliyunOSSUtils {
	
	private static Logger logger = LoggerFactory.getLogger(AliyunOSSUtils.class);
	
    public static void main(String[] args) throws Exception {
    	boolean flag = true;
    	deleteObject(AliyunConstant.key_prefix  + "casetype-h5/attachments/202005/20200529104151_wsblg.jpg");
    	if(flag)return;
    	File file = new File("D:\\Temp\\images\\2.jpg");
    	byte[] bt = Files.readAllBytes(file.toPath());
    	String imgurl = uploadBytes("test","oppo.jpg", bt);
    	System.out.println("imgurl="+imgurl);
    }
    
    /**
     * 	删除文件
     * @param key
     */
    public static void deleteObject(String key){
    	if(StringUtils.isBlank(key)) {
    		throw new ParameterException("key不能为空");
    	}
    	OSSClient ossClient = null;
    	try {
			// 创建OSSClient实例
			OSSClientBuilder builder = new OSSClientBuilder();
			// 国内服务器使用内网上传到oss
			if(CommonUtils.isNw()){
				// 使用内网节点
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_nw, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			}else{
				// 使用外网节点
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_ww, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			}
			ossClient.deleteObject(AliyunConstant.ossBucketName, key);
		} catch (RuntimeException e) {
			logger.error("阿里云OSS上传文件出错", e);
			throw new ServiceException("网络异常，请稍候再试！");
		} finally{
			if(ossClient!=null){
				// 关闭OSSClient。
				ossClient.shutdown();
			}
		}
    }
    
    /**
     * 上传Byte数组
     * @param filename
     * @param content
     * @return
     */
	public static String uploadBytes(String filename, byte[] content){
    	return uploadBytes(null, filename, content);
    }
    
    public static String uploadBytes(String key, String filename, byte[] content){
    	String url = null;
    	OSSClient ossClient = null;
    	try {
			// 创建OSSClient实例
		//	ossClient = new OSSClient(AliyunConstant.endpoint_nw, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			OSSClientBuilder builder = new OSSClientBuilder();
			
			// 国内服务器使用内网上传到oss
			if(CommonUtils.isNw()){
				logger.info("上传文件到OSS, 使用内网节点");
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_nw, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			}else{
				logger.info("上传文件到OSS, 使用外网节点");
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_ww, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);

			}

    		if(StringUtils.isNotBlank(key)){
    			key = AliyunConstant.key_prefix  + key +"/";
    		}else{
    			key = AliyunConstant.key_prefix;
    		}
		//	String daydir = Tools.getSimpleDate(new Date(), "yyyyMM")+"/";
    		String daydir = "";
			key = key + daydir + filename;
			ossClient.putObject(AliyunConstant.ossBucketName, key, new ByteArrayInputStream(content));
			url = AliyunConstant.access_doamin + key;
		} catch (RuntimeException e) {
			logger.error("阿里云OSS上传文件出错", e);
			throw new ServiceException("网络异常，请稍候再试！");
		} finally{
			if(ossClient!=null){
				// 关闭OSSClient。
				ossClient.shutdown();
			}
		}
    	return url;
    }
    
    /**
     * 上传网络流
     * @param filename
     * @param sourceUrl
     * @return
     */
	public static String uploadByURL(String filename, String sourceUrl){
    	if(StringUtils.isBlank(sourceUrl))return null;
    	sourceUrl = sourceUrl.trim();
    	if(!sourceUrl.startsWith("http://") && !sourceUrl.startsWith("https://"))return null;
    	String url = null;
    	OSSClient ossClient = null;
    	InputStream inputStream = null;
    	try {
			// 创建OSSClient实例
		//	ossClient = new OSSClient(AliyunConstant.endpoint_ww, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			OSSClientBuilder builder = new OSSClientBuilder();
			
			// 国内服务器使用内网上传到oss
			if(CommonUtils.isNw()){
				logger.info("上传文件到OSS, 使用内网节点");
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_nw, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
			}else{
				logger.info("上传文件到OSS, 使用外网节点");
				ossClient = (OSSClient) builder.build(AliyunConstant.endpoint_ww, AliyunConstant.accessKeyId, AliyunConstant.accessKeySecret);
	
			}
			
			String daydir = CommonUtils.getSimpleDate(new Date(), "yyyyMM")+"/";
			String key = AliyunConstant.key_prefix  + daydir + filename;
			// 上传网络流
			inputStream = new URL(sourceUrl).openStream();
			ossClient.putObject(AliyunConstant.ossBucketName, key, inputStream);
			
			url = AliyunConstant.access_doamin + key;
		} catch (IOException | RuntimeException e) {
			logger.error("阿里云OSS上传文件出错", e);
			throw new ServiceException("网络异常，请稍候再试！");
		} finally{
			if(ossClient!=null){
				ossClient.shutdown();
			}
			try {
				if(inputStream!=null)inputStream.close();
				inputStream=null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    	return url;
    }
    
}