package cn.com.countrygarden.bi.main.util;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import cn.com.countrygarden.bi.main.configurer.OssInfo;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component("ossUtils")
public class OSSUtils {
	private static String key="https://bgy-wcx.oss-cn-shenzhen.aliyuncs.com/";
	@Autowired
	private OssInfo ossInfo;

	public OSSClient createCilent(){
        String endpoint =ossInfo.getEndpoint();
        String accessKeyId =ossInfo.getAccessKeyId();
        String accessKeySecret =ossInfo.getAccessKeySecret();
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        return client;
    }
	
	
	/**
	 * 单个文件上传，大小自行判断，默认不超过5G。
	 * @param fileName 文件名
	 * @param inputStream 文件流对象
	 * @return 返回下载url
	 */
    public String uploadFile(String fileName, InputStream inputStream){
       OSSClient ossClient = createCilent();
       String url = "";
       try {
    	    fileName = ossInfo.getFiledir() + "/"+ fileName;
    	    boolean doesObjectExist = ossClient.doesObjectExist(ossInfo.getBucketName(),fileName);
    	    if(!doesObjectExist) {
    	    	ossClient.putObject(ossInfo.getBucketName(), fileName, inputStream);
                url=ossClient.generatePresignedUrl(ossInfo.getBucketName(),fileName,new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50)).toString();
    	    }
            // 上传文件流
            
        } catch (OSSException oe) {
        	log.error("{}=Caught an OSSException, which means your request made it to OSS,"
        			+ "but was rejected with an error response for some reason.", oe.getMessage(), oe);
        	log.error("{}=Error Message: "+ oe.getErrorCode());
        	log.error("{}=Error Message: " + oe.getErrorCode());
        	log.error("{}=Error Code:       " + oe.getErrorCode());
        	log.error("{}=Request ID:      " + oe.getRequestId());
        	log.error("{}=Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
        	log.error("{}=Caught an ClientException, which means the client encountered "
        			+ "a serious internal problem while trying to communicate with OSS, "
        			+ "such as not being able to access the network.");
        	log.error("{}=Error Message: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
            	ossClient.shutdown();
            }
        }
        return StringUtils.isEmpty(url)?"文件已存在":url;
    }


	public String uploadFileExpired(String fileName, InputStream inputStream,Long expiretime){
		OSSClient ossClient = createCilent();
		String url = "";
		try {
			fileName = ossInfo.getFiledir() + "/"+ fileName;
			boolean doesObjectExist = ossClient.doesObjectExist(ossInfo.getBucketName(),fileName);
			if(!doesObjectExist) {
				ossClient.putObject(ossInfo.getBucketName(), fileName, inputStream);
				url=ossClient.generatePresignedUrl(ossInfo.getBucketName(),fileName,new Date(System.currentTimeMillis() + expiretime)).toString();
			}
			// 上传文件流

		} catch (OSSException oe) {
			log.error("{}=Caught an OSSException, which means your request made it to OSS,"
					+ "but was rejected with an error response for some reason.", oe.getMessage(), oe);
			log.error("{}=Error Message: "+ oe.getErrorCode());
			log.error("{}=Error Message: " + oe.getErrorCode());
			log.error("{}=Error Code:       " + oe.getErrorCode());
			log.error("{}=Request ID:      " + oe.getRequestId());
			log.error("{}=Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			log.error("{}=Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			log.error("{}=Error Message: " + ce.getMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		return StringUtils.isEmpty(url)?"文件已存在":url;
	}
    /**
     * 删除文件
     * @param fileName
     */
    public void delFile(String fileName) {
    	OSSClient ossClient = createCilent();
    	try {
        	ossClient.deleteObject(ossInfo.getBucketName(), ossInfo.getFiledir()+"/"+fileName);
        	ossClient.shutdown();
		} catch (OSSException e) {
			log.error("{}=Error Message: " + e.getMessage());
		} finally {
            if (ossClient != null) {
            	ossClient.shutdown();
            }
        }
    }
	/**
	 * 上传图片
	 *
	 * @param fileName 文件名
	 * @param inputStream 流
	 */
	public  String uploadImageToOSS(String fileName, InputStream inputStream) {
		/**
		 * 创建OSS客户端
		 */
		OSSClient ossClient = new OSSClient(ossInfo.getEndpoint(), ossInfo.getAccessKeyId(), ossInfo.getAccessKeySecret());
		try {
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String[] names = fileName.split("[.]");
			String name = uuid + "." + names[names.length - 1];
			//new PutObjectRequest(folder +
			ossClient.putObject(new PutObjectRequest(ossInfo.getBucketName(), ossInfo.getFiledir() + name, inputStream));
			//ossClient.putObject(bucketName, name, inputStream);
			ossClient.setObjectAcl(ossInfo.getBucketName(),ossInfo.getFiledir()  + name, CannedAccessControlList.PublicRead);
			return key + ossInfo.getFiledir() + name;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(e.getMessage());
		} finally {
			ossClient.shutdown();
		}
		return null;
	}
}
