package com.yeejoin.precontrol.common.service.impl;

import java.io.IOException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.yeejoin.precontrol.common.service.FileService;

import sun.misc.BASE64Encoder;

/**
 * @author sqy
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FastFileStorageClient storageClinet;

    @Value("${fileserver.domain}")
    private String fileserver;

    @Override
    public String uploadfile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
        StorePath path = storageClinet.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);
        return path.getFullPath();
    }

    @Override
    public ArrayList<String> uploadfiles(MultipartFile[] files) throws IOException {
        ArrayList<String> filePaths = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            if (file.isEmpty()) {
                continue;
            }
            String fileName = file.getOriginalFilename();
            String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
            StorePath path = storageClinet.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);
            filePaths.add(fileserver + path.getFullPath());
        }
        return filePaths;
    }

    @Override
    public String getImageBase64(String src) {
        src = src.replaceAll(fileserver, "");
        String groupName = this.getGroupName(src);
        String filepath = src.substring(7);
        byte[] downloadFile = storageClinet.downloadFile(groupName, filepath, new DownloadByteArray());
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(downloadFile);
    }

    private String getGroupName(String src) {
        return src.substring(0, 6);
    }

	@Override
	public String getDomain() {
		return fileserver;
	}

}
