package com.ycgis.macall.personalcenter.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;

import androidx.annotation.IntDef;
import androidx.core.content.FileProvider;

import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.p.callback.SelectReturnCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.DecimalFormat;
import java.util.List;

/**
 * created by:   Macall
 * create time:  2022/10/26 15:09
 * copyright:    @ruansee.com
 * Describe:
 */
public class FileUtils {

    private static String filePath;

    //文件路径
    public static String FILE_DIR = "file";
    //数据库文件路径
    public static String DB_DIR = "dateBase";
    //图片文件存储路径
    public static String IMAGE_DIR = "Image";
    //视频文件存储路径
    public static String VOID_DIR = "Void";
    //下载文件存储路径
    public static String DOWNLOADS_DIR = "downloads";
    //下载文件存储路径
    public static String LOG_DIR = "Log";

    /**
     * 初始化文件目录，Android10以下可以访问外部存储的任意位置，Android10（包括）以上只能访问指定目录。
     * 为适配Android 10 及以上，应用目录应存储在该目录下
     *
     * @param context 上下文环境
     * @return 文件录
     */
    public static String initFilePath(Context context) {
        if (StringUtil.isNullOrEmpty(filePath)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                filePath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath().replace("Documents", "");
                DOWNLOADS_DIR = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
                IMAGE_DIR = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator;
                VOID_DIR = context.getExternalFilesDir(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator;
                FILE_DIR = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + File.separator;
                DB_DIR = FILE_DIR + "/dateBase/";
                LOG_DIR = filePath + "log/";
            } else {
                // /storage/emulated/0/Android/data/com.spsj.data/files/Documents
                filePath = Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.ycgis.macall.personalcenter/";
                DOWNLOADS_DIR = filePath + "Downloads/";
                IMAGE_DIR = filePath + "Pictures/";
                VOID_DIR = filePath + "DCIM/";
                FILE_DIR = filePath + "Documents/";
                DB_DIR = FILE_DIR + "/dateBase/";
                LOG_DIR = filePath + "log/";
            }
        }
        return filePath;
    }

    public static String getPhotoName() {
        return System.currentTimeMillis() + ".jpg";
    }


    /**
     * @param context
     * @param attrsName
     * @param filePath
     * @return
     */
    public static File copyAPK(Context context, String attrsName, String filePath) {
        InputStream is = null;
        try {
            is = context.getAssets().open(attrsName);
            File destFile = new File(filePath, attrsName);
            if (destFile.exists()) {
                destFile.delete();
            }
//            if (!destFile.exists()) {
            return copy(is, destFile.getAbsolutePath());
//            }
//            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File copy(InputStream is, String path) {
        try {
            File file = new File(path);
            FileOutputStream fos = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();

            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    /**
     * 本地图片转 base64 字符
     *
     * @param filePath 图标全路径
     * @return base64 字符
     */
    public static String fileToBase64(String filePath) {
        if (StringUtil.isNullOrEmpty(filePath)) return "";
        File f = new File(filePath);
        if (!f.exists()) return "";
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(f);
            data = new byte[(int) f.length()];
            in.read(data);
            in.close();
//            return Base64.encodeBase64String(data);
//            return Base64.encodeBase64URLSafeString(data);
            return Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void deleteFiles(File file) {
        if (file == null || !file.exists()) return;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file1 = files[i];
                deleteFiles(file1);
            }
        } else {
            file.delete();
        }
    }

    /**
     * 计算文件
     * @param file      文件
     * @return          大小单位Bit
     */
    public static long calculateFileSize(File file) {
        long totals = 0;
        if (!file.exists()) return 0;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) return 0;
            for (File fl : files) {
                totals += calculateFileSize(fl);
            }
        } else {
            totals += file.length();
        }
        return totals;
    }

    /**
     * 文件重命名
     *
     * @param dir        文件路径
     * @param sourcePath 原文件名
     * @param targetPath 修改后的文件名
     * @return 是否修改成功
     */
    public static boolean renameFile(String dir, String sourcePath, String targetPath) {
        File toBeRenamed = new File(dir, sourcePath);
        //检查要重命名的文件是否存在，是否是文件
        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
            LogUtils.e("FileUtils", "待重命名文件不存在: " + sourcePath);
            return false;
        }
        File newFile = new File(dir, targetPath);
        //修改文件名
        return toBeRenamed.renameTo(newFile);
    }

    /*打开app*/
    @TargetApi(Build.VERSION_CODES.DONUT)
    private void doStartApplicationWithPackageName(Context context, String packagename) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    /**
     * 文件大小单位
     */
    @IntDef(value = {FileSizeFormType.B, FileSizeFormType.K, FileSizeFormType.M, FileSizeFormType.T})
    @Retention(RetentionPolicy.SOURCE)
    public @interface FileSizeFormType {
        int B = 0;  //bit
        int K = 1;  //KB
        int M = 2;  //MB
        int T = 3;  //TB
    }

    /**
     * 格式化文件大小
     *
     * @param fileSize 文件大小单位 bit
     * @param type     格式化单位{@link FileSizeFormType}
     * @return 格式化后的大小
     */
    public static String formatFileSize(long fileSize, int type) {
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        if (FileSizeFormType.K == type) {
            return decimalFormat.format((double)fileSize / 1024 )+ "K";
        } else if (FileSizeFormType.M == type) {
            return decimalFormat.format((double)fileSize / 1024 / 1024 )+ "M";
        } else if (FileSizeFormType.T == type) {
            return decimalFormat.format((double)fileSize / 1024 / 1024 / 1024) + "T";
        }
        return fileSize + "B";
    }

    /**
     * 打开原生APP
     *
     * @param context
     * @param strPackage 包名
     * @param callback
     */
    public static void startAPP(Context context, String strPackage, SelectReturnCallback<Boolean> callback) {
        try {
            // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
            PackageInfo packageinfo = null;
            try {
                packageinfo = context.getPackageManager().getPackageInfo(strPackage, 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                if (callback != null) {
                    callback.returnMsg(false);
                }
            }
            if (packageinfo == null) {
                if (callback != null) {
                    callback.returnMsg(false);
                }
                return;
            }
            // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(packageinfo.packageName);

            // 通过getPackageManager()的queryIntentActivities方法遍历
            List<ResolveInfo> resolveinfoList = context.getPackageManager()
                    .queryIntentActivities(resolveIntent, 0);

            ResolveInfo resolveinfo = resolveinfoList.iterator().next();
            if (resolveinfo != null) {
                // packagename = 参数packname
                String packageName = resolveinfo.activityInfo.packageName;
                // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
                String className = resolveinfo.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                //TODO 打开第三方应用 应当设置 启动模式为新的任务栈
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClassName(packageName, className);
                context.startActivity(intent);
            }
            ApiModel.uploadOperationLog("3","3","用户跳转到第三方应用："+strPackage);
        } catch (Exception e) {
            e.printStackTrace();
            if (callback != null) {
                callback.returnMsg(false);
            }
//            ToastUtil.centered(context, "没有安装应用，请至应用中心下载安装！");
        }
    }

    /**
     * 根据路径打开文件
     *
     * @param context 上下文
     * @param path    文件路径
     */
    public static void openFileByPath(Activity context, String path) {
        if (context == null || path == null) return;
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        Uri photoURI;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
            LogUtils.e("相机权限", "系统版本大于7.0");
//            String provider = context.getString(MResource.getIdByName(context.getApplication(), "string", "app_file_provider_authority"));
            photoURI = FileProvider.getUriForFile(context, context.getString(R.string.fileProviderName), file);
        } else {
            //7.0以下使用这种方式创建一个Uri
            photoURI = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //文件的类型
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type = "";
        for (int i = 0; i < MATCH_ARRAY.length; i++) {
            //判断文件的格式
            if (path.endsWith(MATCH_ARRAY[i][0])) {
                type = MATCH_ARRAY[i][1];
                break;
            }
        }
        try {
            //设置intent的data和Type属性
            intent.setDataAndType(photoURI, type);
            //跳转
            context.startActivity(intent);
        } catch (Exception e) { //当系统没有携带文件打开软件，提示
            ToastUtil.centered(context, "无法打开该格式文件!");
            e.printStackTrace();
        }
    }

    //建立一个文件类型与文件后缀名的匹配表
    private static final String[][] MATCH_ARRAY = {
            //{后缀名，    文件类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/zip"},
            {"", "*/*"}
    };

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree 旋转角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  旋转角度
     * @param bitmap 原图
     * @return bitmap 旋转后的图片
     */
    public static Bitmap rotateImage(int angle, Bitmap bitmap) {
        // 图片旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 得到旋转后的图片
        return Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

}
