package com.dankal.dankal_launcher;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.android.launcher3.accessibility.ListenerAppService;
import com.android.launcher3.manager.LauncherManager;
import com.android.launcher3.util.PermissionUtil;
import com.android.launcher3.util.SystemUtils;
import com.android.launcher3.floatingwindow.FloatPermissionDetectView;

public class PermissionSettingActivity extends AppCompatActivity {

    private AlertDialog.Builder mBuilder;
    private int mResultPermissionType = 0;//返回权限类型

    private String mTitle = "";
    private String mContent = "";
    private TestReceive innerReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_setting);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        check();
        showTip();
    }

    /**
     * 返回回来的时候显示提示
     */
    private void showTip() {
        //关闭悬浮窗
        if (mFloatPermissionDetectView != null) {
            mFloatPermissionDetectView.remove();
            mFloatPermissionDetectView = null;
        }
        if (SystemUtils.isVIVO()) {
            switch (mResultPermissionType) {
                case 1://自启动
                    if (!PermissionUtil.isAutoStartUp) {
                        mTitle = "自启动权限";
                        mContent = "是否已成功设置自启动权限？";
                        showSureDialog();
                    }
                    break;
                case 2://电池高耗电优化
                    if (!PermissionUtil.mIsPowerOptimization) {
                        mTitle = "高耗电优化";
                        mContent = "是否已开启高耗电优化？";
                        showSureDialog();
                    }
                    break;
                case 3://应用速冻
                    if (!PermissionUtil.mIsQuickFreeze) {
                        mTitle = "应用速冻";
                        mContent = "是否已开启应用速冻？";
                        showSureDialog();
                    }
                    break;
            }
        }
    }

    /**
     * 权限确认对话框
     */
    private void showSureDialog() {
        mBuilder = new AlertDialog.Builder(this).setTitle(mTitle).setMessage(mContent)
                .setPositiveButton("设置成功", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (mResultPermissionType) {
                            case 1:
                                PermissionUtil.putAutoStartUp(PermissionSettingActivity.this);
                                break;
                            case 2:
                                PermissionUtil.putHeightPowerConsumption(PermissionSettingActivity.this);
                                break;
                            case 3:
                                PermissionUtil.putQuickFreeze(PermissionSettingActivity.this);
                                break;
                        }
                        check();
                    }
                }).setNegativeButton("还没有", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        mBuilder.create().show();
    }

    //激活设备管理
    private ConstraintLayout clActivateDeviceManager;
    private ImageView ivActivateDeviceManager;

    //关闭耗电保护
    private ConstraintLayout clClosePower;
    private ImageView ivClosePower;

    //开启查看应用使用权限
    private ConstraintLayout clOpenApplicationPermission;
    private ImageView ivOpenApplicationPermission;

    //关闭USB测试
    private ConstraintLayout clCloseUsbTest;
    private ImageView ivCloseUsbTest;

    //自启动权限
    private ConstraintLayout clSelfStartingPermissions;
    private ImageView ivSelfStartingPermissions;

    //开启通知栏监听
    private ConstraintLayout clOpenNotificationListener;
    private ImageView ivOpenNotificationListener;

    //设置默认桌面
    private ConstraintLayout clSettingDefaultLauncher;
    private ImageView ivSettingDefaultLauncher;

    //关闭应用速冻（oppo）
    private ConstraintLayout clCloseQuickFreeze;
    private ImageView ivSettingQuickFreeze;

    //耗电保护中允许后台运行
    private ConstraintLayout clPowerConsumptionProtection;
    private ImageView ivPowerConsumptionProtection;

    //锁定多任务
    private ConstraintLayout clMultitasking;
    private ImageView ivMultitasking;

    //电池高耗电优化
    private ConstraintLayout clHeightPowerConsumption;
    private ImageView ivHeightPowerConsumption;


    private Button buttonConfirm;

    /**
     * 悬浮窗提示
     */
    private FloatPermissionDetectView mFloatPermissionDetectView;


    private void initData() {
        LauncherManager.getInstance().setInterceptSystemSetting(false);
        LauncherManager.getInstance().changeExitState(true);
        ClickAction clickAction = new ClickAction();
        clActivateDeviceManager = findViewById(R.id.cl_activate_device_manager);
        ivActivateDeviceManager = findViewById(R.id.iv_activate_device_manager);

        clClosePower = findViewById(R.id.cl_close_power);
        ivClosePower = findViewById(R.id.iv_close_power);

        clOpenApplicationPermission = findViewById(R.id.cl_open_application_permission);
        ivOpenApplicationPermission = findViewById(R.id.iv_open_application_permission);

        clCloseUsbTest = findViewById(R.id.cl_close_usb_test);
        ivCloseUsbTest = findViewById(R.id.iv_close_usb_test);

        clSelfStartingPermissions = findViewById(R.id.cl_self_starting_permissions);
        ivSelfStartingPermissions = findViewById(R.id.iv_self_starting_permissions);

        clOpenNotificationListener = findViewById(R.id.cl_open_notification_listener);
        ivOpenNotificationListener = findViewById(R.id.iv_open_notification_listener);

        clSettingDefaultLauncher = findViewById(R.id.cl_setting_launcher);
        ivSettingDefaultLauncher = findViewById(R.id.iv_setting_launcher);

        //耗电保护中允许后台运行
        clPowerConsumptionProtection = findViewById(R.id.cl_power_consumption_protection);
        ivPowerConsumptionProtection = findViewById(R.id.iv_power_consumption_protection);

        //应用速冻
        clCloseQuickFreeze = findViewById(R.id.cl_apply_quick_freeze);
        ivSettingQuickFreeze = findViewById(R.id.iv_apply_quick_freeze);

        //锁定多任务
        clMultitasking = findViewById(R.id.cl_multitasking);
        ivMultitasking = findViewById(R.id.iv_multitasking);

        //电池高耗电优化
        clHeightPowerConsumption = findViewById(R.id.cl_height_power_consumption);
        ivHeightPowerConsumption = findViewById(R.id.iv_height_power_consumption);

        buttonConfirm = findViewById(R.id.button_confirm);
        buttonConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //mPresenter.addTimeSwitch();
                LauncherManager.getInstance().setInterceptSystemSetting(true);
                LauncherManager.getInstance().changeExitState(false);
                LauncherManager.getInstance().backLauncherHome(getApplicationContext());
            }
        });

        clActivateDeviceManager.setOnClickListener(clickAction);
        clClosePower.setOnClickListener(clickAction);
        clOpenApplicationPermission.setOnClickListener(clickAction);
        clCloseUsbTest.setOnClickListener(clickAction);
        clOpenNotificationListener.setOnClickListener(clickAction);
        clSettingDefaultLauncher.setOnClickListener(clickAction);
        clSelfStartingPermissions.setOnClickListener(clickAction);
        ivPowerConsumptionProtection.setOnClickListener(clickAction);
        clCloseQuickFreeze.setOnClickListener(clickAction);
        clPowerConsumptionProtection.setOnClickListener(clickAction);
        clHeightPowerConsumption.setOnClickListener(clickAction);


        brandAdapter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (innerReceiver != null) {
            unregisterReceiver(innerReceiver);
        }
    }

    /**
     * 根据手机品牌判断显示相应权限
     */
    private void brandAdapter() {
        if (SystemUtils.isOPPO()) {
            clCloseQuickFreeze.setVisibility(View.VISIBLE);
            clSettingDefaultLauncher.setVisibility(View.GONE);
        }

        if (SystemUtils.isVIVO()) {
            clSettingDefaultLauncher.setVisibility(View.GONE);
            clHeightPowerConsumption.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 检查所有权限
     */
    private void check() {
        //判断是否有设备管理权限
        boolean activateDeviceManager;
        if (PermissionUtil.checkDeviceAdminPermission(this)) {
            openFailTick(ivActivateDeviceManager);
            activateDeviceManager = true;
        } else {
            openFailure(ivActivateDeviceManager);
            activateDeviceManager = false;
        }

        //判断是否电池优化
        boolean closePower;
        if (PermissionUtil.checkBatteryOptimize(this)) {
            openFailTick(ivClosePower);
            closePower = true;
        } else {
            openFailure(ivClosePower);
            closePower = false;
        }

        //高耗电优化
        boolean heightPowerConsumption;
        if (PermissionUtil.checkHeightPowerConsumption(this)) {
            openFailTick(ivHeightPowerConsumption);
            heightPowerConsumption = true;
        } else {
            openFailure(ivHeightPowerConsumption);
            heightPowerConsumption = false;
        }


        //自启动
        boolean selfStarting;
        if (PermissionUtil.checkAutoStartUp(this)) {
            openFailTick(ivSelfStartingPermissions);
            selfStarting = true;
        } else {
            openFailure(ivSelfStartingPermissions);
            selfStarting = false;
        }

        //判断是否开启查看应用使用权限
        boolean openApplicationPermission;
        if (PermissionUtil.checkAppUsagePermission(this)) {
            openFailTick(ivOpenApplicationPermission);
            openApplicationPermission = true;
        } else {
            openFailure(ivOpenApplicationPermission);
            openApplicationPermission = false;
        }

        //判断是否开启usb权限
        boolean closeUsbTest;
        if (!PermissionUtil.enAbleADB(this)) {
            openFailTick(ivCloseUsbTest);
            closeUsbTest = true;
        } else {
            openFailure(ivCloseUsbTest);
            closeUsbTest = false;
        }

        //判断是否开启通知栏
        boolean openNotificationListener;
        if (PermissionUtil.isNotificationListenersEnabled(this)) {
            openFailTick(ivOpenNotificationListener);
            openNotificationListener = true;
        } else {
            openFailure(ivOpenNotificationListener);
            openNotificationListener = false;
        }

        //判断是否设置为默认桌面
        boolean settingDefaultLauncher;
        if (PermissionUtil.isDefaultHome(this)) {
            openFailTick(ivSettingDefaultLauncher);
            settingDefaultLauncher = true;
        } else {
            openFailure(ivSettingDefaultLauncher);
            settingDefaultLauncher = false;
        }

        //判断应用速冻(oppo)
        boolean isQuickFreeze;
        if (PermissionUtil.checkQuickFreeze(this)) {
            openFailTick(ivSettingQuickFreeze);
            isQuickFreeze = true;
        } else {
            openFailure(ivSettingQuickFreeze);
            isQuickFreeze = false;
        }


        if (SystemUtils.isVIVO()) {
            buttonConfirm.setEnabled(activateDeviceManager && closePower && openApplicationPermission &&
                    closeUsbTest && openNotificationListener && heightPowerConsumption && selfStarting);
            return;
        }

        buttonConfirm.setEnabled(activateDeviceManager && closePower && openApplicationPermission &&
                closeUsbTest && openNotificationListener && settingDefaultLauncher);
    }


    private void openFailure(ImageView imageView) {
        imageView.setImageResource(R.mipmap.ic_failure);
    }

    private void openFailTick(ImageView imageView) {
        imageView.setImageResource(R.mipmap.ic_tick);
    }


    class ClickAction implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            mResultPermissionType = 0;
            String tipText = "";//需要提示的文本
            switch (v.getId()) {
                case R.id.cl_self_starting_permissions://自启动权限
                    mResultPermissionType = 1;
                    PermissionUtil.jumpStartInterface(PermissionSettingActivity.this);
                   /* if (Build.DISPLAY.equals("PAFM00_11_F.12")) {//搜索自启动权限
                        String tipText = "1、直接搜索自启动，并打开“倍知守-孩子端”开关\n2、找到“应用管理”+“自启动管理”并打开“倍知守-孩子端”开关";
                        showFloatPermissionWindow(tipText);
                    }*/
                    if (SystemUtils.isVIVO()) {
                        tipText = "1、点击<big><font color='#FFC537'>权限</font></big><br/>" +
                                "2、点击<big><font color='#FFC537' >单项权限设置</font></big><br/>" +
                                "3、开启<big><font color='#FFC537'>自启动</font></big>";
                        showFloatPermissionWindow(tipText);
                    }
                    break;
                case R.id.cl_activate_device_manager://设备管理
                    PermissionUtil.gotoDeviceAdminPermissionSetting(PermissionSettingActivity.this);
                    break;
                case R.id.cl_close_power:  //关闭耗电保护
                    PermissionUtil.gotoBatteryOptimize(PermissionSettingActivity.this);
                    break;
                case R.id.cl_open_application_permission:  //开启使用权限
                    PermissionUtil.gotoAppUsagePermission(PermissionSettingActivity.this);
                    break;
                case R.id.cl_close_usb_test://关闭usb
                    PermissionUtil.gotoDeveloperChoice(PermissionSettingActivity.this);
                    break;
                case R.id.cl_open_notification_listener:////通知
                    PermissionUtil.goToNotificationAccessSetting(PermissionSettingActivity.this);
                    break;
                case R.id.cl_setting_launcher://设置默认桌面
                    PermissionUtil.setDefaultL(PermissionSettingActivity.this);
                    //Utils.openResolverLauncher(PermissionSettingActivity.this);
                    //设置默认桌面
                    break;
                case R.id.cl_power_consumption_protection://耗电保护中允许后台运行
                    tipText = "在“耗电保护中”找到“倍知守护孩子端”选择允许后台运行";
                    showFloatPermissionWindow(tipText);
                    PermissionUtil.jumpStartInterface(PermissionSettingActivity.this);
                    break;
                case R.id.cl_apply_quick_freeze://应用速冻
                    mResultPermissionType = 3;
                    tipText = "1、滑动页面找到<big><font color='#FFC537'>电池</font></big><br/>" +
                            "2、点击<big><font color='#FFC537' >应用速冻</font></big>并找到<big><font color='#FFC537' >倍知守护孩子端</font></big><br/>" +
                            "3、关闭<big><font color='#FFC537'>自动速冻开关</font></big>";
                    showFloatPermissionWindow(tipText);
                    PermissionUtil.jumpSystemSettings(PermissionSettingActivity.this);
                    break;
                case R.id.cl_multitasking://锁定多任务

                    break;
                case R.id.cl_height_power_consumption://电池高耗电（vivo）
                    mResultPermissionType = 2;
                    tipText = "1、滑动页面找到<big><font color='#FFC537'>电池</font></big><br/>" +
                            "2、点击<big><font color='#FFC537' >后台高耗电</font></big>并找到<big><font color='#FFC537' >倍知守护孩子端</font></big><br/>" +
                            "3、开启<big><font color='#FFC537'>倍知守护孩子端</font></big>";
                    showFloatPermissionWindow(tipText);
                    PermissionUtil.jumpHeightPowerConsumption(PermissionSettingActivity.this);
                    break;
            }
        }
    }

    private synchronized void showFloatPermissionWindow(String tipText) {
        if (mFloatPermissionDetectView != null) {
            mFloatPermissionDetectView.remove();
            mFloatPermissionDetectView = null;
        }
        mFloatPermissionDetectView = new FloatPermissionDetectView(getApplicationContext(), tipText);
        mFloatPermissionDetectView.show();
    }
}
