package com.cheng.blzb.utils;


import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.example.base.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

/**
 * @Date: 2021/8/5 17:08
 * @Des:
 */
public class FileUtils {

    private static FileUtils instance;
    private static String packageName = "devcon";

    // 文件缓存路径
    private String CACHE_DIR;

    // 下载目录
    private File downloadDir;
    // 缓存目录
    private File cacheDir;
    // 图片缓存目录
    private File cacheImageDir;

    private File cacheOriginalImageDir;

    private File cacheEditImageDir;

    private File cachePuzzleImageDir;

    public static FileUtils getInstance() {
        if (instance == null) {
            synchronized (FileUtils.class) {
                if (instance == null) {
                    instance = new FileUtils(Utils.INSTANCE.getApp());
                }
            }
        }
        return instance;
    }

    public FileUtils() {

    }

    private FileUtils(Context context) {
        CACHE_DIR = context.getExternalFilesDir(null).getAbsolutePath() + File.separator + packageName + File.separator;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(CACHE_DIR, "/cache");
        } else {
            cacheDir = context.getCacheDir();
        }
        if (!cacheDir.exists())
            cacheDir.mkdirs();
        cacheImageDir = new File(cacheDir, "/image/");
        if (!cacheImageDir.exists())
            cacheImageDir.mkdirs();

        cacheOriginalImageDir = new File(cacheDir, "/originalImage/");
        if (!cacheOriginalImageDir.exists())
            cacheOriginalImageDir.mkdirs();

        cacheEditImageDir = new File(cacheDir, "/cacheEditImage/");
        if (!cacheEditImageDir.exists())
            cacheEditImageDir.mkdirs();

        cachePuzzleImageDir = new File(cacheDir, "/cachePuzzleImage/");
        if (!cachePuzzleImageDir.exists())
            cachePuzzleImageDir.mkdirs();

        downloadDir = new File(cacheDir, "/download/");
        if (!downloadDir.exists())
            downloadDir.mkdirs();
    }

    public String getCACHE_DIR() {
        return CACHE_DIR;
    }

    /**
     * 获取缓存目录
     *
     * @return
     * @Description:
     */
    public File getCacheDir() {
        return cacheDir;
    }

    /**
     * 获取下载目录
     *
     * @return
     */
    public File getCacheDownLoderDir() {
        return downloadDir;
    }

    /**
     * 获取缓存图片目录
     *
     * @return
     * @Description:
     */
    public File getCacheImageDir() {
        return cacheImageDir;
    }

    /**
     * 水印照片编辑后的路径
     *
     * @return
     */
    public File getCacheEditImageDir() {
        return cacheEditImageDir;
    }

    public File getCacheOriginalImageDir() {
        return cacheOriginalImageDir;
    }

    /**
     * 拼图路径
     *
     * @return
     */
    public File getCachePuzzleImageDir() {
        return cachePuzzleImageDir;
    }


    /**
     * 创建一个临时图片文件
     *
     * @return
     * @Description:
     */
    public File newTempImageFile() {
        File file = new File(cacheImageDir, System.currentTimeMillis() + ".jpg");
        return file;
    }

    /**
     * 判断是否安装SD卡
     *
     * @return
     */
    public static boolean checkSaveLocationExists() {
        String sDCardStatus = Environment.getExternalStorageState();
        boolean status;
        if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
            status = true;
        } else
            status = false;
        return status;
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param filePath
     * @return
     */
    public static void deleteFolderFile(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath());
                    }
                }
                if (!file.isDirectory()) {// 如果是文件，删除
                    file.delete();
                } else {// 目录
                    if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                        file.delete();
                    }
                }
            } catch (Exception e) {
                Log.e("FileUtils", e.getMessage());
            }
        }
    }

    /**
     * 删除文件
     *
     * @param path
     * @return
     */
    public boolean deleteFile(String path) {
        boolean status;
        SecurityManager checker = new SecurityManager();

        if (!path.equals("")) {
            File newPath = new File(path);
            checker.checkDelete(newPath.toString());
            if (newPath.isFile()) {
                try {

                    newPath.delete();
                    status = true;
                } catch (SecurityException se) {
                    Log.e("FileUtils", se.getMessage());
                    status = false;
                }
            } else
                status = false;
        } else
            status = false;
        return status;
    }

    /**
     * 获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }

    /**
     * 获取指定文件大小
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {

            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹
     */
    public static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     */
    public static String toFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString;
        String wrongSize = "0M";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //外部存储空间
    public static long getExternalStorageSpace() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            StatFs externalStatFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            long externalBlockSize = externalStatFs.getBlockSizeLong();
            long externalTotalSize = externalStatFs.getBlockCountLong() * externalBlockSize;
            long externalAvailableSize = externalStatFs.getAvailableBlocksLong() * externalBlockSize;
            Log.d("FileUtils", "当前外部空间总大小----" + externalTotalSize);
            Log.d("FileUtils", "当前外部空间可用大小----" + externalAvailableSize);
            return externalAvailableSize;
        } else {
            return 0;
        }
    }

    /**
     * 打开图库
     * @param context
     */
    public void openGallery(Context context) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_APP_GALLERY);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}