package com.diagbot.service.impl;

import com.diagbot.client.fastdfs.FastDFSClient;
import com.diagbot.client.fastdfs.FastDFSFile;
import com.diagbot.dto.FileDTO;
import com.diagbot.exception.CommonException;
import com.diagbot.exception.ServiceErrorCode;
import com.diagbot.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: 文件上传服务接口实现
 * @author: gaodm
 * @time: 2018/11/13 13:50
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public FileDTO singleFileUpload(MultipartFile file) {
        FileDTO fileDTO = new FileDTO();

        if (file.isEmpty()) {
            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "文件不能为空");
        }
        //文件大小上限1M
        if (file.getSize() > 1024 * 1024) {
            throw new CommonException(ServiceErrorCode.FILE_MAX_SIZE_LIMIT, "文件上传失败，超出大小限制1MB");
        }
        try {
            fileDTO = saveFile(file);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "文件上传失败，请重新上传");
        }
        return fileDTO;
    }


    /**
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public FileDTO saveFile(MultipartFile multipartFile) throws IOException {
        FileDTO fileDTO = new FileDTO();
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream = multipartFile.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            log.error("文件上传异常", e);
            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "文件上传异常");
        }
        if (fileAbsolutePath == null) {
            log.error("文件上传失败，请重新上传");
            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "文件上传失败，请重新上传");
        }
        String path = "/" + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        fileDTO.setState("SUCCESS");
        fileDTO.setUrl(path);
        fileDTO.setOriginal(multipartFile.getOriginalFilename());
        fileDTO.setTitle(multipartFile.getOriginalFilename());
        return fileDTO;

    }

    /**
     * 删除服务端文件
     *
     * @param path
     * @return
     */
    public Boolean deleteRemoteFile(String path) {
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        String fileName = path.substring(path.indexOf("/") + 1);
        String groupName = path.substring(0, path.indexOf("/"));
        try {
            FastDFSClient.deleteFile(groupName, fileName);
        } catch (Exception e) {
            log.error("", e);
            throw new CommonException(ServiceErrorCode.FILE_DELETE_ERROR, "文件删除失败");
        }
        return true;
    }
}