package com.playlet.web.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.playlet.common.utils.ExceptionUtil;
import com.playlet.web.service.OssService;
import com.playlet.web.core.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String upload(MultipartFile multipartFile) throws Exception{
        String filePath = getFilePath(multipartFile.getOriginalFilename());
        // 上传到阿里云
        try {
            PutObjectResult ossResult = ossClient.putObject(ossConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(multipartFile.getBytes()));
            log.info("上传文件到OSS结果:{}", ossResult.getResponse());
        } catch (Exception e) {
            log.error(ExceptionUtil.getExceptionMessage(e));
            throw new Exception(e.getMessage());
        }
        return ossConfig.getUrlPrefix() + filePath;
    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
