package com.ym.mec.thirdparty.storage.provider;

import java.io.File;
import java.io.IOException;

import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.ym.mec.thirdparty.exception.ThirdpartyException;
import com.ym.mec.thirdparty.storage.StoragePlugin;
import com.ym.mec.thirdparty.storage.StoragePluginContext;

@Component
public class AliyunOssStoragePlugin implements StoragePlugin, InitializingBean, DisposableBean {

	public final static String PLUGIN_NAME = "Aliyun";

	@Value("${storage.oss.endpoint:oss-cn-beijing.aliyuncs.com}")
	private String endpoint;

	@Value("${storage.oss.accessKeyId:LTAI4Fdhxwfo7FsBDZKK8Wfv}")
	private String accessKeyId;

	@Value("${storage.oss.accessKeySecret:ERRma4P9VWbD98n93gspnZXmoq7rn5}")
	private String accessKeySecret;

	@Value("${storage.oss.bucketName:daya-online}")
	private String bucketName;

	private OSSClient ossClient;

	public String getName() {
		return PLUGIN_NAME;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// 创建ClientConfiguration。ClientConfiguration是OSSClient的配置类，可配置代理、连接超时、最大连接数等参数。
		ClientConfiguration conf = new ClientConfiguration();

		// 设置OSSClient允许打开的最大HTTP连接数，默认为1024个。
		conf.setMaxConnections(200);
		// 设置Socket层传输数据的超时时间，默认为50000毫秒。
		conf.setSocketTimeout(10000);
		// 设置建立连接的超时时间，默认为50000毫秒。
		conf.setConnectionTimeout(10000);
		// 设置从连接池中获取连接的超时时间（单位：毫秒），默认不超时。
		conf.setConnectionRequestTimeout(1000);
		// 设置连接空闲超时时间。超时则关闭连接，默认为60000毫秒。
		conf.setIdleConnectionTime(10000);
		// 设置失败请求重试次数，默认为3次。
		conf.setMaxErrorRetry(5);
		// 设置是否支持将自定义域名作为Endpoint，默认支持。
		conf.setSupportCname(true);

		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
		
		StoragePluginContext.addStoragePlugin(this);
	}

	@Override
	public String uploadFile(String folderName, File file) {
		if (!file.exists()) {
			throw new ThirdpartyException("需要上传的文件[{}]不存在", file.getAbsolutePath());
		}

		if (folderName.endsWith("/")) {
			folderName = folderName.substring(0, folderName.length() - 1);
		}

		ossClient.putObject(bucketName, folderName + "/" + file.getName(), file);

		return "https://" + bucketName + "." + endpoint + "/" + folderName + "/" + file.getName();
	}

	@Override
	public byte[] getFile(String folderName, String fileName) throws IOException {
		OSSObject ossObject = ossClient.getObject(bucketName, folderName + "/" + fileName);
		try {
			return IOUtils.toByteArray(ossObject.getObjectContent());
		} finally {
			if (ossObject != null) {
				ossObject.close();
			}
		}
	}

	@Override
	public void destroy() throws Exception {
		if (ossClient != null) {
			ossClient.shutdown();
		}
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public static void main(String[] args) throws Exception {
		AliyunOssStoragePlugin aliyunOssStorageService = new AliyunOssStoragePlugin();
		aliyunOssStorageService.setAccessKeyId("LTAIwZW9XqrfsZ4r");
		aliyunOssStorageService.setAccessKeySecret("5uDsNZmHMxcnxav8w9byII4zcPpu5G");
		aliyunOssStorageService.setBucketName("yooma-test");
		aliyunOssStorageService.setEndpoint("oss-cn-beijing.aliyuncs.com");
		aliyunOssStorageService.afterPropertiesSet();

		File file = new File("e:/var/2.jpg");
		System.out.println(aliyunOssStorageService.uploadFile("aaa", file));

		System.err.println("***********" + aliyunOssStorageService.getFile("aaa", file.getName()).length);

		aliyunOssStorageService.destroy();
	}
}
