package com.uiui.zyappstore.utils;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

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

import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.google.gson.JsonObject;
import com.uiui.zyappstore.BuildConfig;
import com.uiui.zyappstore.R;
import com.uiui.zyappstore.bean.LocalApp;
import com.uiui.zyappstore.gson.GsonUtils;
import com.uiui.zyappstore.receiver.InstallResultReceiver;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ApkUtils {
    private static final String TAG = ApkUtils.class.getSimpleName();

    public static synchronized boolean getRootAhth() {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("exit\n");
            os.flush();
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.e("*** DEBUG ***", "Unexpected error - Here is what I know: "
                    + e.getMessage());
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void openApp(Context context, String packageName) {
        int setting_other_appInstaller = Settings.Global.getInt(context.getContentResolver(), "setting_other_appInstaller", 0);
        Log.e(TAG, "openApp: " + setting_other_appInstaller);
        if (setting_other_appInstaller == 0) {
            ToastUtil.show("已禁止应用打开");
            return;
        }
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (intent != null) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }


    /**
     * 安装一个apk文件
     */
    public static void install(Context context, File uriFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context, "com.uiui.zyappstore.fileprovider", uriFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(uriFile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 卸载一个app
     */
    public static void Uninstall(Context context, String packageName) {
        //通过程序的包名创建URI
        Uri packageURI = Uri.parse("package:" + packageName);
        //创建Intent意图
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        //执行卸载程序
        context.startActivity(intent);
    }

    /**
     * 根据包名卸载应用
     *
     * @param packageName
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void uninstall(Context context, String packageName) {
        Intent broadcastIntent = new Intent(context, InstallResultReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1,
                broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        packageInstaller.uninstall(packageName, pendingIntent.getIntentSender());
    }

    /**
     * 检查手机上是否安装了指定的软件
     */
    public static boolean isAvailable(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    /**
     * 检查手机上是否安装了指定的软件
     */
    public static boolean isAvailable(Context context, File file) {
        return isAvailable(context, getPackageName(context, file.getAbsolutePath()));
    }

    /**
     * 根据文件路径获取包名
     */
    public static String getPackageName(Context context, String filePath) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            return appInfo.packageName;  //得到安装包名称
        }
        return null;
    }

    /**
     * 从apk中获取版本信息
     */
    public static String getChannelFromApk(Context context, String channelPrefix) {
        //从apk包中获取
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        //默认放在meta-inf/里， 所以需要再拼接一下
        String key = "META-INF/" + channelPrefix;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith(key)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String[] split = ret.split(channelPrefix);
        String channel = "";
        if (split.length >= 2) {
            channel = ret.substring(key.length());
        }
        return channel;
    }


//    public static void installRx(final Context context, final String packageName, final String filePath) {
//
//        Observable.create(new Observable.OnSubscribe<Integer>() {
//            @Override
//            public void call(Subscriber<? super Integer> subscriber) {
//                File file = new File(filePath);
//                if (filePath == null || filePath.length() == 0 || file == null) {
//                    Log.e("fanhuitong", "errormesg=========" + "   空啊 ");
//                    subscriber.onNext(0);
//                    return;
//                }
//                //                                String[] args = { "pm", "install", "-r", filePath };
//                String[] args = {"pm", "install", "-i", "com.colorflykids", "--user", "0", filePath};
//                //                String argss = "pm install -i " + "com.colorflykids" + " --user 0 " + filePath;
//                Log.e("fanhuitong", "argss====" + args);
//                ProcessBuilder processBuilder = new ProcessBuilder(args);
//                Process process = null;
//                BufferedReader successResult = null;
//                BufferedReader errorResult = null;
//                StringBuilder successMsg = new StringBuilder();
//                StringBuilder errorMsg = new StringBuilder();
//                try {
//                    process = processBuilder.start();
//                    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
//                    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//                    String s;
//                    while ((s = successResult.readLine()) != null) {
//                        Log.e("mjhseng", "successResult----------" + s);
//                        successMsg.append(s);
//                    }
//                    while ((s = errorResult.readLine()) != null) {
//                        Log.e("mjhseng", "errorResult----------" + s);
//                        errorMsg.append(s);
//                    }
//                } catch (IOException e1) {
//                    Log.e("fanhuitong", "IOException e1)----------" + e1.toString());
//                    e1.printStackTrace();
//                } finally {
//                    try {
//                        if (successResult != null) {
//                            successResult.close();
//                        }
//                        if (errorResult != null) {
//                            errorResult.close();
//                        }
//                    } catch (IOException e1) {
//                        Log.e("fanhuitong", "IOException e11)---------" + e1.toString());
//                        e1.printStackTrace();
//                    }
//                    if (process != null) {
//                        process.destroy();
//                    }
//                }
//                if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
//                    subscriber.onNext(2);
//                } else {
//                    Log.e("fanhuitong", "errormesg=========" + errorMsg.toString());
//                    subscriber.onNext(1);
//                }
//            }
//        }).subscribeOn(Schedulers.newThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<Integer>() {
//
//                    @Override
//                    public void onNext(Integer value) {
//                        if (value == 2) {
//                            //安装成功
//                            Utils.showToast(context, "安装成功");
//                            Log.e("fanhuitong", "-----------安装成功-----------");
//                        } else {
//                            //安装错误
//                            Log.e("fanhuitong", "------------安装错误-----------");
//                            Utils.showToast(context, "安装失败");
//                        }
//                    }
//
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        //安装错误
//                    }
//                });
//    }

    public static void installApp(Context context, String filePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            installAppatPie(context, filePath);
        } else {
            installApps(filePath);
        }
    }


    public static boolean installApps(String apkPath) {
        ToastUtil.show("正在安装应用...");
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", BuildConfig.APPLICATION_ID, "--user", "0", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            Log.e("installApps1", e.getMessage());
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                Log.e("installApps2", e.getMessage());
            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e("result", "" + errorMsg.toString());
        //如果含有“success”认为安装成功
        Log.e("installApp", successMsg.toString());
//        if (!successMsg.toString().equalsIgnoreCase("success")) {
//            ApkUtils.install(context, new File(apkPath));
//        }
        return successMsg.toString().equalsIgnoreCase("success");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void installAppatPie(Context context, String apkFilePath) {
        File file = new File(apkFilePath);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller
                .SessionParams.MODE_FULL_INSTALL);
        sessionParams.setSize(file.length());
        int sessionId = createSession(packageInstaller, sessionParams);
        if (sessionId != -1) {
            boolean copySuccess = copyApkFile(packageInstaller, sessionId, apkFilePath);
            if (copySuccess) {
                ToastUtil.show("正在安装应用");
                install(packageInstaller, sessionId, context);
            }

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static void install(PackageInstaller packageInstaller, int sessionId, Context context) {
        try {
            PackageInstaller.Session session = packageInstaller.openSession(sessionId);
            Intent intent = new Intent(context, InstallResultReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    context,
                    1, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
            session.commit(pendingIntent.getIntentSender());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @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 copyApkFile(PackageInstaller pi, int sessionId, String apkFilePath) {
        boolean success = false;
        File apkFile = new File(apkFilePath);
        PackageInstaller.Session session = null;
        try {
            session = pi.openSession(sessionId);
            OutputStream out = session.openWrite("app.apk", 0, apkFile.length());
            FileInputStream input = new FileInputStream(apkFile);
            int read = 0;
            byte[] buffer = new byte[65536];
//            while (read != -1) {
//                read = input.read(buffer);
//                out.write(buffer, 0, read);
//            }
            while (true) {
                read = input.read(buffer);
                if (read == -1) {
                    session.fsync(out);
                    success = true;
                    out.close();
                    input.close();
                    break;
                }
                out.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("fht", "copyApkFile" + e.getMessage());
        }
        return success;
    }

    //使用系统签名
//    public static void installApkInSilence(String installPath, String packageName) {
//        ToastUtil.show("正在安装应用...");
//        Class<?> pmService;
//        Class<?> activityTherad;
//        Method method;
//        try {
//            activityTherad = Class.forName("android.app.ActivityThread");
//            Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
//            method = activityTherad.getMethod("getPackageManager", paramTypes);
//            Object PackageManagerService = method.invoke(activityTherad);
//            pmService = PackageManagerService.getClass();
//            Class<?> paramTypes1[] = getParamTypes(pmService, "installPackageAsUser");
//            method = pmService.getMethod("installPackageAsUser", paramTypes1);
//            method.invoke(PackageManagerService, installPath, null, 0x00000040, packageName, getUserId(Binder.getCallingUid()));//getUserId
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//    }
    public static boolean installApkInSilence(Context context, String apkPath) {
        ToastUtil.show("正在安装应用...");
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", BuildConfig.APPLICATION_ID, "--user", "0", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e("result", "" + errorMsg.toString());
        //如果含有“success”认为安装成功
        Log.e("installApp", successMsg.toString());
//        if (!successMsg.toString().equalsIgnoreCase("success")) {
//            ApkUtils.install(context, new File(apkPath));
//        }
        return successMsg.toString().equalsIgnoreCase("success");
    }

    public static void uninstallApp(Context context, String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ApkUtils.uninstall(context, packageName);
        } else {
            ApkUtils.deleteApkInSilence(packageName);
        }
    }

    public static void deleteApkInSilence(String packageName) {
        Class<?> pmService;
        Class<?> activityTherad;
        Method method;
        try {
            activityTherad = Class.forName("android.app.ActivityThread");
            Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
            method = activityTherad.getMethod("getPackageManager", paramTypes);
            Object PackageManagerService = method.invoke(activityTherad);
            pmService = PackageManagerService.getClass();
            Class<?> paramTypes1[] = getParamTypes(pmService, "deletePackageAsUser");
            method = pmService.getMethod("deletePackageAsUser", paramTypes1);
            method.invoke(PackageManagerService, packageName, null, getUserId(Binder.getCallingUid()), 0x00000040);//getUserId
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private static Class<?>[] getParamTypes(Class<?> cls, String mName) {
        Class<?> cs[] = null;
        Method[] mtd = cls.getMethods();
        for (int i = 0; i < mtd.length; i++) {
            if (!mtd[i].getName().equals(mName)) {
                continue;
            }

            cs = mtd[i].getParameterTypes();
        }
        return cs;
    }

    public static final int PER_USER_RANGE = 100000;

    public static int getUserId(int uid) {
        return uid / PER_USER_RANGE;
    }

    public static boolean checkIsUpdate(Context context, String packageName, long versionCode) {
        PackageManager packageManager = context.getPackageManager();
        boolean update = false;
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            int code = packageInfo.versionCode;
            update = versionCode > code;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
//            LogUtils.e("NameNotFoundException", e.getMessage());
            update = false;
        }
        return update;
    }

    synchronized public static PackageInfo getPackageInfo(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            Log.e("getPackageInfo", packageName + ":" + e.getMessage());
        }
        return packageInfo;
    }

    synchronized public static String getApplicationName(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        PackageInfo packageInfo = null;
        String name = "";
        try {
            packageInfo = pm.getPackageInfo(packageName, 0);
            name = pm.getApplicationLabel(packageInfo.applicationInfo).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            Log.e("getPackageInfo", packageName + ":" + e.getMessage());
        }
        return name;
    }

    public static boolean isInstalled(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = pm.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info != null;
    }

    public static boolean isUpdate(Context context, String packageName, long versionCode) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = pm.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (info != null) {
            long appVersionCode;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = info.getLongVersionCode();
            } else {
                appVersionCode = info.versionCode;
            }
            return versionCode > appVersionCode;
        } else {
            return true;
        }
    }

    private static final HashSet<String> fuxiaoyingApp = new HashSet<String>() {{
        this.add("com.fuying.fuxiaoying");
        this.add("com.zhiduoke.fxy");
        this.add("com.fuying.english");
        this.add("com.pengren.growthspace");
        this.add("com.moshujiamm.moshujia");
        this.add("com.gankao.gkwxhd");
        this.add("com.fuying.aobama.pad");
    }};


    private static final Set<String> JXWAPP = new HashSet<String>() {{
        this.add("com.uiui.zybrowser");
        this.add("com.study.flashplayer");
        this.add("com.jxw.laboratory");
        this.add("com.safe.uiui");
        this.add("software.ecenter.study");
        this.add("com.iflytek.speechcloud");
        this.add("com.jxw.online_study");
        this.add("com.jxw.jinfangyici");
        this.add("air.com.zhihuiyoujiao.flashplayer");
        this.add("com.ll.ahschool");
        this.add("com.jxw.classtable");
        this.add("com.jxw.teacher.video");
        this.add("com.jxw.game");
        this.add("com.jxw.yyhb");
        this.add("com.jxw.zncd");
        this.add("com.jxw.dmxcy");
        this.add("com.jxw.bishunguize");
        this.add("com.jxw.characterlearning");
        this.add("com.jxw.newyouer.video");
        this.add("com.iflytek.cyber.iot.show.core");
        this.add("com.jxw.huiben");
        this.add("com.jxw.liancichengju");
        this.add("com.jxw.singsound");
        this.add("com.jxw.jxwcalculator");
        this.add("com.uiui.zyappstore");
        this.add("com.jxw.launcher");
        this.add("com.jxw.jxwbook");
        this.add("com.uiui.zysn");
        this.add("com.jxw.question");
        this.add("com.example.arithmeticformula");
        this.add("com.jxw.schultegrid");
        this.add("com.jxw.mskt.video");
        this.add("com.jxw.wuweijidanci");
        this.add("com.tech.translate");
        this.add("com.jxw.studydigital");
        this.add("com.jxw.englishsoundmark");
        this.add("com.jxw.handwrite");
        this.add("com.example.pianpangbushou");
        this.add("com.jxw.learnchinesepinyin");
        this.add("com.example.elementcycleapp");
        this.add("com.jxw.examsystem");
        this.add("com.jxw.letterstudynew");
        this.add("com.jxw.yuwenxiezuo");
        this.add("com.jxw.bihuamingcheng");
    }};

    synchronized public static List<LocalApp> getLocalApp(Context context) {
        List<LocalApp> appList = new ArrayList<>();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(intent, 0);
//        String aole_force_app = Settings.System.getString(context.getContentResolver(), "aole_force_app");
//        if (TextUtils.isEmpty(aole_force_app)) {
//            return appList;
//        }
//        Set<String> forceAppSet = new HashSet<>(Arrays.asList(aole_force_app.split(",")));
//        forceAppSet.addAll(fuxiaoyingApp);

        for (int i = 0; i < resolveInfoList.size(); i++) {
            LocalApp bean = new LocalApp();
            bean.setAppName(resolveInfoList.get(i).loadLabel(context.getPackageManager()).toString());
            String packageName = resolveInfoList.get(i).activityInfo.packageName;
            if (ApkUtils.ownApp.contains(packageName)) {
                continue;
            }
            if (ApkUtils.canremove_systemapp.contains(packageName)) {
                continue;
            }
            bean.setPackageName(packageName);
            if (JXWAPP.contains(packageName)) {
                bean.setCanUnintall(false);
            }
            Drawable icon = resolveInfoList.get(i).loadIcon(context.getPackageManager());
            bean.setIcon(icon);
//            if (forceAppSet.contains(packageName)) {
//                bean.setCanUnintall(false);
//            } else {
//                bean.setCanUnintall(true);
//            }
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
                String versionCode = context.getPackageManager()
                        .getPackageInfo(packageName, 0).versionName;
                bean.setVersion(versionCode);
                String appInstallDir = packageInfo.applicationInfo.publicSourceDir;
                int size = (int) new File(appInstallDir).length();
                bean.setSize(size);
                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                    //第三方应用
                    appList.add(bean);
                    //判断是否需要进行更新

                } else {
                    //系统应用
                }
                bean.setFirstInstallTime(packageInfo.firstInstallTime);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return appList;
    }

    synchronized public static List<LocalApp> getLocalApp2(Context context) {
        List<LocalApp> appList = new ArrayList<>();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(intent, 0);

        for (int i = 0; i < resolveInfoList.size(); i++) {
            LocalApp bean = new LocalApp();
            bean.setAppName(resolveInfoList.get(i).loadLabel(context.getPackageManager()).toString());
            String packageName = resolveInfoList.get(i).activityInfo.packageName;
            bean.setPackageName(packageName);
            Drawable icon = resolveInfoList.get(i).loadIcon(context.getPackageManager());
            bean.setIcon(icon);
            if (ApkUtils.ownApp.contains(packageName)) {
                continue;
            }
            if (ApkUtils.canremove_systemapp.contains(packageName)) {
                continue;
            }
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
                String versionCode = context.getPackageManager()
                        .getPackageInfo(packageName, 0).versionName;
                bean.setVersion(versionCode);
                bean.setVersionCode(packageInfo.versionCode);
                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                    //第三方应用
                    //判断是否需要进行更新
//                    isNeedUpdate(bean, i);
                    appList.add(bean);
                } else {
                    //系统应用
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return appList;
    }

    public static HashSet<String> canremove_systemapp = new HashSet<String>() {{
        //预置的可以卸载的系统应用，判断出来为第三方
        this.add("com.android.quicksearchbox");
        this.add("com.android.calendar");
        this.add("com.android.dreams.basic");
        this.add("com.android.musicfx");
        this.add("com.android.email");
        this.add("com.jiaoguanyi.sysc");
    }};

    public static HashSet<String> ownApp = new HashSet<String>() {{
        this.add(BuildConfig.APPLICATION_ID);
        this.add("com.android.uiuios");
        this.add("com.safe.uiui");
        this.add("com.uiuios.aios");
        this.add("com.uiuios.sn");
        this.add("com.uiuios.appstore");
        this.add("com.uiuios.browser");
        this.add("com.uiui.aios");
        this.add("com.uiui.sn");
        this.add("com.uiui.appstore");
        this.add("com.uiui.browser");
        this.add("com.aoleyun.os");
        this.add("com.aoleyun.sn");
        this.add("com.aoleyun.appstore");
        this.add("com.aoleyun.browser");
        this.add("com.aoleyun.info");
        this.add("com.aoleyunos.dop1");
        this.add("com.aoleyunos.dop2");
        this.add("com.aoleyunos.diy");
        this.add("com.teclast.zyos");
        this.add("com.teclast.zy");
        this.add("com.teclast.zyappstore");
        this.add("com.teclast.zybrowser");
        this.add("com.uiui.zyos");
        this.add("com.uiui.zy");
        this.add("com.uiui.zyappstore");
        this.add("com.uiui.zybrowser");
        this.add("com.uiui.zysn");
        this.add("com.uiui.calendar");
    }};

    public static void RemoveTask(final Context context, final String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                List<DownloadEntity> list = Aria.download(context).getTaskList();
                if (list == null || list.size() == 0) {
                    e.onComplete();
                    return;
                }
                for (DownloadEntity entity : list) {
                    long id = entity.getId();
                    String extendField = Aria.download(this).load(id).getExtendField();
                    JsonObject jsonObject = GsonUtils.getJsonObject(extendField);
                    if (jsonObject.get("app_package") == null) {
                        continue;
                    }
                    String app_package = jsonObject.get("app_package").getAsString();
                    if (packageName.equals(app_package)) {
                        Log.e("RemoveTask", "subscribe: " + "删除文件：" + entity.getFilePath());
                        File file = new File(entity.getFilePath());
                        file.delete();
                        try {
                            Aria.download(this).load(id).cancel(true);
                        } catch (Exception e1) {
                            Log.e("RemoveTask", "subscribe: " + e1.getMessage());
                        }
                    } else {
                        Log.e("RemoveTask", "subscribe: ");
                    }
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("RemoveTask", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(String s) {
                        Log.e("RemoveTask", "onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("RemoveTask", "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("RemoveTask", "onComplete: ");
                    }
                });

    }
}
