package com.younike.common.utils.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.younike.common.bean.VideoUploadResult;
import com.younike.common.utils.string.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author chenpengfei
 * <p>
 * 阿里OSS上传服务
 */
@Component
@Log4j2
public class AliyunOSSUtil implements InitializingBean {

    @Value("${oss.bucketname}")
    String bucketName;
    @Value("${oss.filehost}")
    private String getFileHost;
    @Resource
    private OSSClient client;

    private static String fileHost;


    /**
     * 获取配置文件中的数据
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        AliyunOSSUtil.fileHost = this.getFileHost;
    }

    /**
     * 上传文件
     */
    public String upLoad(File file, String fileUrl) {
        log.info("------OSS文件上传开始--------" + file.getName());
        // 判断文件是否为空
        if (file == null) {
            return null;
        }

        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
                // 设置权限(公开读)
                client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
                return fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getErrorMessage());
        } finally {

        }
        return null;
    }

    /**
     * 上传视频文件并截取第一帧
     */
    public VideoUploadResult videoUpload(File file, String fileUrl) {
        log.info("------OSS文件上传开始--------" + file.getName());
        // 判断文件是否为空
        if (file == null) {
            return null;
        }
        VideoUploadResult vr = new VideoUploadResult();
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
                // 设置权限(公开读)
                client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
                vr.setVideoUrl(fileUrl);
            }
            String style = "?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
            String signedUrl = fileUrl + style;
            if (signedUrl != null) {
                vr.setSignedUrl(signedUrl);
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getErrorMessage());
        } finally {

        }
        return vr;
    }

    /**
     * 2021-9-6 Another 过滤图片显示全路径（若有微信头像直接返回）
     * @param url
     * @return
     */
    public static String translateAddress(String url) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        if (url.contains("https://")) {
            return url;
        }
        return fileHost + url;
    }

    public static String tailorAddress(String url) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        if (url.contains("https://")) {
            return url.replace(fileHost, "");
        }
        return url;
    }

    /**
     * 2021-9-6 Another 过滤图片显示全路径（若有微信头像直接返回）
     * @param urls 通过指定字符串拼接起来的路径
     * @param character 指定分割字符
     * @return
     */
    public static String translateAddressString(String urls, String character) {
        /*StringBuffer urlString = new StringBuffer();
        if (StringUtils.isBlank(urls)) {
            return "";
        }
        String[] split = urls.split(character);
        for (String url : split) {
            if (StringUtils.isNotBlank(urlString)) {
                urlString.append(character);
            }
            if (url.contains("https://")) {
                urlString.append(url);
            } else {
                urlString.append(fileHost + url);
            }
        }
        return urlString.toString();*/
        return urls;
    }

}
