package com.yeejoin.precontrol.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileUtil {
    private static final transient Logger log = LoggerFactory.getLogger(FileUtil.class);


    /**
     * 文件上传工具类服务方法
     *
     * @param *        @param file
     * @param filePath
     * @param fileName
     * @return
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        try (FileOutputStream out = new FileOutputStream(filePath + fileName);) {
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            out.write(file);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件后缀名
     *
     * @param * @param fileName
     * @return String
     */
    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     *
     * @param * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName) {
        return getUuid() + getSuffix(fileOriginName);
    }

    /**
     * 生成文件名
     *
     * @param * @param
     * @return
     */
    public static String getUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 上传文件到指定目录下
     *
     * @param fileUploadDir 文件保存目录
     * @param file          上传文件
     * @return
     */
    public static ResponseModel uploadFile(String fileUploadDir, MultipartFile file) {
        Calendar cal = Calendar.getInstance();
        String subFolder = String.format("/%d%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);
        String name = file.getOriginalFilename();
        String fileName = "";
        fileName = System.currentTimeMillis() + "_" + name;
// 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();// 例如:.jpg
        // 文件上传后的路径
        String filePath = getFilePath(suffixName);// 1.images 2.musics 3.videos
        // 4.docs
        File dest = new File(fileUploadDir + filePath + subFolder + "/" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            String destFile = filePath + subFolder + "/" + fileName;
            String sltFile = destFile.substring(0, destFile.lastIndexOf(".")) + ".jpg";
            // 增加视频截图处理
            if ("videos".equalsIgnoreCase(filePath)) {
                VideoTool.cutVideoPic(fileUploadDir + destFile, fileUploadDir + sltFile);
                return CommonResponseUtil.success(sltFile, destFile);
            } else {
                return CommonResponseUtil.success(destFile);
            }
        } catch (IllegalStateException | IOException e) {
//            e.printStackTrace();
            log.info("上传失败");
            return CommonResponseUtil.failure("上传失败");
        }
    }

    public static String getFilePath(String suffixName) {
        switch (suffixName) {
            case ".bmp":
            case ".png":
            case ".jpg":
            case ".jpeg":
                return "images";
            case ".mp3":
            case ".wav":
                return "musics";
            case ".mp4":
            case ".avi":
            case ".rmvb":
            case ".mpeg":
                return "videos";
            case ".doc":
            case ".docx":
            case ".xls":
            case ".xlsx":
            case ".ppt":
            case ".pptx":
            case ".pdf":
                return "docs";
            default:
                return "other";
        }
    }

    public static ResponseModel uploadFiles(String fileUploadDir, MultipartFile[] files) {
        if (null != files && files.length > 0) {
            Map<String, String> fileMap = new HashMap<>();
            for (MultipartFile file : files) {
                ResponseModel res = uploadFile(fileUploadDir, file);
                String fileName = file.getOriginalFilename();
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
                fileMap.put(res.getMessage(), fileName);
            }
            return CommonResponseUtil.success(fileMap, "上传成功");
        }
        return CommonResponseUtil.failure("上传失败");
    }
}
