package cn.com.countrygarden.bi.main.configurer;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @Description:图片上传至阿里OSS云库工具类
 *
 * @author ferren
 */
@Data
@Component
public class OSSUtil {
    private static String endpoint;
    private static String accessKeyId;    //这里是你的授权KeyId
    private static String accessKeySecret;//这里是你的授权秘钥
    private static String bucketName;
    /**
     * OSS的文件夹名
     */
    private static String folder;//这里是你存放图片的文件夹名
    private static String key; // = "http://qy-imageserver.oss-cn-shenzhen.aliyuncs.com/";

    /**
     * 上传图片
     *
     * @param fileName 文件名
     * @param inputStream 流
     */
    public static String uploadImageToOSS(String fileName, InputStream inputStream) {
        /**
         * 创建OSS客户端
         */
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String[] names = fileName.split("[.]");
            String name = uuid + "." + names[names.length - 1];
            //new PutObjectRequest(folder +
            ossClient.putObject(new PutObjectRequest(bucketName, folder + name, inputStream));
            //ossClient.putObject(bucketName, name, inputStream);
            ossClient.setObjectAcl(bucketName,folder + name, CannedAccessControlList.PublicRead);
            return key + folder + name;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 多图上传
     */
    public static String[] uploadImageToOSS(String[] fileNames, InputStream[] inputStreams) {
        /**
         * 创建OSS客户端
         */
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(
                    Arrays.asList(fileNames));
            ConcurrentLinkedQueue<InputStream> streamConcurrentLinkedQueue = new ConcurrentLinkedQueue<>(
                    Arrays.asList(inputStreams));
            Iterator<InputStream> inputStreamss = streamConcurrentLinkedQueue.iterator();
            ConcurrentLinkedQueue c = new ConcurrentLinkedQueue();
            for (Iterator<String> iterator = concurrentLinkedQueue.iterator();
                 iterator.hasNext() && inputStreamss.hasNext(); ) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String[] names = iterator.next().split("[.]");
                String name = uuid + "." + names[names.length - 1];
                ossClient.putObject(new PutObjectRequest(bucketName, folder + name, inputStreamss.next()));
                c.add(key + folder + name);
            }
            return (String[]) c.toArray(new String[0]);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 删除图片 警告：在没有调用其他方法的情况下，请调用closeClient方法
     *
     * @param url URL全路径
     */
    public static void deleteImg(String url) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if (url == null || "".equals(url)) {
            return;
        }
        String[] paths = url.split("[.]");
        /**
         * 文件夹是否存在
         */
        if (!ossClient.doesObjectExist(bucketName, folder)) {
            ossClient.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0]));
        }
        String[] name = paths[paths.length - 2].split("[/]");
        /**
         * 对象是否存在
         */
        if (ossClient
                .doesObjectExist(bucketName,
                        folder + name[name.length - 1] + "." + paths[paths.length - 1])) {
            /**
             * 删除存在对象
             */
            ossClient
                    .deleteObject(bucketName, folder + name[name.length - 1] + "." + paths[paths.length - 1]);
        }
        ossClient.shutdown();
    }

    @PostConstruct
    private void init() {
        endpoint = initEndpoint;
        accessKeyId = initAccessKeyId;
        accessKeySecret = initAccessKeySecret;
        bucketName = initBucketName;
        folder = initFolder;
        key = initKey;
    }

    @Value("${wxoss.endpoint}")
    private String initEndpoint;
    @Value("${wxoss.accessKeyId}")
    private String initAccessKeyId;
    @Value("${wxoss.accessKeySecret}")
    private String initAccessKeySecret;
    @Value("${wxoss.bucketName}")
    private String initBucketName;
    @Value("${wxoss.folder}")
    private String initFolder;
    @Value("${wxoss.key}")
    private String initKey;
}