package com.sv.service.common;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * 阿里云 OSS文件类
 *
 * @author zuojie.liang
 */
@Component
public class OSSClientUtil {

    Log log = LogFactory.getLog(OSSClientUtil.class);
    /**
     * 协议
     */
    @Value("${oss.protocol}")
    private String protocol;

    /**
     * 仓库名称
     */
    @Value("${oss.name}")
    private String bucketName;

    /**
     * 公网节点
     */
    @Value("${oss.endPoint}")
    private String endpoint;

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

    /**
     * API访问值
     */
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    //文件存储目录
    private String imageDir = "image/";

    private String videoDir = "video/";

    @Value("${oss.url}")
    private String url;

    private OSSClient ossClient;


    public String upload(String filename, InputStream file) {
        return uploadImg(file, filename);
    }


    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    public String uploadImg(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        return uploadImg(file.getInputStream(), originalFilename);
    }

    public String uploadImg(InputStream inputStream, String originalFilename) {
        String backUrl = "";
        try {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            Random random = new Random();
            String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
            backUrl = imageDir + name;
            // 上传文件
            ossClient.putObject(bucketName, backUrl, inputStream);
            ossClient.setObjectAcl(bucketName, backUrl, CannedAccessControlList.PublicRead);
            // 判断是否上传成功
            boolean uploadResult = ossClient.doesObjectExist(bucketName, backUrl);

            if (uploadResult) {
                backUrl = getImgUrl(name);
            } else {
                backUrl = "";
            }
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return backUrl;
    }

    /**
     * 上传视频
     *
     * @param file
     * @return
     */
    public String uploadVideo(MultipartFile file) {
        String backUrl = "";
        try {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            Random random = new Random();
            String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
            backUrl = videoDir + name;
            // 上传文件
            ossClient.putObject(bucketName, backUrl, file.getInputStream());
            ossClient.setObjectAcl(bucketName, backUrl, CannedAccessControlList.PublicRead);
            // 判断是否上传成功
            boolean uploadResult = ossClient.doesObjectExist(bucketName, backUrl);

            if (uploadResult) {
                backUrl = getVideoUrl(name);
            } else {
                backUrl = "";
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return backUrl;
    }


    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return url + this.imageDir + split[split.length - 1];
        }
        return null;
    }

    /**
     * 获得视频路径
     *
     * @param fileUrl
     * @return
     */
    public String getVideoUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return url + this.videoDir + split[split.length - 1];
        }
        return null;
    }


    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getBucketName() {
        return bucketName;
    }

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

    public String getEndpoint() {
        return endpoint;
    }

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

    public String getAccessKeyId() {
        return accessKeyId;
    }

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

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

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

    public String getImageDir() {
        return imageDir;
    }

    public void setImageDir(String imageDir) {
        this.imageDir = imageDir;
    }

    public OSSClient getOssClient() {
        return ossClient;
    }

    public void setOssClient(OSSClient ossClient) {
        this.ossClient = ossClient;
    }

    public String getVideoDir() {
        return videoDir;
    }

    public void setVideoDir(String videoDir) {
        this.videoDir = videoDir;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}