package shop.alien.util.ali;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.util.file.FileUtil;

import java.io.File;

/**
 * 阿里云oss工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2025/7/17 8:51
 */
@Slf4j
@Component
public class AliOSSUtil {

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

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

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

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

    /**
     * oss上传文件
     *
     * @param multipartFile 前端上传的文件
     * @param ossFilePath   oss中文件全路径(image/xxx.jpg)
     * @return filePath
     */
    public String uploadFile(MultipartFile multipartFile, String ossFilePath) {
        File convertFile = FileUtil.convert(multipartFile);
        return uploadFile(convertFile, ossFilePath);
    }

    /**
     * oss上传文件
     *
     * @param file        后端文件
     * @param ossFilePath oss中文件全路径(image/xxx.jpg)
     * @return filePath
     */
    public String uploadFile(File file, String ossFilePath) {
        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossFilePath, file);
            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            String eTag = result.getETag();
            if (StringUtils.isNotEmpty(eTag)) {
                //删除临时文件
                file.delete();
                return "https://" + bucketName + "." + endPoint + "/" + ossFilePath;
            }
            return null;
        } catch (Exception e) {
            log.error("AliOSSUtil.uploadFile ERROR: {}", e.getMessage());
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
