package com.xugame.gameconsole.util;


import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Util {

    public static boolean IS_DEBUG = true;//测试用，发布版本为false

    private static final String TAG = "UtilTAG";
    public static int mYKDevicesId = -1;
    private static final float WIDTH = 1920;
    private static final float HEIGHT = 1080;
    private static float sScale = 1.0f;
    private static int sRectifyX = 0;
    private static int sRectifyY = 0;
    private static int sScreenW;
    private static int sScreenH;

    private static boolean sInitDone = false;

    public static boolean homeBottomIsFirst = true;
    private static Toast toast;

    public static int HB_COUNT = 0;


    public static void init(Context context) {
        homeBottomIsFirst = true;
        if (Util.sInitDone)
            return;

        Display display;
        DisplayMetrics metrics = new DisplayMetrics();

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        display = wm.getDefaultDisplay();
        display.getRealMetrics(metrics);
//        display.getMetrics(metrics);

        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        DebugUtil.i(TAG, "width=" + width + "height=" + height + "dpi=" + metrics.densityDpi);
        if (width < height) {
            int tmp = width;
            width = height;
            height = tmp;
        }

        Util.sScreenW = width;
        Util.sScreenH = height;

        float scaleX = (float) width / Util.WIDTH;
        float scaleY = (float) height / Util.HEIGHT;

        Util.sScale = scaleX <= scaleY ? scaleX : scaleY;

        if (Util.sScale == scaleX
                && Util.sScale != scaleY) {
            Util.sRectifyY = (int) ((scaleY - Util.sScale) * height / 2);
        } else if (Util.sScale == scaleY
                && Util.sScale != scaleX) {
            Util.sRectifyX = (int) ((scaleX - Util.sScale) * width / 2);
        } else
            ;

        Util.sInitDone = true;
    }


    public static Bitmap getAlplaBitmap(Bitmap sourceImg, int number) {

        int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
        sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg.getWidth(), sourceImg.getHeight());
        number = number * 255 / 100;
        for (int i = 0; i < argb.length; i++) {
            argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);
        }
        sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Bitmap.Config.ARGB_8888);

        return sourceImg;

    }


    public static ArrayList<String> getExistStorage(Context context) {
        ArrayList<String> resList = new ArrayList<>();
        StorageManager storageManager = (StorageManager) context.getSystemService(Context
                .STORAGE_SERVICE);
        try {
            boolean isSD = false;
            String exSD = null;
            if (Environment.getExternalStorageState().endsWith(Environment.MEDIA_MOUNTED)) {
                exSD = Environment.getExternalStorageDirectory().getAbsolutePath();
                isSD = true;
                resList.add(exSD);
            }
            Class<?>[] paramClasses = {};
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", paramClasses);
            getVolumePathsMethod.setAccessible(true);
            Object[] params = {};
            Object invoke = getVolumePathsMethod.invoke(storageManager, params);
            String[] result = (String[]) invoke;

//            String local = Environment.getDataDirectory().getAbsolutePath();
//            resList.add(local);
            for (int i = 0; i < result.length; i++) {
                resList.add(result[i]);
//                Method getVolumeState = storageManager.getClass().getMethod(
//                        "getVolumeState", String.class);
//                String state = (String) getVolumeState.invoke(storageManager,
//                        result[i]);
//                if (Environment.MEDIA_MOUNTED.equals(state)) {
//
//                }
            }
            ArrayList<String> arrayListnew = new ArrayList<>();
            for (String s : resList) {
                if (!arrayListnew.contains(s)) {
                    File file = new File(s);
                    if (file.exists()) {
                        Method getVolumeState = storageManager.getClass().getMethod(
                                "getVolumeState", String.class);
                        String state = (String) getVolumeState.invoke(storageManager,
                                s);
                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                            arrayListnew.add(s);
                        }
                    }
                    //  arrayListnew.add(s);
                    //便利旧集合没有就添加到新集合
                }
            }
            return arrayListnew;
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getNetFileSizeDescription(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.0");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            } else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }


    public static int getNetType(Context context) {
        int type = -1;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null) {
            switch (networkINfo.getType()) {
                case ConnectivityManager.TYPE_ETHERNET:
                    type = 0;
                    break;
                case ConnectivityManager.TYPE_WIFI:
                    type = 1;
                    break;
                default:
                    break;
            }
        }
        return type;
    }

    /**
     * get the real size for the current devices
     *
     * @param context
     * @param name
     * @return
     */
    public static int getSize(Context context, String name) {
        return (int) (context.getResources().getDimensionPixelSize(
                ResUtil.getDimID(context, name)) * Util.sScale);
    }

    public static int getSize(int size) {
        return (int) (Util.sScale * size);
    }

    public static float getFloatSize(float size) {
        return (Util.sScale * size);
    }

    /**
     * get total x coordinates
     *
     * @param context
     * @param name
     * @return
     */
    public static int getsRectifyX(Context context, String name) {
        return (int) (context.getResources().getDimensionPixelSize(
                ResUtil.getDimID(context, name)) * Util.sScale) + Util.sRectifyX;
    }

    public static int getsRectifyX(int size) {
        return (int) (size * Util.sScale) + Util.sRectifyX;
    }

    /**
     * get total y coordinates
     *
     * @param context
     * @param name
     * @return
     */
    public static int getRectifyY(Context context, String name) {
        return (int) (context.getResources().getDimensionPixelSize(
                ResUtil.getDimID(context, name)) * Util.sScale) + Util.sRectifyY;
    }

    public static int getRectifyY(int size) {
        return (int) (size * Util.sScale) + Util.sRectifyY;
    }

    public static int getScreenWidth() {
        return Util.sScreenW;
    }

    public static int getScreenHeight() {
        return Util.sScreenH;
    }

    public static void setFullScreen(Activity activity) {
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    public static int execCMD(String[] paramString) {
        try {
            Process localProcess = Runtime.getRuntime().exec(paramString);
//            localProcess.waitFor();
            int result = localProcess.exitValue();
            return result;
        } catch (Exception localException) {
            localException.printStackTrace();
            return -1;
        }
    }

    public static boolean isRoot() {
        String[] cmd = {"ls", "-l"};
        int i = execCMD(cmd);
        if (i == 0) {
            return true;
        }
        return false;

    }

    public static boolean queryRootPermission() {
        Process process = null;
        try {
            String[] root = {"su", "arcade"};
            process = Runtime.getRuntime().exec(root);
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("mount -o remount rw, /system\n");
            os.flush();

            os.writeBytes("touch /data/123.txt\n");
            os.flush();

            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
            os.close();

            int result = process.exitValue();
            if (result == 0)
                return true;

        } catch (Exception e) {
            return false;
        }

        return false;
    }


    public static boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        Intent i = manager.getLaunchIntentForPackage(packageName);
        if (i == null) {
            return false;
        }
        return true;
    }

    public static void startOtherApp(Context context, String packageName) {
        Intent intent = context.getPackageManager().
                getLaunchIntentForPackage(packageName);
        context.startActivity(intent);
    }


    public static int getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode = -1;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static int getVersionCode(Context context, String pkg) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode = -1;
        try {
            packageInfo = packageManager.getPackageInfo(pkg, 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static void deleteDir(File dir) {
        if (!dir.exists())
            return;

        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children == null)
                return;

            for (int i = 0; i < children.length; i++)
                deleteDir(new File(dir, children[i]));
        }
    }


    public static void deleteSaveDir(File dir) {
        if (!dir.exists())
            return;

        if (dir.isDirectory()) {
            String[] children = dir.list();

            for (int i = 0; i < children.length; i++) {
                File file = new File(dir, children[i]);
                if (file.isDirectory())
                    deleteDir(file);
                else
                    file.delete();
            }
        }
    }


    public static SpannableStringBuilder getSpannable(String selNum, String allNum) {
        String center = "/";
        SpannableStringBuilder builder
                = new SpannableStringBuilder(selNum + center + allNum);
        ForegroundColorSpan span1 = new ForegroundColorSpan(0xFF2979FF);
        ForegroundColorSpan span2 = new ForegroundColorSpan(0XFFFFFFFF);
        AbsoluteSizeSpan absSpan = new AbsoluteSizeSpan(Util.getSize(140));
        builder.setSpan(absSpan, 0, selNum.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(span2, selNum.length(), selNum.length() + center.length() + allNum.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (mConnectivityManager == null) {
                return false;
            }
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    public static boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            //  Timber.d(info.toString());
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            //Timber.d(e.toString());
            return false;
        }
    }

    public static String formatTime(Long ms) {
        if (ms == null && ms < 0)
            return "null";

        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
//        if(day > 0) {
//            sb.append(day+"天");
//        }

        if (hour >= 10) {
            sb.append(hour + ":");
        } else if (hour > 0 && hour < 10) {
            sb.append("0" + hour + ":");
        } else if (hour <= 0) {
            sb.append("00:");
        }

        if (minute >= 10) {
            sb.append(minute + ":");
        } else if (minute > 0 && minute < 10) {
            sb.append("0" + minute + ":");
        } else if (minute <= 0) {
            sb.append("00:");
        }

//        if(minute > 0) {
//            sb.append(minute+":");
//        }else {
//            sb.append("00:");
//        }

        if (second >= 10) {
            sb.append(second);
        } else if (second > 0 && second < 10) {
            sb.append("0" + second);
        } else if (second <= 0) {
            sb.append("00");
        }

//        if(second > 0) {
//            sb.append(second);
//        }
//        if(milliSecond > 0) {
//            sb.append(milliSecond+"毫秒");
//        }
        return sb.toString();
    }

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }


    public static String autoSplitText(final TextView tv, final String indent) {
        final String rawText = tv.getText().toString(); //原始文本
        final Paint tvPaint = tv.getPaint(); //paint，包含字体等信息
        final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度

        //将缩进处理成空格
        String indentSpace = "";
        float indentWidth = 0;
        if (!TextUtils.isEmpty(indent)) {
            float rawIndentWidth = tvPaint.measureText(indent);
            if (rawIndentWidth < tvWidth) {
                while ((indentWidth = tvPaint.measureText(indentSpace)) < rawIndentWidth) {
                    indentSpace += " ";
                }
            }
        }

        //将原始文本按行拆分
        String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");
        StringBuilder sbNewText = new StringBuilder();
        for (String rawTextLine : rawTextLines) {
            if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                //如果整行宽度在控件可用宽度之内，就不处理了
                sbNewText.append(rawTextLine);
            } else {
                //如果整行宽度超过控件可用宽度，则按字符测量，在超过可用宽度的前一个字符处手动换行
                float lineWidth = 0;
                for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                    char ch = rawTextLine.charAt(cnt);
                    //从手动换行的第二行开始，加上悬挂缩进
                    if (lineWidth < 0.1f && cnt != 0) {
                        sbNewText.append(indentSpace);
                        lineWidth += indentWidth;
                    }
                    lineWidth += tvPaint.measureText(String.valueOf(ch));
                    if (lineWidth <= tvWidth) {
                        sbNewText.append(ch);
                    } else {
                        sbNewText.append("\n");
                        lineWidth = 0;
                        --cnt;
                    }
                }
            }
            sbNewText.append("\n");
        }

        //把结尾多余的\n去掉
        if (!rawText.endsWith("\n")) {
            sbNewText.deleteCharAt(sbNewText.length() - 1);
        }

        return sbNewText.toString();
    }


    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean 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 if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * 6.0获取外置sdcard和U盘路径，并区分
     *
     * @param mContext
     * @param keyword  SD = "内部存储"; EXT = "SD卡"; USB = "U盘"
     * @return
     */
    public static String getStoragePath(Context mContext, String keyword) {
        String targetpath = "";
        StorageManager mStorageManager = (StorageManager) mContext
                .getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");

            Method getPath = storageVolumeClazz.getMethod("getPath");

            Object result = getVolumeList.invoke(mStorageManager);

            final int length = Array.getLength(result);

            Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");


            for (int i = 0; i < length; i++) {

                Object storageVolumeElement = Array.get(result, i);

                String userLabel = (String) getUserLabel.invoke(storageVolumeElement);

                String path = (String) getPath.invoke(storageVolumeElement);

                if (userLabel.contains(keyword)) {
                    targetpath = path;
                }

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return targetpath;
    }

    public static String getTime(int second) {
//        if (second < 10) {
//            return second + "秒";
//        }
        if (second < 60) {
            return second + "seconds";
        }
        if (second < 3600) {
            int minute = second / 60;
            second = second - minute * 60;
            if (minute < 10) {
                if (second < 10) {
                    return minute + "minutes" + second + "seconds";
                }
                return minute + "minutes" + second + "seconds";
            }
            if (second < 10) {
                return minute + "minutes" + second + "seconds";
            }
            return minute + "minutes" + second + "seconds";
        }
        int hour = second / 3600;
        int minute = (second - hour * 3600) / 60;
        second = second - hour * 3600 - minute * 60;
        if (hour < 10) {
            if (minute < 10) {
                if (second < 10) {
                    return hour + "H" + minute + "minutes" + second + "seconds";
                }
                return hour + "H" + minute + "minutes" + second + "seconds";
            }
            if (second < 10) {
                return hour + "H" + minute + "minutes" + second + "seconds";
            }
            return hour + "H" + minute + "minutes" + second + "seconds";
        }
        if (minute < 10) {
            if (second < 10) {
                return hour + "H" + minute + "minutes" + second + "seconds";
            }
            return hour + "H" + minute + "minutes" + second + "seconds";
        }
        if (second < 10) {
            return hour + "H" + minute + "minutes" + second + "seconds";
        }
        return hour + "H" + minute + "minutes" + second + "seconds";
    }

    public static String getTime(long second) {
//        if (second < 10) {
//            return second + "秒";
//        }
        if (second < 1000) {
            return "1" + "s";
        }
        second = second / 1000;
        if (second < 60) {
            return second + "s";
        }
        if (second < 3600) {
            long minute = second / 60;
            second = second - minute * 60;
            if (minute < 10) {
                if (second < 10) {
                    return minute + "min " + second + "s";
                }
                return minute + "min " + second + "s";
            }
            if (second < 10) {
                return minute + "min " + second + "s";
            }
            return minute + "min " + second + "s";
        }
        long hour = second / 3600;
        long minute = (second - hour * 3600) / 60;
        second = second - hour * 3600 - minute * 60;
        if (hour < 10) {
            if (minute < 10) {
                if (second < 10) {
                    return hour + "H " + minute + "min " + second + "s";
                }
                return hour + "H " + minute + "min " + second + "s";
            }
            if (second < 10) {
                return hour + "H " + minute + "min " + second + "s";
            }
            return hour + "H " + minute + "min " + second + "s";
        }
        if (minute < 10) {
            if (second < 10) {
                return hour + "H " + minute + "min " + second + "s";
            }
            return hour + "H " + minute + "min " + second + "s";
        }
        if (second < 10) {
            return hour + "H " + minute + "min " + second + "s";
        }
        return hour + "H " + minute + "min " + second + "s";
    }

    private SpannableStringBuilder getBuild(long h, long min, long s) {
        String strH = "H";
        String strMin = "min";
        String strS = "s";
        SpannableStringBuilder builder
                = new SpannableStringBuilder(h + strH + " " + min + strMin + " " + s + strS);
//        ForegroundColorSpan span1 = new ForegroundColorSpan(0xFF2979FF);
//        ForegroundColorSpan span2 = new ForegroundColorSpan(0XFFFFFFFF);
//        AbsoluteSizeSpan absSpan = new AbsoluteSizeSpan(Util.getSize(140));
//        builder.setSpan(absSpan, 0, selNum.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.setSpan(span2, selNum.length(), selNum.length() + center.length() + allNum.length(),
//                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }


    /**
     * MTK8163
     */
    public static boolean silentInstall(PackageManager packageManager, String apkPath) {
        DebugUtil.i(TAG, "silentInstall" + apkPath);
        Class<?> pmClz = packageManager.getClass();
        try {
            if (Build.VERSION.SDK_INT >= 21) {

                Class<?> aClass = Class.forName("android.app.PackageInstallObserver");
                Constructor<?> constructor = aClass.getDeclaredConstructor();
                constructor.setAccessible(true);
                Object installObserver = constructor.newInstance();
                Method method = pmClz.getDeclaredMethod("installPackage", Uri.class, aClass, int.class, String.class);
                method.setAccessible(true);
                method.invoke(packageManager, Uri.fromFile(new File(apkPath)), installObserver, 2, null);
            } else {
                Method method = pmClz.getDeclaredMethod("installPackage", Uri.class, Class.forName("android.content.pm.IPackageInstallObserver"), int.class, String.class);
                method.setAccessible(true);
                method.invoke(packageManager, Uri.fromFile(new File(apkPath)), null, 2, null);
            }
            DebugUtil.i(TAG, "silentInstall1111111");
            return true;
        } catch (Exception e) {
            DebugUtil.i(TAG, "silentInsta222222222" + e.getLocalizedMessage());
        }

        return false;
    }

    //MTK8168
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void install28(Context context, String apkFilePath) {
        Log.d(TAG, "install28 path=" + apkFilePath);
        File apkFile = new File(apkFilePath);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams sessionParams
                = new PackageInstaller.SessionParams(PackageInstaller
                .SessionParams.MODE_FULL_INSTALL);
        sessionParams.setSize(apkFile.length());

        int sessionId = createSession(packageInstaller, sessionParams);
        Log.d(TAG, "install28  sessionId=" + sessionId);
        if (sessionId != -1) {
            boolean copySuccess = copyInstallFile(packageInstaller, sessionId, apkFilePath);
            Log.d(TAG, "install28  copySuccess=" + copySuccess);
            if (copySuccess) {
                execInstallCommand(context, packageInstaller, sessionId);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static void execInstallCommand(Context context, PackageInstaller packageInstaller, int sessionId) {
        PackageInstaller.Session session = null;
        try {
            session = packageInstaller.openSession(sessionId);
            Intent intent = new Intent();
//            PendingIntent pendingIntent = PendingIntent.
//                    getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
//            Intent intent = new Intent(context, receiver);
//            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
//                    1, intent,
//                    PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(pendingIntent.getIntentSender());
            Log.i(TAG, "begin session");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static int createSession(PackageInstaller packageInstaller,
                                     PackageInstaller.SessionParams sessionParams) {
        int sessionId = -1;
        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionId;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static boolean copyInstallFile(PackageInstaller packageInstaller,
                                           int sessionId, String apkFilePath) {
        InputStream in = null;
        OutputStream out = null;
        PackageInstaller.Session session = null;
        boolean success = false;
        try {
            File apkFile = new File(apkFilePath);
            session = packageInstaller.openSession(sessionId);
            out = session.openWrite("base.apk", 0, apkFile.length());
            in = new FileInputStream(apkFile);
            int total = 0, c;
            byte[] buffer = new byte[65536];
            while ((c = in.read(buffer)) != -1) {
                total += c;
                out.write(buffer, 0, c);
            }
            session.fsync(out);
            Log.i(TAG, "streamed " + total + " bytes");
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }

    public static SpannableString setTextStrColor(SpannableString spannableString, int color, int startIndex, int endIndex) {
        spannableString.setSpan(new ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    public static SpannableString setTextStrSize(SpannableString spannableString, int textSize, int startIndex, int endIndex) {
        spannableString.setSpan(new AbsoluteSizeSpan(textSize), startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }


    /**
     * 忘记所有wifi密码
     */
    public static void removeAllWIFI(Context context) {
        WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        WifiConfiguration mWifiConfig = new WifiConfiguration();
        List<WifiConfiguration> wifiConfigs = mWifiManager.getConfiguredNetworks();
        //忘记所有wifi密码
        for (WifiConfiguration wifiConfig : wifiConfigs) {
            Log.e(TAG, "SSID = " + wifiConfig.SSID + " netId = " + String.valueOf(wifiConfig.networkId));
//            mWifiManager.forget(wifiConfig.networkId, null);
            forgetNetwork(mWifiManager, wifiConfig.networkId);
        }
    }

    // 忘记网络.
    public static void forgetNetwork(WifiManager manager, int networkId) {
        if (manager == null) {
            return;
        }
        try {
            Method forget = manager.getClass().getDeclaredMethod("forget", int.class, Class.forName("android.net.wifi.WifiManager$ActionListener"));
            if (forget != null) {
                forget.setAccessible(true);
                forget.invoke(manager, networkId, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isGamePad(InputDevice dev) {
        if (dev.getName().toLowerCase().indexOf("qanba") != -1)
            return true;
        //add for mibox3
        if (dev.getName().equals("eventserver-Joystick")
                && Build.MANUFACTURER.equals("Xiaomi")
            /*&& Build.MODEL.equals("MiBOX3")*/)
            return false;

        if (0x1000511 == (dev.getSources() & 0x1000511)) {
            if (dev.isVirtual())
                return false;
//
//			boolean HAT_X = false;
//			boolean HAT_Y = false;

            InputDevice.MotionRange range = dev.getMotionRange(MotionEvent.AXIS_HAT_X);
            if (range == null)
                return false;

            range = dev.getMotionRange(MotionEvent.AXIS_HAT_Y);
            if (range == null)
                return false;


            List<InputDevice.MotionRange> list = dev.getMotionRanges();

            boolean axisY = false;
            boolean axisX = false;
            for (InputDevice.MotionRange motion : list) {
                if (motion.getAxis() == MotionEvent.AXIS_X && motion.getMax() == 1 && motion.getMin() == -1)
                    axisX = true;
                else if (motion.getAxis() == MotionEvent.AXIS_Y && motion.getMax() == 1 && motion.getMin() == -1)
                    axisY = true;
            }


            return axisX && axisY;
        } else
            return false;
    }

    /**
     * 获得sd卡剩余容量，即可用大小
     */
    public static long getPathAvailableSize(String path) {
        long size = 0;
        StatFs sf = new StatFs(path);
        if (Build.VERSION.SDK_INT < 18) {
            size = (long) ((long) sf.getAvailableBlocks() * (long) sf.getBlockSize());
        } else {
            size = sf.getAvailableBlocksLong() * sf.getBlockSizeLong();
        }
        return size;
    }


    public static int getRankColor(int rankLevel) {
        int color;
        switch (rankLevel) {
            case -1:
            case 0:
            case 1:
                color = 0xFF000000;
                break;
            case 2:
                color = 0xFF0CC66C;
                break;
            case 3:
                color = 0xFF168DFF;
                break;
            case 4:
                color = 0xFFEA60FF;
                break;
            case 5:
                color = 0xFFFFBA00;
                break;
            case 6:
            default:
                color = 0xFFFF2630;
                break;
        }

        return color;
    }


    public static String createSavePath(int gameID) {
        String path = Environment.getExternalStorageDirectory().getPath()
                + File.separator + "arcade" + File.separator
                + "save" + File.separator
                + "" + gameID + File.separator;

        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();

        return path;
    }

    public static String getLocalInitPath(int gameID) {

        String path = "/mnt/sdcard/arcade/rom/" + gameID + ".init";

        return path;
    }

    public static String getRomSDCardPath(String rom_pkg_name, String suffix) {
        return "/mnt/sdcard/arcade/rom/" + rom_pkg_name + "." + suffix;
    }

    public static String getInitSDCardPath(String rom_pkg_name) {
        return "/mnt/sdcard/arcade/rom/" + rom_pkg_name + ".init";
    }

    public static String getAPKSDCardPath(String rom_pkg_name) {
        String path = "/mnt/sdcard/arcade/apk/";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();

        return path + rom_pkg_name + ".apk";
    }

    public static String createUpdatePath(String versionName) {
        String path = "/mnt/sdcard/arcade/update/";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();

        return path + versionName + ".apk";
    }


    public static String getLocalRoomPath(Context activity, int gameID) {

//        String dataPath = activity.getDir("data", Activity.MODE_PRIVATE).getPath() + File.separator;
//        String path = dataPath + gameID;
        String path = "/mnt/sdcard/arcade/rom/";

        if (gameID < 300) {
            path += gameID;
        } else {
            if (gameID == 667)
                path += "xman";
            else if (gameID == 668)
                path += "mshin";
        }
        if (gameID == 667 || gameID == 668)
            path += ".smc";
        else if (gameID == 0 || gameID == 3)
            path += ".fba";
        else
            path += ".zip";

        return path;
    }

    public static void updateG1UserDiamonds(Context context, int dimonds) {
        SharedPreferences sp = context.getSharedPreferences("g1_user_account", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_user_diamonds", dimonds);
        editor.commit();
    }

    public static void updateG1UserMembers(Context context, int members) {
        SharedPreferences sp = context.getSharedPreferences("g1_user_account", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_user_members", members);
        editor.commit();
    }

    public static void saveMALLRuleState(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_app_config_file", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("g1_mall_rule_read_states", true);
        editor.commit();
    }

    public static boolean getMALLRuleState(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_app_config_file", Context.MODE_PRIVATE);
        return sp.getBoolean("g1_mall_rule_read_states", false);
    }


    public static void saveLEDStatus(Context context, int status) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_setting_led_status", status);
        editor.commit();
    }

    public static int getLEDStatus(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        return sp.getInt("g1_setting_led_status", 0);
    }


    public static void saveScreen(Context context, int dimonds) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_setting_screen", dimonds);
        editor.commit();
    }

    public static int getScreen(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        return sp.getInt("g1_setting_screen", 0);
    }

    public static void saveQualityScreen(Context context, int dimonds) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_setting_quality_screen", dimonds);
        editor.commit();
    }

    public static int getQualityScreen(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_setting_table", Context.MODE_PRIVATE);
        return sp.getInt("g1_setting_quality_screen", 0);
    }


    public static void setBaseUrlID(Context context, int serverid) {
        SharedPreferences sp = context.getSharedPreferences("g1_base_server_config", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_base_server_id", serverid);
        editor.commit();
    }

    public static int getBaseUrlID(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_base_server_config", Context.MODE_PRIVATE);
        return sp.getInt("g1_base_server_id", 0);
    }


    public static void setAPPIsFirst(Context context, boolean isFirst) {
        SharedPreferences sp = context.getSharedPreferences("g1_app_config_file", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("g1_config_is_first", isFirst);
        editor.commit();
    }

    public static boolean getAPPIsFirst(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_app_config_file", Context.MODE_PRIVATE);
        return sp.getBoolean("g1_config_is_first", true);
    }


    public static void clearG1Account(Context context) {
        SharedPreferences sp = context.getSharedPreferences("g1_user_account", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("g1_user_id", -1);
        editor.putString("g1_user_name", "");
        editor.putString("g1_user_icon_url", "");
        editor.putString("g1_user_password", "");
        editor.putString("g1_user_token", "");
        editor.putString("g1_user_nickname", "");
        editor.putInt("g1_user_diamonds", 0);
        editor.putInt("g1_user_members", 0);
        editor.putInt("g1_user_coins", 0);
        editor.commit();
    }

    //将B转化为KB,M,GB
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }


    //Z = 字母 S = 数字 T = 特殊字符
    public static String passwordStrong(String passwordStr) {
        if (TextUtils.equals("", passwordStr)) {
            return "出现故障";
        }
        String regexZ = "\\d*";
        String regexS = "[a-zA-Z]+";
        String regexZS = "\\w*";
        String regexZSS = "^[a-zA-Z0-9]{6,12}$";


        if (passwordStr.matches(regexZ)) {
            if (passwordStr.length() < 10)
                return "弱";
            else
                return "中";
        }
        if (passwordStr.matches(regexS)) {
            if (passwordStr.length() < 10)
                return "弱";
            else
                return "中";
        }

        if (passwordStr.matches(regexZS)) {
            if (passwordStr.length() < 10)
                return "中";
            else
                return "强";
        }

        return passwordStr;
    }

    public static int getLangID(Context context) {
        int temp = 0;
        String defaultLan = Locale.getDefault().getLanguage();
        String LangStr[] = {"en", "ksh", "ca", "it", "es",
                "pt", "ru", "ja", "kr", "zh", ""};
        for (int i = 0; i < LangStr.length; i++) {
            if (defaultLan.equals(LangStr[i])) {
                temp = i;
                break;
            }
        }
        return temp;
    }

    public static String getCountryFromID(int id) {
        String[] mISO3County = {
                "安道尔", "阿联酋", "阿富汗", "安提瓜和巴布达", "安圭拉", "阿尔巴尼亚", "亚美尼亚", "安哥拉", "南极洲", "阿根廷", "美属萨摩亚", "奥地利", "澳大利亚", "阿鲁巴", "奥兰群岛", "阿塞拜疆", "波黑", "巴巴多斯", "孟加拉", "比利时", "布基纳法索", "保加利亚", "巴林", "布隆迪", "贝宁", "圣巴泰勒米岛", "百慕大", "文莱", "玻利维亚", "荷兰加勒比区", "巴西", "巴哈马", "不丹", "布韦岛", "博茨瓦纳", "白俄罗斯", "伯利兹", "加拿大", "科科斯群岛", "中非", "瑞士", "智利", "喀麦隆", "哥伦比亚", "哥斯达黎加", "古巴", "佛得角", "圣诞岛", "塞浦路斯", "捷克", "德国", "吉布提", "丹麦", "多米尼克", "多米尼加", "阿尔及利亚", "厄瓜多尔", "爱沙尼亚", "埃及", "西撒哈拉", "厄立特里亚", "西班牙", "芬兰", "斐济群岛", "马尔维纳斯群岛（ 福克兰）", "密克罗尼西亚联邦", "法罗群岛", "法国", "加蓬", "格林纳达", "格鲁吉亚", "法属圭亚那", "加纳", "直布罗陀", "格陵兰", "几内亚", "瓜德罗普", "赤道几内亚", "希腊", "南乔治亚岛和南桑威奇群岛", "危地马拉", "关岛", "几内亚比绍", "圭亚那", "香港", "赫德岛和麦克唐纳群岛", "洪都拉斯", "克罗地亚", "海地", "匈牙利", "印尼", "爱尔兰", "以色列", "马恩岛", "印度", "英属印度洋领地", "伊拉克", "伊朗", "冰岛", "意大利", "泽西岛", "牙买加", "约旦", "日本", "柬埔寨", "基里巴斯", "科摩罗", "科威特", "开曼群岛", "黎巴嫩", "列支敦士登", "斯里兰卡", "利比里亚", "莱索托", "立陶宛", "卢森堡", "拉脱维亚", "利比亚", "摩洛哥", "摩纳哥", "摩尔多瓦", "黑山", "法属圣马丁", "马达加斯加", "马绍尔群岛", "马其顿", "马里", "缅甸", "澳门", "马提尼克", "毛里塔尼亚", "蒙塞拉特岛", "马耳他", "马尔代夫", "马拉维", "墨西哥", "马来西亚", "纳米比亚", "尼日尔", "诺福克岛", "尼日利亚", "尼加拉瓜", "荷兰", "挪威", "尼泊尔", "瑙鲁", "阿曼", "巴拿马", "秘鲁", "法属波利尼西亚", "巴布亚新几内亚", "菲律宾", "巴基斯坦", "波兰", "皮特凯恩群岛", "波多黎各", "巴勒斯坦", "帕劳", "巴拉圭", "卡塔尔", "留尼汪", "罗马尼亚", "塞尔维亚", "俄罗斯", "卢旺达", "所罗门群岛", "塞舌尔", "苏丹", "瑞典", "新加坡", "斯洛文尼亚", "斯瓦尔巴群岛和 扬马延岛", "斯洛伐克", "塞拉利昂", "圣马力诺", "塞内加尔", "索马里", "苏里南", "南苏丹", "圣多美和普林西比", "萨尔瓦多", "叙利亚", "斯威士兰", "特克斯和凯科斯群岛", "乍得", "多哥", "泰国", "托克劳", "东帝汶", "突尼斯", "汤加", "土耳其", "图瓦卢", "坦桑尼亚", "乌克兰", "乌干达", "美国", "乌拉圭", "梵蒂冈", "委内瑞拉", "英属维尔京群岛", "美属维尔京群岛", "越南", "瓦利斯和富图纳", "萨摩亚", "也门", "马约特", "南非", "赞比亚", "津巴布韦", "中国 内地", "刚果（布）", "刚果（金）", "莫桑比克", "根西岛", "冈比亚", "北马里亚纳群岛", "埃塞俄比亚", "新喀里多尼亚", "瓦努阿图", "法属南部领地", "纽埃", "美国本土外小岛屿", "库克群岛", "英国", "特立尼达和多巴哥", "圣文森特和格林纳丁斯", "台湾", "新西兰", "沙特阿拉伯", "老挝", "朝鲜 北朝鲜", "韩国 南朝鲜", "葡萄牙", "吉尔吉斯斯坦", "哈萨克斯坦", "塔吉克斯坦", "土库曼斯坦", "乌兹别克斯坦", "圣基茨和尼维斯", "圣皮埃尔和密克隆", "圣赫勒拿", "圣卢西亚", "毛里求斯", "科特迪瓦", "肯尼亚", "蒙古国 蒙古", "荷属圣马丁", "库拉索"};
        if (id <= mISO3County.length) {
            return mISO3County[id];
        } else
            return "";
    }


    public static ArrayList<Integer> getLocalGameList(Context context, int userid) {
        SharedPreferences sp = context.getSharedPreferences("g1_local_" + userid, Context.MODE_PRIVATE);
        ArrayList<Integer> gamelist = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            int gID = sp.getInt("g1_local_gameids" + i, -1);
            if (gID >= 0) {
                gamelist.add(gID);
            }
        }
        return gamelist;
    }

    public static boolean isHaveGameID(Context context, int userid, int gameid) {
        SharedPreferences sp = context.getSharedPreferences("g1_local_" + userid, Context.MODE_PRIVATE);
        boolean isHave = false;
        for (int i = 0; i < 7; i++) {
            int gID = sp.getInt("g1_local_gameids" + i, -1);
            if (gameid == gID) {
                isHave = true;
                break;
            }
        }
        return isHave;
    }


    public static void saveLocalGameIDS(Context context, int userid, int gameid) {
        SharedPreferences sp = context.getSharedPreferences("g1_local_" + userid, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        ArrayList<Integer> gamelist = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            int gID = sp.getInt("g1_local_gameids" + i, -1);
            if (gID >= 0) {
                if (gID == gameid)
                    continue;
                gamelist.add(gID);
            }
        }
        DebugUtil.i(TAG, "save" + gamelist.size() + "==" + gameid);
        if (gamelist != null && gamelist.size() > 0) {
            gamelist.add(0, gameid);
            for (int i = 0; i < 7; i++) {
                if (i < gamelist.size()) {
                    editor.putInt("g1_local_gameids" + i, gamelist.get(i));
                } else
                    editor.putInt("g1_local_gameids" + i, -1);
            }
            DebugUtil.i(TAG, "save22=" + gamelist.size() + "==" + gameid);
        } else {
            editor.putInt("g1_local_gameids0", gameid);
            DebugUtil.i(TAG, "save33=" + gamelist.size() + "==" + gameid);
        }
        editor.commit();
    }


    //    public static String getMineGameIDStr(Context context, int userid) {
//        if (userid <= 0)
//            return null;
//        SharedPreferences sp = context.getSharedPreferences("g1_local_" + userid, Context.MODE_PRIVATE);
//        String strs = sp.getString("g1_local_gameids", "");
//        DebugUtil.i(TAG, "getMineGameIDStr" + strs);
//        return strs;
//    }
    public static String getIP(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    public static double formatDouble2(double d) {
        BigDecimal bigDecimal = new BigDecimal(d);
        double bg = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return bg;
    }


    /**
     * 得到CRC32校验码
     */
    public static int getCRC32(byte[] bytes) {
        int[] table = {
                0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
                0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
                0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
                0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
                0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
                0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
                0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
                0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
                0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
                0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
                0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
                0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
                0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
                0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
                0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
                0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
                0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
                0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
                0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
                0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
                0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
                0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
                0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
                0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
                0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
                0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
                0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
                0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
                0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
                0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
                0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
                0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
        };
        int crc = 0xffffffff;
        for (byte b : bytes) {
            crc = (crc >>> 8 ^ table[(crc ^ b) & 0xff]);
        }
        crc = crc ^ 0xffffffff;
        return crc;
    }


    public static void deleteAllSaveDir(File dir) {
        if (!dir.exists())
            return;
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children == null)
                return;
            for (int i = 0; i < children.length; i++) {
                File file = new File(dir, children[i]);
                if (file.isDirectory())
                    deleteAllSaveDir(file);
                else
                    file.delete();
            }
        }
    }


    public static ArrayList<String> getStorageUSBPath(Context context, boolean isUsb) {
        ArrayList<String> paths = new ArrayList<>();
        StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        Class<?> volumeInfoClazz;
        Class<?> diskInfoClaszz;
        try {
            volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
            diskInfoClaszz = Class.forName("android.os.storage.DiskInfo");
            Method StorageManager_getVolumes = Class.forName("android.os.storage.StorageManager").getMethod("getVolumes");
            Method VolumeInfo_GetDisk = volumeInfoClazz.getMethod("getDisk");
            Method VolumeInfo_GetPath = volumeInfoClazz.getMethod("getPath");
            Method DiskInfo_IsUsb = diskInfoClaszz.getMethod("isUsb");
            Method DiskInfo_IsSd = diskInfoClaszz.getMethod("isSd");
            List<Object> List_VolumeInfo = (List<Object>) StorageManager_getVolumes.invoke(mStorageManager);
            assert List_VolumeInfo != null;
            for (int i = 0; i < List_VolumeInfo.size(); i++) {
                Object volumeInfo = List_VolumeInfo.get(i);
                Object diskInfo = VolumeInfo_GetDisk.invoke(volumeInfo);
                if (diskInfo == null) continue;
                boolean sd = (boolean) DiskInfo_IsSd.invoke(diskInfo);
                boolean usb = (boolean) DiskInfo_IsUsb.invoke(diskInfo);
                File file = (File) VolumeInfo_GetPath.invoke(volumeInfo);
                if (isUsb == usb) {//usb
                    assert file != null;
                    String path = file.getAbsolutePath();
                    if (!TextUtils.isEmpty(path)) {
                        paths.add(path);
                    }
                    Log.i(TAG, "is Usb" + path);
                } else if (!isUsb == sd) {//sd
                    assert file != null;
                    String path = file.getAbsolutePath();
                    if (!TextUtils.isEmpty(path)) {
                        paths.add(path);
                    }
                }
            }
        } catch (Exception e) {
            Log.i(TAG, "[——————— ——————— Exception:" + e.getMessage() + "]");
            e.printStackTrace();
        }
        return paths;
    }
}
