package com.rv.component.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;

import com.example.component_utils.BuildConfig;

import java.lang.reflect.Method;

public class MachineAuthorityHelper {


    @SuppressLint("NewApi")
    public static void checkMachineAuthority(Activity activity) {
        String machine = getMachine();
        if (TextUtils.isEmpty(machine)) return;
        boolean b = AppCookie.getBooleanValue("machine_authority", false);

        if ("xiaomi".equalsIgnoreCase(machine) && hasOneWeek()) {
            String finalMachine = machine;
            if (!isAllowed(activity)) {
                new AlertDialog.Builder(activity).setTitle("提示")
                        .setMessage("为了实时掌握房车出行优惠资讯，建议去开启“后台弹出界面”的权限")
                        .setNegativeButton("下次再说", (dialogInterface, i) -> {
                            dialogInterface.dismiss();
                        })
                        .setPositiveButton("好的", (dialogInterface, i) -> {
                            AppCookie.save("machine_authority", true);
                            gotoSetting(activity, finalMachine);
                        }).setCancelable(false).show();
            }
        } else if ( !b  && ("vivo".equalsIgnoreCase(machine) || "oppo".equalsIgnoreCase(machine))) {
            String finalMachine = machine;
            new AlertDialog.Builder(activity).setTitle("提示")
                    .setMessage("为了实时掌握房车出行优惠资讯，建议去开启“后台弹出界面”的权限")
                    .setNegativeButton("下次再说", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    })
                    .setPositiveButton("好的", (dialogInterface, i) -> {
                        AppCookie.save("machine_authority", true);
                        gotoSetting(activity, finalMachine);
                    }).setCancelable(false).show();
        }
    }

    /***
     * 判断上一次显示距现在是否有七天了
     * @return
     */
    public static boolean hasOneWeek() {
        long lastShowTime = AppCookie.getLongValue("last_show_time");
        long distance = System.currentTimeMillis() - lastShowTime;
        if (distance > 1000 * 60 * 60 * 24 * 7) {
            AppCookie.save("last_show_time", System.currentTimeMillis());
            return true;
        }
        return false;
    }

    public static String getMachine() {
        String machine = null;
        if (Build.MANUFACTURER != null && Build.MANUFACTURER.length() > 0) {
            machine = Build.MANUFACTURER.toLowerCase();
        }
        return machine;
    }

    private static void gotoSetting(Activity activity, String machine) {
        switch (machine) {
            case "vivo":
                goVivoManager(activity);
                break;

            case "xiaomi":
                goXiaoMiManager(activity);
                break;

            case "oppo":
                goOppoManager(activity);
                break;


        }
    }


    private static void goVivoManager(Activity activity) {

        Intent intent = new Intent();
        intent.putExtra("packagename", activity.getPackageName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"));
        } else {
            intent.setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.safeguard.SoftPermissionDetailActivity"));
        }
        start(activity, intent);
    }

    private static void goXiaoMiManager(Activity activity) {
        Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
        localIntent.putExtra("extra_pkgname", activity.getPackageName());
        start(activity, localIntent);
    }

    private static void goOppoManager(Activity activity) {
        Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.coloros.securitypermission", "com.coloros.securitypermission.permission.PermissionAppAllPermissionActivity");//R11t 7.1.1 os-v3.2
        intent.setComponent(comp);
        start(activity, intent);
    }

    private static void start(Activity activity, Intent intent) {
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            goAppDetailSetting(activity);
        }
    }


    private static boolean isAllowed(Activity activity) {
        @SuppressLint({"NewApi", "LocalSuppress"}) AppOpsManager ops = (AppOpsManager) activity.getSystemService(Context.APP_OPS_SERVICE);
        try {
            int op = 10021;
            Method method = ops.getClass().getMethod("checkOpNoThrow", new Class[]{int.class, int.class, String.class});
            Integer result = (Integer) method.invoke(ops, op, Process.myUid(), activity.getPackageName());
            return result == AppOpsManager.MODE_ALLOWED;

        } catch (Exception e) {

        }
        return false;
    }


    private static void goAppDetailSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", BuildConfig.APPLICATION_ID);
        }

        try {
            context.startActivity(localIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
