package com.lightinit.hsdataplatformresdir.common;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author WangYao
 * @date 2018/6/13 11:48
 * @description
 */
public class UploadFileUtils {

    private static final Logger logger = LoggerFactory.getLogger(UploadFileUtils.class);

    public static void write(MultipartFile uploadFile, String targetDir) throws IOException {
        String dataFileName = uploadFile.getOriginalFilename();
        File dataFilePath = new File(targetDir, dataFileName);
        //判断路径是否存在，如果不存在就创建一个
        if (!dataFilePath.getParentFile().exists()) {
            dataFilePath.getParentFile().mkdirs();
        }
        uploadFile.transferTo(new File(targetDir + dataFileName));
    }

    public static boolean writeUploadFile(MultipartFile dataFile, String relativeDir, String propertieds) {
        try {
            String uploadRootDir = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(propertieds);
            String absoluteDir = uploadRootDir + relativeDir;
            write(dataFile, absoluteDir);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    public static String buildRelativeDir(String parentDir, String uniqueDir, String childDir){
        if (!StringUtils.isNotEmpty(uniqueDir)){
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dir = (parentDir == null ? "" : parentDir) + uniqueDir + (childDir == null ? "" : childDir) + simpleDateFormat.format(new Date()) + File.separator;
        return dir;
    }

    public static String getExistingFileRelativeDir(int removeParentDirs, String existingFilePath, int removeChildDirs){
        String dir = new File(existingFilePath).getParent();
        for (int i = 0; i < removeParentDirs; i++) {
            dir = dir.substring(dir.indexOf(File.separator) + 1, dir.length());
        }
        for (int i = 0; i < removeChildDirs; i++) {
            dir = dir.substring(0, dir.lastIndexOf(File.separator));
        }
        dir += File.separator;
        return dir;
    }

    public static String getFileNameByPath(String filePath){
        String fileName = new File(filePath).getName();
        return fileName;
    }

}
