package com.izouma.jmrh.service.storage;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.izouma.jmrh.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);
        client.putObject(ossBucketName, path, inputStream, new ObjectMetadata());
        client.shutdown();
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ossDomain + "/" + path;
    }

}
