package com.cirle.scientific.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.Callback.CalbackBodyType;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 阿里云OSS上传下载文件Utils
 *
 * @author 美沃斯-老周
 *
 */
@Slf4j
public class OSSUtils {

	private static final String ACCESS_ID = "LTAI5tHTG5eNAC7pmoqUDghi";

	private static final String ACCESS_KEY = "K8aZK7RWhqw4LdkP9MtwiC7Rq0avwt";

	private static final String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com/";
	public static final String OSS_DOMAIN = "https://files.qkyxzx.com/";
	public static final String OSS_BUCKET = "qkj-web";


	private static OSSClient getClient() {
		return new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		// oos文件上传
		String bucketName = "mevos-web";
		String key = "upload/toutiao/testuploader.mp4";

		String uploadFilePath = "http://v3-tt.ixigua.com/60208e117ccabbf71fc87ac984b4849b/5a0a6693/video/m/220ff7d5cfa629544d6af799408c1fe6e5d114cea300004963b5e186ff/";

		try {

			System.out.println("正在上传...");
			uploadHttpFile(bucketName, key, uploadFilePath, "video/mp4");

		} finally {
		}

	}



	/**
	 * MultipartFile方式上传
	 *
	 * @param file 文件
	 * @param key  /
	 * @return str
	 * @throws IOException
	 */
	public static String uploadMultipartFile(MultipartFile file, String key){
		try {
			OSSClient client = getClient();
			client.putObject(OSS_BUCKET, key, file.getInputStream());
			client.shutdown();
			return OSS_DOMAIN + key;
		}catch (Exception e){
			log.info("uploadMultipartFile e:{}", e);
		}
		return null;

	}

	// 删除文件
	public static void deleteFile(String key) {
		// 创建OSSClient实例
		OSSClient ossClient = getClient();
		ossClient.deleteObject(OSS_BUCKET, key);
		// 关闭client
		ossClient.shutdown();

	}

	/**
	 * 默认不指定key的情况下，以日期格式为路径  以文件内容的hash值作为文件名
	 *
	 * @param file 文件名
	 * @return String
	 */
	public static String getKey(String file) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String now = sdf.format(date);
		String fileName = FileUtil.getFileNameNoEx(file) + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "." + FileUtil.getExtensionName(file);
		return "test/project/" + now + "/" + fileName;
	}

	public static String getKeyUUId(String file) {
		return UUID.getUUID() + file;
	}

	/**
	 * 上传图片类型file
	 * @param bucketName
	 * @param key
	 * @param uploadFile
	 * @throws Exception
	 */
	public static void uploadPicture(String bucketName, String key, File uploadFile, String fileType) throws Exception {
		uploadFileNew(bucketName, key, uploadFile, fileType);
	}

	// 上传文件
	public static void uploadFileNew(String bucketName, String key, File file,
                                     String fileType) throws OSSException, ClientException,
            FileNotFoundException {
		OSSClient client = getClient();
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		// 可以在metadata中标记文件类型
		objectMeta.setContentType(fileType);
		InputStream input = new FileInputStream(file);
		client.putObject(bucketName, key, input, objectMeta);

	}

	public static File MultipartFileToFile(MultipartFile multiFile) {
		// 获取文件名
		String fileName = multiFile.getOriginalFilename();
		// 获取文件后缀
		String prefix = fileName.substring(fileName.lastIndexOf("."));
		// 若须要防止生成的临时文件重复,能够在文件名后添加随机码

		try {
			File file = File.createTempFile(fileName, prefix);
			multiFile.transferTo(file);
			return file;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 上传本地文件
	 *
	 * @param bucketName
	 * @param key
	 * @param localFileUrl
	 * @param contentType
	 */
	public static void uploadFile(String bucketName, String key, String localFileUrl, String contentType) {
		OSSClient client = getClient();
		File file = new File(localFileUrl);
		InputStream inputStream;
		try {
			inputStream = new FileInputStream(file);
			ObjectMetadata meta = new ObjectMetadata();
			meta.setContentLength(inputStream.available());
			meta.setContentType(contentType);
			client.putObject(bucketName, key, inputStream, meta);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	public static void uploadFileList(String bucketName, List<String> keyList, List<String> localFileUrlList, String contentType) {
		OSSClient c= getClient();
		OSSClient client = new OSSClient("http://oss-cn-beijing.aliyuncs.com/", ACCESS_ID, "FTzDVsO1TcVxTypBLFjThuQKMYV07y");
		try {
			for (int i =0 ;i < localFileUrlList.size(); i++) {
				File file = new File(localFileUrlList.get(i));
				InputStream inputStream;
					inputStream = new FileInputStream(file);
					ObjectMetadata meta = new ObjectMetadata();
					meta.setContentLength(inputStream.available());
					meta.setContentType(contentType);
					client.putObject(bucketName, keyList.get(i), inputStream, meta);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			client.shutdown();
		}

	}

	public static String uploadHttpFileNew(String fileHttpUrl, String key) {
		OSSClient client = getClient();
		URL urlfile = null;

		InputStream inputStream = null;
		try {
			urlfile = new URL(fileHttpUrl);

			inputStream = urlfile.openStream();

			client.putObject(OSS_BUCKET, key, inputStream);
			client.shutdown();

		} catch (Exception e) {
			log.error("uploadHttpFileNew e:{}", e);
		}
		return OSS_DOMAIN + key;
	}

	/**
	 * 上传网络文件
	 *
	 * @param bucketName
	 * @param key
	 * @param fileHttpUrl
	 * @param contentType
	 */
	public static void uploadHttpFile(String bucketName, String key, String fileHttpUrl, String contentType) {
		OSSClient client = getClient();
		URL urlfile = null;

		InputStream inputStream = null;

		try {
			urlfile = new URL(fileHttpUrl);

			inputStream = urlfile.openStream();

			ObjectMetadata meta = new ObjectMetadata();
			meta.setContentType(contentType);

			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, meta);
			Callback callback = new Callback();
			callback.setCallbackUrl("http://api.imevos.com/callback/ossupload");
			callback.setCallbackHost("api.imevos.com");
			callback.setCallbackBody(
					"{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size},\\\"obj\\\":${object},\\\"etag\\\":${etag}}");
			callback.setCalbackBodyType(CalbackBodyType.JSON);

			putObjectRequest.setCallback(callback);

			client.putObject(putObjectRequest);

			client.shutdown();
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
	/**
	 * 删除文件
	 * @param bucketName
	 * @param key
	 */
	public static void deleteObject(String bucketName, String key) {
		OSSClient client = new OSSClient("http://oss-cn-beijing.aliyuncs.com/", ACCESS_ID, "FTzDVsO1TcVxTypBLFjThuQKMYV07y");
		try {
			client.deleteObject(bucketName, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 判断文件是否存在
	 * @param bucketName
	 * @param key
	 */
	public static Boolean doesObjectExist(String bucketName, String key) {
		OSSClient client = new OSSClient("http://oss-cn-beijing.aliyuncs.com/", ACCESS_ID, "FTzDVsO1TcVxTypBLFjThuQKMYV07y");
		try {
			return client.doesObjectExist(bucketName, key);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
