package com.skr.mdm.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * @ProjectName: mdm
 * @Package: com.skr.mdm.util
 * @ClassName: FileUtils
 * @Author: Tty
 * @Description: 文件工具类'
 * @Date: 2021/1/5 18:28
 * @Version: 1.0
 */
@Slf4j
public class FileUtils {


    public static void getFile(File file, int deep) {
        // 获得该文件夹内的所有文件
        File[] fileArray = file.listFiles();
        if (null != fileArray) {
            for (File array : fileArray) {
                //如果是文件
                if (array.isFile()) {
                    for (int j = 0; j < deep; j++) {
                        continue;
                    }
                    //输出前置空格
                    // 只输出文件名字
                    delTargetFile(array);
                    //如果是文件夹
                } else if (array.isDirectory()) {
                    //输出前置空格
                    for (int j = 0; j < deep; j++) {
                        continue;
                    }
                    //文件夹需要调用递归 ，深度+1
                    getFile(array, deep + 1);
                }
            }
        }
    }

    private static void delTargetFile(File uploadedFile) {
        try {
            long time = System.currentTimeMillis() - (60 * 1000);
            Path path2 = Paths.get(uploadedFile.getPath());
            BasicFileAttributeView basicFileAttributeView = Files.getFileAttributeView(path2, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes attr = basicFileAttributeView.readAttributes();
            long createTime = attr.creationTime().toMillis();
            long updateTime = uploadedFile.lastModified();
            log.info("文件创建时间 " + createTime);
            log.info("文件修改时间 " + updateTime);
            if (updateTime < time) {
                uploadedFile.delete();
            }
        } catch (Exception e) {
            log.error("删除文件异常：", e);
        }
    }

    /**
     * multipartFile转file
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        InputStream ins = null;
        try {
            toFile = null;
            if (file == null) {
                return null;
            }
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
        } catch (IOException e) {
            log.error("InputStream异常", e);
        } finally {
            try {
                ins.close();
            } catch (IOException e) {
                log.error("InputStream关闭异常", e);
            }
        }
        return toFile;
    }

    /**
     * file转multipartFile
     * @param file
     * @return
     * @throws IOException
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}