package com.fdkanfang.common.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿里云oss工具类
 */
@Slf4j
public class AliyunOssUtil {


    private static final String END_POINT = "http://oss-cn-shenzhen.aliyuncs.com";
	private static final String ACCESS_KEY_ID = "LTAIUrvuHqj8pvry";
	private static final String ACCESS_KEY_SECREY = "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4";
	private static final String BUCKET_NAME = "4dkankan";

	// 加载对象
	private static OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECREY);
    

    
    public static void delete(String key) throws IOException{
    	  try {
    		  
            // 2019-2-28 启动aliyun oss 空间
          	ossClient.deleteObject(BUCKET_NAME, key);
          } catch (Exception e) {
              e.printStackTrace();
          }
    }
    
    //上传的数据是byte[]，key是上传后的文件名
    public void upload(byte[] data,String key) throws IOException{  
    	try 
    	{  
    		// 2019-2-28 启动aliyun oss 空间
        	ossClient.putObject(BUCKET_NAME, key, new ByteArrayInputStream(data));
        } catch (Exception e) {
        	log.error(e.toString()+key); 
        }
    }  
    
   
	public static void upload(String filePath, String key) {
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				log.error("要上传的文件不存在：" + filePath);
			}
			ossClient.putObject(BUCKET_NAME, key, new File(filePath));

		} catch (Exception e) {
			log.error(e.toString() + filePath);
		}
	}
    
	public static void upload2(String filePath, String key) {
		try {
			
			// 2019-2-28 启动aliyun oss 空间
			ossClient.putObject(BUCKET_NAME , key, new File(filePath));
		} catch (Exception e) {
			log.error(e.toString() + filePath);
		}
	}
    

	/**
	 * 上传的数据是文件夹，参数是文件夹路径，key是上传后的文件名
	 * @param filepaths
	 * key : 原文件路径
	 * value： oss路径， oss会自动创建目录
	 */
	public static void uploadMulFiles(Map<String, String> filepaths) {
		if (filepaths == null) {
			return;
		}
		log.info("开始批量上传到阿里云：" + new Date().toString());
		if (filepaths.size() > 50) {
			for (String filePath : filepaths.keySet()) {
				upload2(filePath, filepaths.get(filePath));
			}
		} else {
			for (String filePath : filepaths.keySet()) {
				log.info("文件：" + filePath + "到阿里云：" + filepaths.get(filePath));
				upload(filePath, filepaths.get(filePath));
			}
		}
		log.info("批量上传阿里云完毕：" + new Date().toString());
	}


	/**
	 * 可以删除目录
	 * @param prefix 图片路径
	 * @return
	 */
	public static int deleteFile(String prefix){

		ObjectListing objectListing = ossClient.listObjects(BUCKET_NAME, prefix);
		List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
		try {
			for (OSSObjectSummary s : sums) {
				delete(s.getKey());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return sums.size();  
	}
	
	public static void main(String[] args) throws IOException {

		HashMap<String, String> map = new HashMap<>();
//		map.put("F:\\test\\aa.jpg", "kanfang/test/aa.jpg");
		map.put("F:\\test\\oss\\floor.json", "kanfang/test/faa.json");
		uploadMulFiles(map);

//		deleteFile("kanfang/test/aa.jpg");

    }


	public static String upload5(String filePath, String key) {
		PutObjectResult result = null;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				log.error("要上传的文件不存在：" + filePath);
			}


			 result = ossClient.putObject(BUCKET_NAME, key, new File(filePath));

		} catch (Exception e) {
			log.error(e.toString() + filePath);
		}

		log.info(" getETag : " + result.getETag());
		log.info("1 : " + result.toString());
		log.info("2 : " + result.getRequestId());
		log.info("3 : " + result.getClientCRC());
		log.info("4 : " + result.getResponse());
		log.info("5 : " + result.getServerCRC());
		return result.getETag();
	}


    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @param fileName 文件名
     * @return 文件的contentType
     */
    private static String getContentType(String fileName) {
        log.info("getContentType:" + fileName);
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        // 默认返回类型
        return "image/jpeg";
    }

    /**
     * 以流下载图片
	 * @Title: getInputStreamByFileUrl
     * @Description: 根据文件路径获取InputStream流
     * @param
     * @return
     * @return: InputStream
     */
    public static InputStream getInputStreamByFileUrl(String filePath) {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(BUCKET_NAME, filePath);
        return ossObject.getObjectContent();
    }


	/**
	 * 生成图片
	 * @param inputFilePath
	 * @param savePath
	 */
	public static void writeFile(String inputFilePath, String savePath){
		try {
			FileUtils.downloanAndGetResolutionRate(getInputStreamByFileUrl(inputFilePath), savePath ,false);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
