package com.android.launcher3.manager;


import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Printer;

import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherProviderChangeListener;
import com.android.launcher3.LockScreenActivity;
import com.android.launcher3.LockScreenInterface;
import com.android.launcher3.accessibility.FloatWindowService;
import com.android.launcher3.accessibility.ListenerAppService;
import com.android.launcher3.debug.CustomDialog;
import com.android.launcher3.debug.DebugInfoActivity;
import com.android.launcher3.debug.SearchAppCanUseActivity;
import com.android.launcher3.model.ConfigManager;
import com.android.launcher3.model.TimeConfig;
import com.android.launcher3.provider.DBManager;
import com.android.launcher3.provider.ManagerAppProvider;
import com.android.launcher3.util.ActivityUtil;
import com.android.launcher3.util.KToast;
import com.android.launcher3.util.Logger;
import com.android.launcher3.util.PermissionUtil;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.SystemUtils;
import com.android.launcher3.util.ThreadpoolManager;
import com.android.launcher3.util.UIExecutor;
import com.android.launcher3.util.UiThreadHelper;
import com.android.launcher3.util.WeakHandler;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.android.launcher3.manager.Constants.DIALOG_KEY_VALUE;

/**
 * 桌面图标状态的管理工具
 */
public class LauncherManager {


    public static final int LOCK_SCREEN_TIME_UP = 0x1;

    public static final String TAG = "LauncherManager";
    private ArrayMap<String, ManagementInfo> appInfo;

    private static volatile LauncherManager mInstance;

    private TimeModeManager timeModeManager;

    private static Context mContext;

    public static CustomDialog mCustomDialog;
    public static int mStartSendCount = 0;

    public static KToast mKToast;

    private final LauncherProvider.ChangeListenerWrapper mListenerWrapper = new LauncherProvider.ChangeListenerWrapper();

    private Handler mListenerHandler;
//    private WeakHandler<Context> weakHandler;

    private static Class mSettingActivity;

    private int lockScreenMode = ColumnDef.LockScreen.MODE_UNLOCK;

    //   金币数量 1金币=1分钟的游戏使用时长
    private int mCoinNum;

    private boolean interceptSystemSetting = true;

    private LockScreenInterface floatWindowHandle;

    private boolean mIsInterceptAppointPage = false;


    private static boolean DEBUG_MODEL = false;


    /**
     * 初始化方法 （必须!）
     *
     * @param application
     */
    public static void init(Application application) {
        init(application, Launcher.class);
    }

    /**
     * 设置Debug模式 正式版需关闭
     *
     * @param debugModel
     */
    public static void setDebugModel(boolean debugModel) {
        DEBUG_MODEL = debugModel;
    }

    /**
     * @param application
     * @param settingActivity 拦截系统设置后跳转到页面
     */
    public static void init(Application application, Class settingActivity) {
        mContext = application;
        ActivityUtil.getInstance().init(application);
        Logger.init(application);
        Intent intent = new Intent(mContext, ListenerAppService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mContext.startForegroundService(intent);
        } else {
            mContext.startService(intent);
        }

        mSettingActivity = settingActivity;

        LauncherManager.getInstance();

    }


    public static LauncherManager getInstance() {
        if (mInstance == null) {
            synchronized (LauncherManager.class) {
                if (mInstance == null) {
                    mInstance = new LauncherManager();
                }
            }
        }
        return mInstance;
    }

    private LauncherManager() {
        appInfo = new ArrayMap<>();

       /* ManagementInfo managementInfo = new ManagementInfo();
        managementInfo.setUseEndTimeStamp(43320);

        managementInfo.setPackageName("com.tencent.mobileqq");
        managementInfo.setLock(ColumnDef.LockApp.LOCKED);
        managementInfo.setUseType(ColumnDef.AppUseType.GAME_LOCK_TYPE);

        LauncherManager.getInstance().addPackageInfo(managementInfo);
*/
        timeModeManager = TimeModeManager.getInstance(getContext());
        mListenerHandler = new Handler(mListenerWrapper);

//        weakHandler = new WeakHandler<Context>(getContext()) {
//            @Override
//            public void handleMessage(Message msg) {
//                switch (msg.what) {
//                    case LOCK_SCREEN_TIME_UP:
//                        updateLockScreenDelay();
//                        break;
//                }
//            }
//        };
        loadManagementAppInfoFromDB();
//
//
//        Intent floatWindowService = new Intent(mContext, FloatWindowService.class);
//
//        mContext.bindService(floatWindowService, new ServiceConnection() {
//            @Override
//            public void onServiceConnected(ComponentName name, IBinder service) {
//                floatWindowHandle = LockScreenInterface.Stub.asInterface(service);
//                Logger.e(TAG, "onServiceConnected");
//            }
//
//            @Override
//            public void onServiceDisconnected(ComponentName name) {
//                floatWindowHandle = null;
//                mContext.bindService(floatWindowService, this, Context.BIND_AUTO_CREATE);
//
//                Logger.e(TAG, "onServiceDisconnected");
//            }
//        }, Context.BIND_AUTO_CREATE);


    }


    public String getSettingActivityName() {
        if (mSettingActivity != null) {
            return mSettingActivity.getName();
        }
        return null;
    }

    public boolean isInterceptSystemSetting() {
        return interceptSystemSetting;
    }

    /**
     * 是否需要拦截系统设置
     *
     * @param interceptSystemSetting
     */
    public void setInterceptSystemSetting(boolean interceptSystemSetting) {
        this.interceptSystemSetting = interceptSystemSetting;
    }

    public boolean isIsInterceptAppointPage() {
        return mIsInterceptAppointPage;
    }

    public void setIsIsInterceptAppointPage(boolean isInterceptAppointPage) {
        this.mIsInterceptAppointPage = isInterceptAppointPage;
    }


    /**
     * 获取受管理app的信息
     *
     * @param packageName 应用包名
     * @return
     */
    public ManagementInfo getManageAppInfo(String packageName) {
        if (TextUtils.isEmpty(packageName))
            return null;
        if (appInfo.containsKey(packageName)) {
            return appInfo.get(packageName);
        }
        return null;
    }


    /**
     * Sets a provider listener.
     */
    public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
        Preconditions.assertUIThread();
        mListenerWrapper.mListener = listener;
    }

    /**
     * Overridden in tests
     */
    protected void notifyListeners() {
        mListenerHandler.sendEmptyMessage(LauncherProvider.ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
    }

    /**
     * 增加某个app的信息
     */
    public void addPackageInfo(ManagementInfo managementInfo) {
        if (managementInfo == null)
            return;
        if (TextUtils.isEmpty(managementInfo.getPackageName())) {
            throw new NullPointerException("app packagename must not null");
        }
        if (TextUtils.isEmpty(managementInfo.getPackageName()))
            return;
        if (!appInfo.containsKey(managementInfo.getPackageName())) {


            appInfo.put(managementInfo.getPackageName(), managementInfo);


            ContentValues contentValues = new ContentValues();

            long id = mContext.getContentResolver().call(ManagerAppProvider.DatabaseHelper.CONTENT_URI, ManagerAppProvider.METHOD_GENERATENEWITEMID, null, null).getLong(ManagerAppProvider.EXTRA_VALUE);
            contentValues.put(ManagerAppProvider.ManagementColumns._ID, id);
            contentValues.put(ManagerAppProvider.ManagementColumns.PACKAGENAME, managementInfo.getPackageName());
            contentValues.put(ManagerAppProvider.ManagementColumns.USE_TYPE, managementInfo.getUseType());
            contentValues.put(ManagerAppProvider.ManagementColumns.LOCK, managementInfo.getLock());
            contentValues.put(ManagerAppProvider.ManagementColumns.ENDTIMESTAMP, managementInfo.getUseEndTimeStamp());

            ThreadpoolManager.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    mContext.getContentResolver().insert(ManagerAppProvider.DatabaseHelper.CONTENT_URI, contentValues);
                }
            });

            refreshLauncherIconWidget(managementInfo.getPackageName());
            notifyListeners();
            Logger.e(TAG, "addPackageInfo");
        } else {
            updatePackageInfo(managementInfo);
        }


    }


    /**
     * 状态更新发广播给桌面(Launcher)处理
     *
     * @param packageName
     */
    public void refreshLauncherIconWidget(String packageName) {

        Intent intent = new Intent(Constants.ACTION_UPDATE_ICON);
        intent.putExtra(Constants.EXTRA_PACKAGE, packageName);
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }

//    /**
//     * 将应用整理
//     * @param appInfo
//     */
//    private void classifyAppInfo(ManagementInfo appInfo) {
//
//        String packageName=appInfo.getPackageName();
//        if (appInfo.getUseType() == ColumnDef.AppUseType.SAFE_TYPE) {
//            safePackageList.add(packageName);
//        }else if (appInfo.getUseType()==ColumnDef.AppUseType.LEARN_TYPE){
//            learnPackageList.add(packageName);
//        }else if (appInfo.getUseType()==ColumnDef.AppUseType.GAME_LOCK_TYPE){
//            gamePackageList.add(packageName);
//        }else {
//            unClassPackageList.add(packageName);
//        }
//    }

    /**
     * 更新某个app的管理信息
     *
     * @param managementInfo
     */
    public void updatePackageInfo(ManagementInfo managementInfo) {
        if (managementInfo == null)
            return;
        if (TextUtils.isEmpty(managementInfo.getPackageName())) {
            throw new NullPointerException("app packagename must not null");
        }
        appInfo.put(managementInfo.getPackageName(), managementInfo);
        ContentValues contentValues = new ContentValues();

        contentValues.put(ManagerAppProvider.ManagementColumns.PACKAGENAME, managementInfo.getPackageName());
        contentValues.put(ManagerAppProvider.ManagementColumns.USE_TYPE, managementInfo.getUseType());
        contentValues.put(ManagerAppProvider.ManagementColumns.LOCK, managementInfo.getLock());
        contentValues.put(ManagerAppProvider.ManagementColumns.ENDTIMESTAMP, managementInfo.getUseEndTimeStamp());
        ThreadpoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                mContext.getContentResolver().update(ManagerAppProvider.DatabaseHelper.CONTENT_URI, contentValues, ManagerAppProvider.ManagementColumns.PACKAGENAME + "='" + managementInfo.getPackageName() + "'", null);
            }
        });
        refreshLauncherIconWidget(managementInfo.getPackageName());
        notifyListeners();
        Logger.e(TAG, "updatePackageInfo");
    }

    /**
     * 移除某个app的信息
     *
     * @param packageName
     */
    public void removePackageInfo(String packageName) {

        if (appInfo.containsKey(packageName)) {
            appInfo.remove(packageName);
            ThreadpoolManager.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    mContext.getContentResolver().delete(ManagerAppProvider.DatabaseHelper.CONTENT_URI, ManagerAppProvider.ManagementColumns.PACKAGENAME + "='" + packageName + "'", null);
                }
            });

            refreshLauncherIconWidget(packageName);
            notifyListeners();
            Logger.e(TAG, "removePackageInfo");
        }
    }

    /**
     * 列表式添加
     *
     * @param appInfoList
     */
    public void addPackageInfoList(List<ManagementInfo> appInfoList) {
        if (appInfoList == null)
            return;

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        for (ManagementInfo managementInfo : appInfoList) {
            if (appInfo.containsKey(managementInfo.getPackageName())) {


                ContentValues contentValues = new ContentValues();

                contentValues.put(ManagerAppProvider.ManagementColumns.PACKAGENAME, managementInfo.getPackageName());
                contentValues.put(ManagerAppProvider.ManagementColumns.USE_TYPE, managementInfo.getUseType());
                contentValues.put(ManagerAppProvider.ManagementColumns.LOCK, managementInfo.getLock());
                contentValues.put(ManagerAppProvider.ManagementColumns.ENDTIMESTAMP, managementInfo.getUseEndTimeStamp());

                ops.add(ContentProviderOperation.newUpdate(ManagerAppProvider.DatabaseHelper.CONTENT_URI).withValues(contentValues).withSelection(ManagerAppProvider.ManagementColumns.PACKAGENAME + "=?", new String[]{managementInfo.getPackageName()}).build());

            } else {

                ContentValues contentValues = new ContentValues();

                long id = mContext.getContentResolver().call(ManagerAppProvider.DatabaseHelper.CONTENT_URI, ManagerAppProvider.METHOD_GENERATENEWITEMID, null, null).getLong(ManagerAppProvider.EXTRA_VALUE);
                contentValues.put(ManagerAppProvider.ManagementColumns._ID, id);
                contentValues.put(ManagerAppProvider.ManagementColumns.PACKAGENAME, managementInfo.getPackageName());
                contentValues.put(ManagerAppProvider.ManagementColumns.USE_TYPE, managementInfo.getUseType());
                contentValues.put(ManagerAppProvider.ManagementColumns.LOCK, managementInfo.getLock());
                contentValues.put(ManagerAppProvider.ManagementColumns.ENDTIMESTAMP, managementInfo.getUseEndTimeStamp());
                ops.add(ContentProviderOperation.newInsert(ManagerAppProvider.DatabaseHelper.CONTENT_URI).withValues(contentValues).build());
            }

            appInfo.put(managementInfo.getPackageName(), managementInfo);

            refreshLauncherIconWidget(managementInfo.getPackageName());
        }

        if (ops.size() > 0) {
            notifyListeners();

            DBManager.doSql(mContext, ops);
        }


    }


    /**
     * 批量删除
     *
     * @param packageNameList
     */
    public void removePackageInfoList(List<String> packageNameList) {
        if (packageNameList == null)
            return;

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        for (String packageName : packageNameList) {
            if (appInfo.containsKey(packageName)) {
                appInfo.remove(packageName);
                refreshLauncherIconWidget(packageName);
                ops.add(ContentProviderOperation.newUpdate(ManagerAppProvider.DatabaseHelper.CONTENT_URI).withSelection(ManagerAppProvider.ManagementColumns.PACKAGENAME + "=?", new String[]{packageName}).build());
            }
        }

        if (ops.size() > 0) {
            notifyListeners();
            DBManager.doSql(mContext, ops);
        }
    }


    private void loadManagementAppInfoFromDB() {
        Observable.just("").map(new Function<String, ArrayMap>() {
            @Override
            public ArrayMap apply(String s) throws Exception {


                ArrayMap<String, ManagementInfo> arrayMap = new ArrayMap<>();
                final ContentResolver contentResolver = mContext.getContentResolver();
                final Cursor c = contentResolver.query(
                        ManagerAppProvider.DatabaseHelper.CONTENT_URI, null, null, null, null);

                final int packageNameIndex = c.getColumnIndexOrThrow(
                        ManagerAppProvider.ManagementColumns.PACKAGENAME);
                final int useTypeIndex = c.getColumnIndexOrThrow(
                        ManagerAppProvider.ManagementColumns.USE_TYPE);
                final int lockIndex = c.getColumnIndexOrThrow
                        (ManagerAppProvider.ManagementColumns.LOCK);

                final int timeStampIndex = c.getColumnIndexOrThrow
                        (ManagerAppProvider.ManagementColumns.ENDTIMESTAMP);

                while (c.moveToNext()) {

                    String packageName = c.getString(packageNameIndex);
                    int useType = c.getInt(useTypeIndex);
                    int lock = c.getInt(lockIndex);
                    long timeStamp = c.getLong(timeStampIndex);

                    ManagementInfo managementInfo = new ManagementInfo();
                    managementInfo.setPackageName(packageName);
                    managementInfo.setUseType(useType);
                    managementInfo.setLock(lock);

                    managementInfo.setUseEndTimeStamp(timeStamp);

                    arrayMap.put(packageName, managementInfo);

                }
                c.close();
                return arrayMap;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Observer<ArrayMap>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayMap arrayMap) {
                appInfo.putAll(arrayMap);
                Logger.e(TAG, "onNext");
            }

            @Override
            public void onError(Throwable e) {

                Logger.e(TAG, e.getLocalizedMessage());

            }

            @Override
            public void onComplete() {

            }
        });

    }

    /**
     * 获取受管理的app信息
     *
     * @return
     */
    public ArrayMap<String, ManagementInfo> getAppInfo() {
        return appInfo;
    }


    public void backLauncherHome(Context context) {
        UIExecutor.postRunable(new Runnable() {
            @Override
            public void run() {
                Intent home = new Intent(context, Launcher.class);
                home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(home);
            }
        });
    }


    public void backLauncherHome(Context context, String dialogTipString) {
        UIExecutor.postRunable(new Runnable() {
            @Override
            public void run() {
                Intent home = new Intent(context, Launcher.class);
                home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                home.putExtra(DIALOG_KEY_VALUE, dialogTipString);
                context.startActivity(home);
            }
        });

    }

    public void backLauncherHome(Context context, int dialogType) {
        UIExecutor.postRunable(new Runnable() {
            @Override
            public void run() {
                Intent home = new Intent(context, Launcher.class);
                home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                home.putExtra(DIALOG_KEY_VALUE, dialogType);
                context.startActivity(home);
            }
        });
    }

    public void jumpSetting(Context context) {
        UIExecutor.postRunable(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, mSettingActivity);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });

    }


    public int getLockScreenMode() {
        return lockScreenMode;
    }

    /**
     * 无限期强制锁屏
     *
     * @param context
     */
    public void forceLockScreenForever(Context context) {
        forceLockScreen(context, 0);
    }


    /**
     * @param context
     * @param timeStamp 此次锁屏的时长 单位：秒 如锁屏一小时 即传3600秒 timeStamp<=0表示无限期已此模式锁屏
     */
    public void forceLockScreen(Context context, long timeStamp) {
        lockScreen(context, ColumnDef.LockScreen.MODE_FORCE_LOCK);

        if (timeStamp > 0) {
            timeModeManager.updateLockScreenEndTime(timeStamp * 1000 + System.currentTimeMillis());
//            weakHandler.sendEmptyMessageDelayed(LOCK_SCREEN_TIME_UP, timeStamp * 1000);
        } else {
            timeModeManager.updateLockScreenEndTime(0);
        }
    }

    public void lockScreenNormal(Context context) {
        lockScreen(context, ColumnDef.LockScreen.MODE_NORMAL);
    }

    private void lockScreen(Context context, @ColumnDef.LockScreen.LockScreenMode int mode) {
        UIExecutor.postRunableDelay(new Runnable() {
            @Override
            public void run() {
                lockScreenMode = mode;
                if (PermissionUtil.hasPermission(getContext()) && floatWindowHandle != null && !(SystemUtils.isHW() || SystemUtils.isHONOR())) {
                    try {
                        Logger.e(TAG, "floatWindowHandle lockScreen");
                        floatWindowHandle.lockScreen();
                    } catch (RemoteException e) {
//                        e.printStackTrace();
                        Logger.e(TAG, "lockScreen float window RemoteException" + e.getMessage());
                        Intent intent = new Intent(context, LockScreenActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }

                } else {
                    Logger.e(TAG, "lockScreen activity");
                    if (!ConfigManager.getInstance().isLockScreen()) {
                        Intent intent = new Intent(context, LockScreenActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }

                }

            }
        }, 200);
    }

    public void unlockScreen() {
        Logger.e(TAG, "unlockScreen");
        timeModeManager.updateLockScreenEndTime(-1);
        UIExecutor.postRunable(new Runnable() {
            @Override
            public void run() {

                if (ActivityUtil.getInstance().getTopActivity() != null && ActivityUtil.getInstance().getTopActivity() instanceof LockScreenActivity) {
                    ActivityUtil.getInstance().getTopActivity().finish();
                }

                if (floatWindowHandle != null) {
                    try {
                        floatWindowHandle.unlockScreen();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

                ConfigManager.getInstance().setLockScreen(false);
                lockScreenMode = ColumnDef.LockScreen.MODE_UNLOCK;
            }
        });

    }

    /**
     * 是否强制锁屏
     *
     * @return
     */
    public boolean isForceLock() {
        return lockScreenMode == ColumnDef.LockScreen.MODE_FORCE_LOCK || lockScreenMode == ColumnDef.LockScreen.MODE_REST;
    }


    /**
     * 设置当前工作模式
     *
     * @param workMode
     */
    public void setCurrentWorkMode(@ColumnDef.TimeManager.TimeMode int workMode) {
        timeModeManager.setCurrentWorkModel(workMode);
    }


    /**
     * 添加对应的工作模式及模式下的管理信息
     *
     * @param config 秒级时间戳
     */
    public void addWorkMode(TimeConfig config) {
        timeModeManager.addWorkModeConfig(config);
//        updateLockScreenDelay();
    }


    public int canUse(String packageName) {
        return timeModeManager.canUse(packageName);
    }


    /**
     * 判断当前应用是否是忽略规则启动的应用 如电话短信等
     *
     * @param packageName
     * @return
     */
    public boolean isSafePackageName(String packageName) {
        for (int i = 0; i < Constants.SAFE_APP.length; i++) {
            if (Pattern.matches(Constants.SAFE_APP[i], packageName)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断当前这个设置页面是否需要拦截
     */
    public boolean isInterceptPackage(String packageName) {
        for (int i = 0; i < Constants.INTERCEPT_SETTING.length; i++) {
            if (Constants.INTERCEPT_SETTING[i].equals(packageName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断当前应用是否是系统应用
     *
     * @param packageName
     * @return
     */
    public boolean isSystemPackageName(String packageName) {
        for (int i = 0; i < Constants.SYSTEM_APP.length; i++) {
            if (Pattern.matches(Constants.SYSTEM_APP[i], packageName)) {
                return true;
            }
        }

        return false;
    }


    public static Context getContext() {
        return mContext;
    }


    /**
     * 判断以前设置的强制锁屏是否过期
     */
    public synchronized boolean updateLockScreenDelay() {
        Log.i("lock_zzzzzzzz", "1");
//        退出管制
        if (getExitState()) {
            unlockScreen();
            return false;
        }
        if (ConfigManager.getInstance().isLockScreen() && lockScreenMode == ColumnDef.LockScreen.MODE_NORMAL) {
            return true;
        }
        if (timeModeManager.getLockScreenType() == ColumnDef.LockScreen.MODE_FORCE_LOCK || timeModeManager.getLockScreenType() == ColumnDef.LockScreen.MODE_REST) {
            Log.i("lock_zzzzzzzz", "2");
            //判断之前是否有忽略工作模式去锁屏
            long endTime = timeModeManager.getLockScreenEndTime();
            Logger.e(TAG, "updateLockScreen\t" + endTime + "\t" + System.currentTimeMillis());
            if (endTime == 0 || endTime > System.currentTimeMillis()) {
//            无限期已家长端临时设定的模式执行锁屏
                Log.i("lock_zzzzzzzz", "3");
//            if (lockScreenMode != timeModeManager.getLockScreenType()) {
                lockScreen(getContext(), ColumnDef.LockScreen.MODE_FORCE_LOCK);
                return true;
//            }

            } else if (endTime < System.currentTimeMillis()) {
                Log.i("lock_zzzzzzzz", "4");

//            非家长端强制锁定状态或者锁定时间到期 恢复当前工作模式下的锁屏方式
                Logger.e(TAG, lockScreenMode + "\t" + timeModeManager.getCurrentScreenModel());

                if (timeModeManager.getCurrentScreenModel() != ColumnDef.LockScreen.MODE_NORMAL && timeModeManager.getCurrentScreenModel() != ColumnDef.LockScreen.MODE_UNLOCK) {
                    Logger.e(TAG, "lockScreen");
                    lockScreen(getContext(), timeModeManager.getCurrentScreenModel());
                    Log.i("lock_zzzzzzzz", "5");

                    return true;
                } else {
                    unlockScreen();
                    return false;
                }

            }
        } else {
            Log.i("lock_zzzzzzzz", "6");

//            //判断工作模式去锁屏
            Logger.e(TAG, "inTimeRegionTolockScreen");
            if (!timeModeManager.inTimeRegionTolockScreen()) {
                lockScreen(getContext(), timeModeManager.getCurrentScreenModel());
            } else {
                unlockScreen();
                return false;
            }
        }
        return false;

    }


    public void relockScreen() {
        Logger.e(TAG, "relockScreen");
        UIExecutor.postRunableDelay(new Runnable() {
            @Override
            public void run() {
                if (PermissionUtil.hasPermission(getContext()) && floatWindowHandle != null) {
                    try {
                        floatWindowHandle.lockScreen();
                    } catch (RemoteException e) {
//                        e.printStackTrace();
                        Intent intent = new Intent(getContext(), LockScreenActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getContext().startActivity(intent);
                    }

                } else {
                    Intent intent = new Intent(getContext(), LockScreenActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                }

            }
        }, 0);
    }


    /**
     * true 可卸载 默认false
     *
     * @param enabele
     */
    public void changeUninstallEnable(boolean enabele) {
        timeModeManager.updateUninstallEnabled(enabele);
    }


    /**
     * 获取当前是否可卸载
     *
     * @return
     */
    public boolean getUninstallEnable() {
        return timeModeManager.getUninstallEnable();
    }


    /**
     * 获取当前是否开启了管制
     *
     * @return
     */
    public boolean getExitState() {
        return timeModeManager.isExitProtect();
    }


    /**
     * 改变管制的状态
     *
     * @param exit true 解除管制
     */
    public void changeExitState(boolean exit) {
        timeModeManager.setExitProtect(exit);
    }

    public int getCoinNum() {
        return mCoinNum;
    }

    /**
     * 设置金币数量
     *
     * @param mCoinNum
     */
    public void setCoinNum(int mCoinNum) {
        this.mCoinNum = mCoinNum;
    }


    /**
     * 跳转debug信息页面
     *
     * @param context
     */
    public void jumpDebugInfo(Context context) {
        Intent intent = new Intent(context, DebugInfoActivity.class);
        context.startActivity(intent);
    }


    /**
     * 跳转查询app是否可用页面
     *
     * @param context
     */
    public void jumpSearchAppCanUse(Context context) {
        Intent intent = new Intent(context, SearchAppCanUseActivity.class);
        context.startActivity(intent);
    }

    /**
     * 打开倍知守护app
     */
    public void openApplication(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        /*ComponentName cn = new ComponentName("cn.dankal.bzshchild", "cn.dankal.bzshchild.ui.SplashActivity");
        intent.setComponent(cn);
        Uri uri = Uri.parse("cn.dankal.bzshchild.ui.SplashActivity");*/

        ComponentName cn = new ComponentName("com.dankal.dankal_launcher", "com.dankal.dankal_launcher.PackageManageActivity");
        intent.setComponent(cn);
        Uri uri = Uri.parse("com.dankal.dankal_launcher.PackageManageActivity");

        intent.setData(uri);
        context.startActivity(intent);
    }
}
