package com.example.util;

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

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 〈一句话功能简述〉<br>
 * 〈阿里云OSS服务相关工具类〉
 *
 * @author xunyong
 * @create 2019/2/21
 * @since 1.0.0
 */
@Component
public class AliyunOSSUtil {

	private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
	/// private static String bucketName = AliyunOSSConfigConstant.BUCKE_NAME;
	private static String FILE_URL;
	// private static String endpoint = AliyunOSSConfigConstant.END_POINT;
	// private static String accessKeyId = AliyunOSSConfigConstant.AccessKey_ID;
	// private static String accessKeySecret =
	// AliyunOSSConfigConstant.AccessKey_Secret;
	// private static String fileHost = AliyunOSSConfigConstant.FILE_HOST;

	//@Autowired
	private AliyunOSSConfigConstant aliyunOSSConfigConstant=new AliyunOSSConfigConstant();

	@Autowired
	private DataConfig dataConfig;
	
	

	/**
	 * Description: upolad 嵌入ueditor的上传
	 *
	 * @param file
	 * @param fileUrl
	 * @return java.lang.String
	 * @date 2019/2/21 16:40
	 */

	public AliyunOSSConfigConstant getOssConfig(String env) {
		
		dataConfig.getUeditor().forEach(oSSConfigConstant -> {
			   
			if(oSSConfigConstant.getEnv().equals(env)) {
				BeanUtils.copyProperties(oSSConfigConstant, aliyunOSSConfigConstant);
			}
		});
		
		return aliyunOSSConfigConstant;
	}
	
	public String upolad(File file, String fileUrl) {
	
		
		String bucketName = aliyunOSSConfigConstant.getBucketName();
		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(aliyunOSSConfigConstant.getHost(), aliyunOSSConfigConstant.getKeyId(),
				aliyunOSSConfigConstant.getKeySecret());
		try {
			// 判断容器是否存在,不存在就创建
			if (!ossClient.doesBucketExist(bucketName)) {
				ossClient.createBucket(bucketName);
				CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
				createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
				ossClient.createBucket(createBucketRequest);
			}
			String fileType = new MimetypesFileTypeMap().getContentType(file);
			ObjectMetadata meta = new ObjectMetadata(); // 创建上传Object的Metadata
			meta.setContentType(AliyunOSSUtil.contentType(fileType)); // 设置上传内容类型
			meta.setCacheControl("no-cache");

			PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file, meta));
			// 设置权限(公开读)
			ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			if (result != null) {
				logger.info("------OSS文件上传成功------" + fileUrl);
			}
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		return fileUrl;
	}

	/**
	 * 上传文件。
	 *
	 * @param file 需要上传的文件路径
	 * @return 如果上传的文件是图片的话，会返回图片的"URL"，如果非图片的话会返回"非图片，不可预览。文件路径为：+文件路径"
	 */
	public String upLoad(File file) {
		// 默认值为：true
		boolean isImage = true;
		// 判断所要上传的图片是否是图片，图片可以预览，其他文件不提供通过URL预览
		try {
			Image image = ImageIO.read(file);
			isImage = image == null ? false : true;
		} catch (IOException e) {
			e.printStackTrace();
		}

		logger.info("------OSS文件上传开始--------" + file.getName());

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = format.format(new Date());

		// 判断文件
		if (file == null) {
			return null;
		}

		String bucketName = aliyunOSSConfigConstant.getBucketName();

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(aliyunOSSConfigConstant.getHost(), aliyunOSSConfigConstant.getKeyId(),
				aliyunOSSConfigConstant.getKeySecret());
		try {
			// 判断容器是否存在,不存在就创建
			if (!ossClient.doesBucketExist(bucketName)) {
				ossClient.createBucket(bucketName);
				CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
				createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
				ossClient.createBucket(createBucketRequest);
			}
			// 设置文件路径和名称
			String fileUrl = aliyunOSSConfigConstant.getFolder() + UUID.randomUUID().toString().replace("-", "") + "-"
					+ file.getName();
			if (isImage) {// 如果是图片，则图片的URL为：....
				FILE_URL = aliyunOSSConfigConstant.getHost() + "/" + fileUrl;
			} else {
				FILE_URL = "非图片，不可预览。文件路径为：" + fileUrl;
			}

			// 上传文件
			PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
			// 设置权限(公开读)
			ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			if (result != null) {
				logger.info("------OSS文件上传成功------" + fileUrl);
			}
		} catch (OSSException oe) {
			logger.error(oe.getMessage());
		} catch (ClientException ce) {
			logger.error(ce.getErrorMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}
		return FILE_URL;
	}

	/**
	 * 通过文件名下载文件
	 *
	 * @param objectName    要下载的文件名
	 * @param localFileName 本地要创建的文件名
	 */
	public void downloadFile(String objectName, String localFileName) {

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(aliyunOSSConfigConstant.getHost(), aliyunOSSConfigConstant.getKeyId(),
				aliyunOSSConfigConstant.getKeySecret());
		// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
		ossClient.getObject(new GetObjectRequest(aliyunOSSConfigConstant.getBucketName(), objectName),
				new File(localFileName));
		// 关闭OSSClient。
		ossClient.shutdown();
	}

	/**
	 * 列举 test 文件下所有的文件
	 */
	public void listFile() {
		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(aliyunOSSConfigConstant.getHost(), aliyunOSSConfigConstant.getKeyId(),
				aliyunOSSConfigConstant.getKeySecret());
		// 构造ListObjectsRequest请求。
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(aliyunOSSConfigConstant.getBucketName());

		// 设置prefix参数来获取fun目录下的所有文件。
		listObjectsRequest.setPrefix("test/");
		// 列出文件。
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		// 遍历所有文件。
		System.out.println("Objects:");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			System.out.println(objectSummary.getKey());
		}
		// 遍历所有commonPrefix。
		System.out.println("CommonPrefixes:");
		for (String commonPrefix : listing.getCommonPrefixes()) {
			System.out.println(commonPrefix);
		}
		// 关闭OSSClient。
		ossClient.shutdown();
	}

	/**
	 * 
	 * @MethodName: contentType
	 * @Description: 获取文件类型
	 * @param FileType
	 * @return String
	 */
	private static String contentType(String fileType) {
		fileType = fileType.toLowerCase();
		String contentType = "";
		switch (fileType) {
		case "bmp":
			contentType = "image/bmp";
			break;
		case "gif":
			contentType = "image/gif";
			break;
		case "png":
		case "jpeg":
		case "jpg":
			contentType = "image/jpeg";
			break;
		case "html":
			contentType = "text/html";
			break;
		case "txt":
			contentType = "text/plain";
			break;
		case "vsd":
			contentType = "application/vnd.visio";
			break;
		case "ppt":
		case "pptx":
			contentType = "application/vnd.ms-powerpoint";
			break;
		case "doc":
		case "docx":
			contentType = "application/msword";
			break;
		case "xml":
			contentType = "text/xml";
			break;
		case "mp4":
			contentType = "video/mp4";
			break;
		default:
			contentType = "image/jpeg";
			break;
		}
		return contentType;
	}

	
}