package com.fdage.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.fdage.constant.ConfigConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by owen on 2020/5/12 0012 17:21
 */
@Slf4j
@Component
public class FileUtils {

    @Autowired
    ConfigConstant configConstant;

    public boolean checkFile(MultipartFile file) {
        //设置允许上传文件类型
//        String suffixList = ".jpg,.gif,.png,.ico,.bmp,.jpeg,.zip,.zp,.rar,.mp3,.mp4,.avi,.mov,.4dage,.wav,.wma,.m4a";
        String suffixList = configConstant.serverFileFallow;
        // 获取文件后缀
        if(file == null){
            log.info("文件流为空不可上传");
            return false;
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")
                + 1, fileName.length());
        if (suffixList.contains(suffix.trim().toLowerCase())) {
            log.info("无非法参数可以放行！！！");
            return true;
        }
        log.info("存在非法参数不能放行！请核对上传文件格式，重新刷新页面再次上传！");
        return false;
    }


    /**
     *
     * @param file
     * @param urlBasePath 目前传入需要/ , 结尾不要/ , 保存的中间目录， 文件名后加
     * @return
     */
    public Map<String, Object> upload(MultipartFile file, String urlBasePath) {

        // 检查非法文件上传
        boolean checkFile = this.checkFile(file);
        if (!checkFile) {
            throw new BaseRuntimeException("非法文件, 请重新上传");
        }

        // 文件目录
        String fileName = file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(fileName, ".");

        String newName = DateUtil.format(LocalDateTime.now(), "yyyyMMdd_HHmmssSSS") + "." + suffix;
        String resUrl =  urlBasePath + "/" + newName;
        String savePath = configConstant.serverBasePath + resUrl;
        log.info("保存文件地址：{}", savePath);

        try {
            FileUtil.writeFromStream(file.getInputStream(), savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("fileName", fileName);
        result.put("filePath", resUrl);
        return result;
    }

}
