package cn.datax.service.file.config;

import cn.datax.service.file.api.entity.FileEntity;
import cn.datax.service.file.properties.FileServerProperties;
import cn.datax.service.file.service.impl.FileServiceImpl;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.aliyun.oss.OSSClient;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 阿里云配置
 */
@Configuration
@ConditionalOnProperty(name = "data.file-server.type", havingValue = "aliyun")
public class AliyunOSSAutoConfig {

    @Autowired
    private FileServerProperties fileProperties;

    /**
     * 阿里云文件存储client
     * 只有配置了aliyun.oss.access-key才可以使用
     */
    @Bean
    public OSSClient ossClient() {
        OSSClient ossClient = new OSSClient(fileProperties.getOss().getEndpoint()
                , new DefaultCredentialProvider(fileProperties.getOss().getAccessKey(), fileProperties.getOss().getAccessKeySecret())
                , new ClientConfiguration());
        return ossClient;
    }

    @Service
    public class AliyunOssServiceImpl extends FileServiceImpl {
        @Autowired
        private OSSClient ossClient;

        @Override
        protected String fileType() {
            return fileProperties.getType();
        }

        @Override
        protected void uploadFile(MultipartFile file, FileEntity fileEntity) {
            try {
                PutObjectResult result = ossClient.putObject(fileProperties.getOss().getBucketName(), fileEntity.getFileName(), file.getInputStream());
                if(result.getResponse().getStatusCode() == 200){
                    fileEntity.setFilePath(fileProperties.getOss().getDomain() + "/" + fileEntity.getFileName());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void deleteFile(FileEntity fileEntity) {
            ossClient.deleteObject(fileProperties.getOss().getBucketName(), fileEntity.getFileName());
        }
    }
}
