/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.czg.service.account.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSSClient;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AliOssUtil {

    private final String endPoint = "oss-cn-beijing.aliyuncs.com";
    private final String accessKey = "LTAI5tPdEfYSZcqHbjCrtPRD";
    private final String secretKey = "DZjyHBq3nTujF0NMLxnZgsecU8ZCvy";
    private final String bucketName = "cashier-oss";
    private final String url = "cashier-oss.oss-cn-beijing.aliyuncs.com";
    private final String prefix = "upload";
    private final String selfPrefix = "self";

    /**
     * 文件路径
     *
     * @param prefix 前缀
     * @param suffix 后缀
     * @return 返回上传路径
     */
    public String getPath(String prefix, String suffix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtil.date().getDay() + "/" + uuid;

        if (StrUtil.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }

        return path + "." + suffix;
    }

    /**
     * 文件路径
     *
     * @param prefix  前缀
     * @param fileName 文件名
     * @param suffix  后缀
     * @return 返回上传路径
     */
    public String getPathByFileName(String prefix, String fileName, String suffix) {
        return prefix + "/" + fileName + "." + suffix;
    }


    public String upload(InputStream inputStream, String path) throws Exception {
        OSSClient client = new OSSClient(endPoint, accessKey, secretKey);
        try {
            client.putObject(bucketName, path, inputStream);
            client.shutdown();
        } catch (Exception e) {
            throw new Exception("上传异常");
        }

        return "https://" + url + "/" + path;
    }

    public String uploadSuffix(byte[] data, String suffix) throws Exception {
        return upload(new ByteArrayInputStream(data), getPath(prefix, suffix));
    }

    public String uploadSelfSuffix(byte[] data, String fileName, String suffix) throws Exception {
        return upload(new ByteArrayInputStream(data), getPathByFileName(selfPrefix, fileName, suffix));
    }

}
