package com.liquidnet.commons.lang.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * aloss 上传MultipartFile to File
 *
 * @author jiangxiulong
 * @since 2021-06-10
 */
@Slf4j
public class FilesUtils {
    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) {
        try {
            File toFile = null;
            if (!file.equals("") && file.getSize() > 0) {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }
            return toFile;
        } catch (Exception e) {
            log.error("multipartFileToFileError", e);
            return null;
        }
    }

    //获取流文件
    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) {
            log.error("inputStreamToFileError", e);
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        try {
            if (file != null) {
                file.delete();
            }
        } catch (Exception e) {
            log.error("deleteTempFileError", e);
        }
    }

    /**
     * 获取文件的md5值
     *
     * @param file 文件
     * @return 返回文件的md5值字符串
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            log.error("getFileMD5CatchError", e);
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                log.error("getFileMD5FinallyError", e);
            }
        }
    }

    /**
     * 大美 通过URL上传
     *
     * @param url
     * @param name
     * @return
     */
    public static File inputStreamToFile(String url, String name) {
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            InputStream ins = httpUrl.getInputStream();
            File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
            if (file.exists()) {
                return file;
            }
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            int len = 8192;
            byte[] buffer = new byte[len];
            while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return file;
        } catch (Exception e) {
            log.error("inputStreamToFileUrlError", e);
            return null;
        }
    }

    /**
     * 获取上传含文件名的完整路径 这里文件名用了uuid 防止重复，可以根据自己的需要来写
     *
     * @param pathName banner
     * @param filename time.jpeg
     * @return
     */
    public static String getUploadPath(String pathName, String filename) {
        // 078a77e0-cf80-481b-824c-5935247cff15.jpeg
        String uploadName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
        // 078a77e0cf80481b824c5935247cff15.jpeg
        uploadName = uploadName.replace("-", "");
        return pathName + "/" + DateUtil.format(LocalDateTime.now(), DateUtil.Formatter.yyyy_MM_dd2) + "/" + uploadName;
    }

    /**
     * 获取 bucketName
     *
     * @param buckType
     * @return
     */
    public static String getBucketName(int buckType) {
        String bucketName = "img-zhengzai-tv";
        switch (buckType) {
            case 1:
                bucketName = "img-zhengzai-tv";
                break;
            case 2:
                bucketName = "app-zhengzai-tv";
                break;
        }
        return bucketName;
    }
}
