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.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * FastDFS配置
 */
@Configuration
@ConditionalOnProperty(name = "data.file-server.type", havingValue = "fastdfs")
public class FastdfsAutoConfig {

    @Autowired
    private FileServerProperties fileProperties;

    @Service
    public class FastdfsServiceImpl extends FileServiceImpl {
        @Autowired
        private FastFileStorageClient storageClient;

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

        @Override
        protected void uploadFile(MultipartFile file, FileEntity fileEntity) {
            StorePath storePath = null;
            try {
                storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
            } catch (IOException e) {
                e.printStackTrace();
            }
//            fileEntity.setFilePath("http://" + fileProperties.getFdfs().getWebUrl() + "/" + storePath.getFullPath());
            fileEntity.setFilePath(storePath.getFullPath());
        }

        @Override
        protected void deleteFile(FileEntity fileEntity) {
            StorePath storePath = StorePath.parseFromUrl(fileEntity.getFilePath());
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        }
    }
}
