package com.yunzhi.marketing.common;

import com.aliyun.oss.OSSClient;
import com.yunzhi.marketing.config.AliOSSProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Configuration
@EnableConfigurationProperties(AliOSSProperties.class)
public class AliOSSUtils {

    /**
     * 上传文件
     * @param mf 上传的文件
     * @param toDirs 上传到的目录
     * @return
     */
    public static String putObject(MultipartFile mf, String ... toDirs) throws IOException {
        String fName = StringUtils.ifNull(mf.getOriginalFilename(), StringUtils.random(16) + ".png");
        String preFix = String.valueOf(System.currentTimeMillis());
        String toDir = "/";
        if (null != toDirs && toDirs.length > 0) {
            toDir = toDirs[0];
        }
        String nwFName = toDir + preFix + "-" + fName;
        nwFName = StringUtils.trim(nwFName,"/");

        return putFile(nwFName, new ByteArrayInputStream(mf.getBytes()));
    }

    public static String putObject(File f, String ... toDirs) throws FileNotFoundException {
        String fName = StringUtils.ifNull(f.getName(), StringUtils.random(16) + ".png");
        String preFix = String.valueOf(System.currentTimeMillis());
        String toDir = "/";
        if (null != toDirs && toDirs.length > 0) {
            toDir = toDirs[0];
        }
        String nwFName = toDir + preFix + "-" + fName;
        nwFName = StringUtils.trim(nwFName,"/");

        InputStream inputStream = new FileInputStream(f);
        return putFile(nwFName, inputStream);
    }

    private static String putFile(String fname, InputStream input) {
        OSSClient ossClient = new OSSClient(AliOSSProperties.oss.getEndpoint(), AliOSSProperties.accessKeyId, AliOSSProperties.accessKeySecret);
        ossClient.putObject(AliOSSProperties.oss.getBucketName(), fname, input);
        ossClient.shutdown();

        // String url = ossClient.generatePresignedUrl(AliOSSUtils.oss.getBucketName(), fname, expiration).toString();

        String preURL = AliOSSProperties.oss.getBucketURL();
        if (!preURL.endsWith("/")) {
            preURL += "/";
        }

        return preURL + fname;
    }
}
