package com.izouma.wenlvju.service.storage;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.izouma.wenlvju.exception.BusinessException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@Data
@Service
@Slf4j
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "aliyun")
@ConditionalOnProperty(name = "storage.provider", havingValue = "aliyun")
public class AliStorageService implements StorageService {
    private String accessKeyId;
    private String accessKeySecret;
    private String ossBucketName;
    private String ossEndPoint;
    private String ossDomain;

    @Override
    public String uploadFromInputStream(InputStream inputStream, String path) {
        log.info("阿里云OSS上传: inputStream -> {}", path);
        try {
            String result = upload(inputStream, path);
            log.info("上传成功 {}", result);
            return result;
        } catch (Exception e) {
            log.error("阿里云OSS上传失败", e);
            throw new BusinessException("上传失败", e.getMessage());
        }
    }

    @Override
    public String uploadFromUrl(String url, String path) {
        log.info("阿里云OSS上传: {} -> {}", url, path);
        try {
            InputStream inputStream = new URL(url).openStream();
            String result = upload(inputStream, path);
            log.info("上传成功 {}", result);
            return result;
        } catch (Exception e) {
            log.error("阿里云OSS上传失败", e);
            throw new BusinessException("上传失败", e.getMessage());
        }
    }

    private String upload(InputStream inputStream, String path) {
        OSSClient client = new OSSClient(ossEndPoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        client.putObject(ossBucketName, path, inputStream, metadata);
        client.shutdown();
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ossDomain + "/" + path;
    }

    public void rename(String sourceKey, String destinationKey) {
        // 填写源Object的完整路径。Object完整路径中不能包含Bucket名称。
//        String sourceKey = "application.txt";

        // 填写目标Object的完整路径。Object完整路径中不能包含Bucket名称。
//        String destinationKey = sourceKey;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEndPoint, accessKeyId, accessKeySecret);

        // 创建CopyObjectRequest对象。
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(ossBucketName, sourceKey, ossBucketName, destinationKey);

        // 设置新的文件元信息。
        ObjectMetadata meta = new ObjectMetadata();
//        meta.setContentType("text/txt");
        copyObjectRequest.setNewObjectMetadata(meta);

        // 复制文件。
        CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
        System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());

        // 关闭OSSClient。
        ossClient.shutdown();
    }

}
