package com.yonge.toolset.thirdparty.storage.provider;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ksyun.ks3.dto.PostObjectFormFields;
import com.ksyun.ks3.service.Ks3;
import com.ksyun.ks3.service.Ks3Client;
import com.ksyun.ks3.service.Ks3ClientConfig;
import com.yonge.toolset.thirdparty.entity.UploadSign;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
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.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.thirdparty.storage.StoragePlugin;
import com.yonge.toolset.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 String asyncUploadFile(String folderName, File file, boolean delLocalFile) {
        if (!file.exists()) {
            throw new ThirdpartyException("需要上传的文件[{}]不存在", file.getAbsolutePath());
        }

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

        final String dir = folderName;

        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                ossClient.putObject(bucketName, dir + "/" + file.getName(), file);
                if (delLocalFile) {
                    FileUtils.deleteQuietly(file);
                }
            }
        });
        thread.start();

        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 PostObjectFormFields getUploadSign(UploadSign uploadSign) {
        //要上传的文件名称,不包含路径信息
        String fileName = uploadSign.getFileName();
        //可以确定值得表单项
        Map<String, String> postData = uploadSign.getPostData();
        //无法确定值得表单项
        List<String> unknowValueField = uploadSign.getUnknowValueField();

        Ks3ClientConfig config = new Ks3ClientConfig();
        // 设置域名
        config.setEndpoint(endpoint);
        // 创建Ks3Client实例
        Ks3 client = new Ks3Client(accessKeyId, accessKeySecret, config);

        /**
         * 需要用户在postData和unknowValueField中提供所有的除KSSAccessKeyId, signature, file, policy外的所有表单项。否则用生成的签名上传会返回403</br>
         * 对于用户可以确定表单值的放在 postData中，对于用户无法确定表单值的放在unknownValueField中(比如有的上传控件会添加一些表单项,但表单项的值可能是随机的)</br>
         */
        //Map<String, String> postData = new HashMap<String, String>();
        // 如果使用js sdk上传的时候设置了ACL，请提供以下一行，且值要与SDK中一致，否则删除下面一行代码
        //postData.put("acl","public-read");
        // 提供js sdk中的key值
        //postData.put("key","20150115/中文/${filename}");
        // 设置无法确定的表单值
        //List<String> unknowValueField = new ArrayList<String>();

        // js sdk上传的时候会自动加上一个name的表单项，所以下面需要加上这样的代码。
        unknowValueField.add("name");

        // 如果计算签名时提供的key里不包含${filename}占位符，第二个参数传一个空字符串。
        String postDataKey = postData.get("key");
        if (StringUtils.isNotBlank(postDataKey)) {
            if (postDataKey.indexOf("${filename}") == -1) {
                return client.postObject(bucketName, "", postData, unknowValueField);
            }
        }
        return client.postObject(bucketName, fileName, postData, unknowValueField);
    }

    @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();
    }
}
