package cn.com.countrygarden.bi.main.util;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 木木子
 * @Description: 文件上传工具类
 * @email 944528607@qq.com
 * @date 2019/5/13 8:53
 */
@Component
public class FileUploadUtil {
    @Value("${resident.file.path}")
    private String path;

    @Value("${resident.file.url.base}")
    private String accessPath;

    // 上传附件
    public Result fileUpload(MultipartFile attach,
                             HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        // 上传文件处理
        String fileName = "";
        if (StringUtils.isEmpty(path)) {
            path = request.getServletContext().getRealPath("");
        }
        if (!attach.isEmpty()) {
            String oldFileName = attach.getOriginalFilename();// 原文件名
            map.put("fileName", oldFileName);
            Instant instant = Instant.now();
            LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

            fileName = attach.getOriginalFilename();

            // 文件存放路径 /uploadFile/年/月/日/时/分/秒
            String saveDirectory = "/uploadFile/" + dateTime.getYear() + "/" + dateTime.getMonthValue() + "/"
                    + dateTime.getDayOfMonth() + "/" + dateTime.getHour() + dateTime.getMinute() + dateTime.getSecond();

            String saveFileName = saveDirectory + "/" + MD5.GetMD5Code(dateTime.toString())
                    + FilenameUtils.getBaseName(fileName) + "." + FilenameUtils.getExtension(fileName);

            File dir = new File(path + saveDirectory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File saveFile = new File(path + saveFileName);
            // 保存
            try {
                ((CommonsMultipartFile) attach).getFileItem().write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("上传文件失败");

            }
            map.put("fileAddress", accessPath + saveFileName);

            // }
        }
        return Response.response(map);

    }
}
