package com.base.utils.tools.java;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.base.utils.Config;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;

/**
 * 文件工具
 */

public class FileUtil {

    // log文件的后缀名
    public static final String FILE_NAME_SUFFIX = ".log";
    public final static String FILE_PNG = ".png";   //png格式的图片
    public final static String FILE_JPG = ".jpg";   //jpg格式的图片

    /**
     * 默认在手机建立文件夹
     * 在程序入口时就建立了
     */
    public static void setAppFileDir() {
        File sd = Environment.getExternalStorageDirectory();
        String rootPath = sd.getPath() + Config.appDir;
        File rootFile = new File(rootPath);
        if (!rootFile.exists()) {
            rootFile.mkdir();
        }
        //建立图片目录
        String imagePath = sd.getPath() + Config.appDir + Config.appImageDir;
        File imageFile = new File(imagePath);
        if (!imageFile.exists()) {
            imageFile.mkdir();
        }
        //建立APK目录
        String clientApkPath = sd.getPath() + Config.appDir + Config.clientApkDir;
        File clientApkFile = new File(clientApkPath);
        if (!clientApkFile.exists()) {
            clientApkFile.mkdir();
        }
        //建立异常目录
        String exceptionPath = sd.getPath() + Config.appDir + Config.appExceptionDir;
        File exceptionFile = new File(exceptionPath);
        if (!exceptionFile.exists()) {
            exceptionFile.mkdir();
        }
    }


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


    /**
     * 获取默认存储数据的文件夹
     */
    public static String getAppFileDir() {
        File sd = Environment.getExternalStorageDirectory();
        String path = sd.getPath() + Config.appDir;

        return path;
    }

    /**
     * 获取默认存储  异常数据的文件夹
     */
    public static String getAppFileDirForException() {
        File sd = Environment.getExternalStorageDirectory();
        String path = sd.getPath() + Config.appDir + Config.appExceptionDir;
        return path;
    }

    /**
     * 获取存储缓存图片的文件夹
     */
    public static String getImageFileDir() {
        File sd = Environment.getExternalStorageDirectory();
        String path = sd.getPath() + Config.appDir + Config.appImageDir;

        return path;
    }

    /**
     * 获取存储客户端apk新版本的文件夹
     */
    public static String getClientApkFileDir() {
        File sd = Environment.getExternalStorageDirectory();
        String path = sd.getPath() + Config.appDir + Config.clientApkDir;

        return path;
    }

    /**
     * 修改某文件的文件名
     *
     * @param oldFile     需要修改的文件的全路径
     * @param newFileName 新的全路径
     */
    public static boolean updateFileName(String oldFile, String newFileName) {
        return new File(oldFile).renameTo(new File(newFileName));
    }

    /**
     * 默认保存在主目录下
     * 同步方法
     *
     * @param bitmap 需要保存的图片
     * @param name   文件命名
     */
    public static boolean saveBitmapAsPNGToAppDir(Bitmap bitmap, String name) {
        return saveBitmapToAppDir(Bitmap.CompressFormat.PNG, bitmap, name);
    }

    /**
     * 默认保存在主目录下
     * 同步方法
     *
     * @param bitmap 需要保存的图片
     * @param name   文件命名
     */
    public static boolean saveBitmapAsJPEGToAppDir(Bitmap bitmap, String name) {
        return saveBitmapToAppDir(Bitmap.CompressFormat.JPEG, bitmap, name);
    }

    /**
     * 默认保存在主目录下
     * 同步方法
     *
     * @param format 图片格式
     * @param bitmap 需要保存的图片
     * @param name   文件命名
     */
    public static boolean saveBitmapToAppDir(Bitmap.CompressFormat format, Bitmap bitmap, String name) {
        //得到外部存储卡的路径
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //无内存卡
            return false;
        }
        String path = Environment.getExternalStorageDirectory().toString() + Config.appDir;
        String formatFlag = FILE_PNG;
        if (format == Bitmap.CompressFormat.PNG) {
            formatFlag = FILE_PNG;
        } else if (format == Bitmap.CompressFormat.JPEG) {
            formatFlag = FILE_JPG;
        }
        //存储的图片的名称
        File file = new File(path, name + formatFlag);
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(format, 100, out);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 在根目录下获取 图片
     */
    public static File getRootFolderImage(Bitmap.CompressFormat format, String name) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().toString() + Config.appDir;
            File file = null;
            if (format == Bitmap.CompressFormat.JPEG) {
                file = new File(path, name + FILE_JPG);
            } else if (format == Bitmap.CompressFormat.PNG) {
                file = new File(path, name + FILE_PNG);
            }
            if (file != null) {
                try {
                    if (FileUtil.getFileSizes(file) > 2000) {
                        //如果文件大于 2000 B
                        return file;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    //保存异常到手机内存卡
    public static void saveExceptionToSDCard(Context context, Throwable ex) throws Exception {
        // File file = YDFileUtils.getSaveFile(logPath, UESystemTool.getDataTime("yyyy-MM-dd-HH-mm-ss") + FILE_NAME_SUFFIX);
        File file = new File(getAppFileDirForException(), DateUtil.getDataTime("yyyy-MM-dd-HH-mm-ss") + FILE_NAME_SUFFIX);

        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        // 导出发生异常的时间
        pw.println(DateUtil.getDataTime("yyyy-MM-dd-HH-mm-ss"));
        // 导出手机信息
        dumpPhoneInfo(context, pw);

        pw.println();
        // 导出异常的调用栈信息
        ex.printStackTrace(pw);
        pw.close();
    }

    // 导出手机信息
    private static void dumpPhoneInfo(Context mContext, PrintWriter pw) throws PackageManager.NameNotFoundException {
        // 应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App Version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);
        pw.println();

        // android版本号
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);
        pw.println();

        // 手机制造商
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);
        pw.println();

        // 手机型号
        pw.print("Model: ");
        pw.println(Build.MODEL);
        pw.println();

        // cpu架构
        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
        pw.println();
    }

    /**
     * Image 先保存到本地，再转化为Bitmap
     */
    @SuppressLint("NewApi")
    public static Bitmap imageTransformBitmap(Image image, String imageSaveName) {
        if (image == null || imageSaveName == null) {
            return null;
        }

        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        //每个像素的间距
        int pixelStride = planes[0].getPixelStride();
        //总的间距
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        image.close();
        File fileImage = null;
        if (bitmap != null) {
            try {
                fileImage = new File(getImageFileDir() + File.separator + imageSaveName + FileUtil.FILE_PNG);
                if (!fileImage.exists()) {
                    fileImage.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(fileImage);
                if (out != null) {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    out.flush();
                    out.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                fileImage = null;
            } catch (IOException e) {
                e.printStackTrace();
                fileImage = null;
            }
        }

        if (fileImage != null) {
            return bitmap;
        }
        return null;
    }
//==================================================================================================

    /**
     * Uri转File
     */
    @SuppressLint("NewApi")
    public static String getPathByUri4kitkat(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                // ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {
                // DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                // MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // MediaStore
            // (and
            // general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // File
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

//==================================================================================================

    /**
     * File Path To Media Uri
     * File 转 Uri
     */

    public static Uri getMediaUriFromPath(Context context, String path) {
        Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = context.getContentResolver().query(mediaUri,
                null,
                MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                new String[]{path.substring(path.lastIndexOf("/") + 1)},
                null);

        Uri uri = null;
        if (cursor.moveToFirst()) {
            uri = ContentUris.withAppendedId(mediaUri,
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        }
        cursor.close();
        return uri;
    }


//==================================================================================================


    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        boolean flag;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }
        if (!flag) {
            return false;
        }
        //删除当前空目录
        return dirFile.delete();
    }

    /**
     * 根据路径删除指定的目录或文件，无论存在与否
     *
     * @param filePath 要删除的目录或文件
     * @return 删除成功返回 true，否则返回 false。
     */
    public static boolean deleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                // 为文件时调用删除文件方法
                return deleteFile(filePath);
            } else {
                // 为目录时调用删除目录方法
                return deleteDirectory(filePath);
            }
        }
    }


    /**
     * 获取文件得到大小
     *
     * @return long  --B--   KB  MB
     */
    public static long getFileSizes(File f) throws Exception {
        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s = fis.available();
            fis.close();
        } else {
            f.createNewFile();
        }

        return s;
    }

    /***
     * 获取文件类型
     *
     * @param paramString
     * @return
     */
    public static String getFileType(String paramString) {
        String str = null;

        if (!TextUtils.isEmpty(paramString)) {
            int i = paramString.lastIndexOf('.'); //得到最后一个点的下标
            if (!(i <= -1)) {
                str = paramString.substring(i + 1);
            }
        }
        return str;
    }


}
