package com.lyg.tools.common;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class FileUtil {

    @Value("${yz.upload.path}")
    String uploadPath;

    private void checkUploadPath(String path) throws Exception {
        File tmp = new File(path);
        if (!tmp.exists()) {
            boolean isOk = tmp.mkdirs();
            if (!isOk) {
                throw new Exception("保存路径创建失败");
            }
        }
    }

    private String getMonth() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        return now.format(formatter);
    }

    private String[] getFilePaths(String appid, String fileName) throws Exception {
        String monthStr = getMonth();
        String newFileName = String.format("%d-%s", System.currentTimeMillis(), fileName);
        checkUploadPath(String.format("%s/%s/%s", uploadPath, appid, monthStr));

        // 绝对路径
        String filePath = String.format("%s/%s/%s/%s", uploadPath, appid, monthStr, newFileName);
        // 相对路径 - 不包含 uploadPath
        String url = String.format("%s/%s/%s", appid, monthStr, newFileName);

        return new String[]{filePath, url};
    }

    // 上传目录
    public String saveFile(MultipartFile multipartFile, String appid) throws Exception {
        //获取文件名
        String fileName = multipartFile.getOriginalFilename();

        String[] filePaths = getFilePaths(appid, fileName);
        File upFile = new File(filePaths[0]);
        multipartFile.transferTo(upFile);

        // 返回值 去掉根目录
        return filePaths[1];
    }

    // 保存文件
    public String saveFile(File file, String fileName, String appid) throws Exception {

        String[] filePaths = getFilePaths(appid, fileName);
        if (!file.renameTo(new File(filePaths[0]))) {
            throw new Exception("保存文件失败");
        }

        return filePaths[1];
    }


    // 保存文件
    public String saveFile(byte[] bytes, String fileName, String appid) throws Exception {

        String[] filePaths = getFilePaths(appid, fileName);
        File file = new File(filePaths[0]);
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(bytes);
        outputStream.close();

        return filePaths[1];
    }
}