package com.cool.bang.modules.upload.service.impl;

import com.cool.bang.common.constant.Constants;
import com.cool.bang.modules.upload.service.IUploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * file upload service implementation class
 *
 * @author PeiZhi Guo
 * 2021-04-17 15:32
 */
@Service
public class UploadServiceImpl implements IUploadService {

    @Value("${cool.file-path}")
    private String filePath;

    @Override
    public String upload(MultipartFile file, String path) throws IOException {
        String yearMonthDay = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        byte[] data = file.getBytes();

        // 文件名
        String fn = file.getOriginalFilename();
        assert fn != null;
        String suffix = fn.substring(fn.lastIndexOf(".")).toLowerCase();
        String fileName = UUID.randomUUID() + suffix;

        // 判断是否有保存路径
        String uploadPath = Constants.IMG;
        if (StringUtils.isNotEmpty(path)) {
            uploadPath = path + "/";
        }

        // 文件路径
        String imgPath = filePath + uploadPath + yearMonthDay + "/";
        File targetFile = new File(imgPath);
        if (!targetFile.exists()) {
            boolean b = targetFile.mkdirs();
        }

        // 文件输出
        FileOutputStream out = new FileOutputStream(imgPath + fileName);
        out.write(data);
        out.flush();
        out.close();
        return Constants.IMG_CHANGE + uploadPath + yearMonthDay + "/" + fileName; // 输出普通保存路径
    }

}
