package com.mytatvarnsdk.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import cgmblelib.utils.ConstantsLibrary;
import cgmblelib.utils.MyLog;
import cgmblelib.utils.PermissionCheckTool;
import com.mytatvarnsdk.R;
import com.mytatvarnsdk.myView.popupwindow.BPopupWindow;
import com.mytatvarnsdk.myView.popupwindow.PopupType;
import com.mytatvarnsdk.myView.popupwindow.PopupWindowManagement;

import java.util.Arrays;

/**
 * 权限基础
 *
 * @author minyuchun
 */
public abstract class BasePermissionActivity extends AppCompatActivity {
    /**
     * 权限申请Code
     */
    protected static final int PERMISSION_REQUEST_CODE = 0x114;
    /**
     * 权限申请Code 进入设置界面
     */
    protected static final int PERMISSION_SETTING_REQUEST_CODE = 0x124;
    /**
     * 权限检测器
     */
    protected PermissionCheckTool mPermissionsChecker;
    /**
     * 记录申请的权限
     */
    protected String[] permissions = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPermissionsChecker = new PermissionCheckTool(this);
    }

    /**
     * 获取需要申请的权限集合
     *
     * @return 返回权限集合
     */
    public abstract String[][] getPermission();

    /***
     * 申请权限成功
     */
    public abstract void onPermissionRequestSuccess();

    /**
     * 申请权限失败-单次拒绝
     */
    public abstract void onPermissionRequestFail(String... permission);

    /**
     * 申请权限永远失败，勾选了不再提醒
     */
    public abstract void onPermissionRequestFailForever(String... permission);

    /**
     * 得到未授权的权限
     *
     * @return 返回未授权的权限
     */
    public String[] getDeniedPermissions() {
        MyLog.i("getDeniedPermissions ");
        String[][] permissions = getPermission();
        if (permissions != null && permissions.length > 0) {
            for (String[] per : permissions) {
                if (per != null && per.length > 0) {
                    if (mPermissionsChecker != null && mPermissionsChecker.lacksPermissions(per)) {
                        return per;
                    }
                }
            }
        }
        return null;
    }

    /***
     * 权限申请
     */
    protected void requestPermission() {
        // 第一步，获取未被允许的权限(被拒绝或者未申请)
        MyLog.i("requestPermission ");
        String[] permissions = getDeniedPermissions();
        if (permissions != null) {
            // 需要确定这几个权限是否需要给予申请前的说明
            if (isShouldShowRequestPermissionRationaleForFirst(permissions)) {
                // 显示权限申请前需要进行提示
                showPermissionRequestRationale(false, permissions);
            } else {
                requestPermissions(permissions); //直接申请权限
            }
        } else {
            //没有未申请的权限，授权成功
            onPermissionRequestSuccess();
        }
    }

    /***
     * 请求权限的申请，兼容低版本
     * @param permissions 所有权限
     */
    public void requestPermissions(String... permissions) {
        if (permissions != null) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * @param permission 权限
     * @return 是否会显示权限申请弹框
     */
    public boolean shouldShowRequestPermission(String permission) {
        if (permission != null) {
            return ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        }
        return false;
    }

    /**
     * @param permissions 权限集合
     * @return 是否会显示权限申请弹框
     */
    public boolean shouldShowRequestPermission(String[] permissions) {
        if (permissions != null && permissions.length > 0) {
            for (String permission : permissions) {
                if (shouldShowRequestPermission(permission)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (hasAllPermissionsGranted(grantResults)) { //申请权限返回的Code，查看是否所有权限已经被申请
                requestPermission(); //继续申请下一组权限
            } else {
                if (shouldShowRequestPermission(permissions)) {
                    // 申请了用户拒绝了，那你就要提示用户了，所以返回true
//                    MyLog.d("被拒绝后需要显示 理由");
                    onPermissionRequestFail(permissions);
                } else {
                    // 没有申请过权限，申请就是了，所以返回false；
                    // 已经允许了，不需要申请也不需要提示，所以返回false；
                    // 用户选择了拒绝并且不再提示，那你也不要申请了，也不要提示用户了，所以返回false；这里执行的是3
//                    MyLog.d("被拒绝后也不需要显示 理由");
                    onPermissionRequestFailForever(permissions);
                }
            }
        }
    }


    /**
     * 是否所有权限已经被申请
     *
     * @param grantResults 所有权限
     * @return 是否被申请成功
     */
    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 定位权限失败的处理,继续申请权限
     */
    protected void showLocalPermissionFail() {
        PopupWindowManagement.getInstance()
                .setOnConfirmListener(view -> {
                    PopupWindowManagement.getInstance().dismiss();
                    requestPermission();
                })
                .setMessages(this.getResources().getString(R.string.fail_permission))
                .show(this, PopupType.POPUP_PERMISSION_FAIL);
    }

    /**
     * 定位权限永远失败的处理
     */
    protected void showLocalPermissionFailForever() {
        PopupWindowManagement.getInstance()
                .setOnSelectListener(new BPopupWindow.OnSelectListener() {
                    @Override
                    public void confirm(View view) {
                        PopupWindowManagement.getInstance().dismiss();
                        startAppSettings();
                    }

                    @Override
                    public void cancel(View view) {
                        PopupWindowManagement.getInstance().dismiss();
                    }
                })
                .setMessages(this.getResources().getString(R.string.fail_permission))
                .show(this, PopupType.POPUP_PERMISSION_FAIL_FOREVER);
    }

    /**
     * 这些第一次申请的时候是否需要显示提示信息
     *
     * @param permissions 权限
     * @return 是否需要显示
     */
    private boolean isShouldShowRequestPermissionRationaleForFirst(String[] permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
                Arrays.equals(permissions, ConstantsLibrary.BLUETOOTH_S)) {
            return true;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                Arrays.equals(permissions, ConstantsLibrary.BACKGROUND_LOCATION_Q)) {
            return true;
        } else if (Arrays.equals(permissions, ConstantsLibrary.LOCAL_PERMISSION)) {
            return true;
        } else if (Arrays.equals(permissions, ConstantsLibrary.CAMERA_PERMISSION)) {
            return true;
        }
        return false;
    }

    /**
     * 显示权限请求的基本理由
     *
     * @param isFailForever 是否是因为永久取消了权限申请还是第一次判断的原因，如果是 true 表示由于用户永久取消了权限申请
     * @param permission    权限的显示问题
     */
    public void showPermissionRequestRationale(boolean isFailForever, String... permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
                && Arrays.equals(permission, ConstantsLibrary.BLUETOOTH_S)) { //展示需要蓝牙权限
            showNearbyRequestRationale(isFailForever, permission);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                Arrays.equals(permission, ConstantsLibrary.BACKGROUND_LOCATION_Q)) { // 展示需要All the time 的权限
            showLocalBackgroundPermissionRequestRationale(isFailForever, permission);
        } else if (Arrays.equals(permission, ConstantsLibrary.LOCAL_PERMISSION)) { // 展示需要精确定位权限
            showLocationPermission(isFailForever, permission);
        } else if (Arrays.equals(permission, ConstantsLibrary.CAMERA_PERMISSION)) { // 展示需要相机的权限
            showCameraPermission(isFailForever, permission);
        } else {
            requestPermissions(permission);
        }
        permissions = permission;
    }

    /**
     * 定位权限获取的理由
     *
     * @param isFailForever 是否永久取消了权限 true：永久取消
     * @param permissions   权限列表
     */
    protected void showCameraPermission(boolean isFailForever, String... permissions) {
        PopupWindowManagement.getInstance()
                .setOnConfirmListener(view -> {
                    PopupWindowManagement.getInstance().dismiss();
                    if (isFailForever) {
                        startAppSettings();
                        finish();
                    } else {
                        requestPermissions(permissions);
                    }
                })
                .setMessages(this.getResources().getString(R.string.fail_camara_permission))
                .show(this, PopupType.POPUP_PERMISSION_RATIONALE_CAMERA);
    }

    /**
     * 定位权限获取的理由
     *
     * @param isFailForever 是否永久取消了权限 true：永久取消
     * @param permissions   权限列表
     */
    protected void showLocationPermission(boolean isFailForever, String... permissions) {
        PopupWindowManagement.getInstance()
                .setOnConfirmListener(view -> {
                    PopupWindowManagement.getInstance().dismiss();
                    if (isFailForever) {
                        startAppSettings();
                        finish();
                    } else {
                        requestPermissions(permissions);
                    }
                })
                .setMessages(this.getResources().getString(R.string.permission_rationale_location))
                .show(this, PopupType.POPUP_PERMISSION_RATIONALE_LOCATION);
    }

    /**
     * 显示后台定位权限申请的理由
     *
     * @param isFailForever 是否永久取消了权限 true：永久取消
     * @param permissions   权限列表
     */
    protected void showLocalBackgroundPermissionRequestRationale(boolean isFailForever, String... permissions) {
        try {
            CharSequence label = getResources().getString(R.string.allow_all_the_time);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                PackageManager manager = getPackageManager();
                if (manager != null) {
                    label = manager.getBackgroundPermissionOptionLabel();
                }
            }
            PopupWindowManagement.getInstance()
                    .setOnConfirmListener(view -> {
                        PopupWindowManagement.getInstance().dismiss();
                        if (isFailForever) {
                            startAppSettings();
                            finish();
                        } else {
                            requestPermissions(permissions);
                        }
                    })
                    .setMessages(this.getResources().getString(R.string.permission_rationale_location_background, label))
                    .show(this, PopupType.POPUP_PERMISSION_RATIONALE_LOCATION_BACKGROUND);
        } catch (Exception e) {
            e.printStackTrace();
            startAppSettings();
        }
    }

    /**
     * 打开附近设备
     *
     * @param isFailForever 是否永久取消了权限 true：永久取消
     * @param permissions   权限列表
     */
    protected void showNearbyRequestRationale(boolean isFailForever, String... permissions) {
        PopupWindowManagement.getInstance()
                .setOnConfirmListener(view -> {
                    PopupWindowManagement.getInstance().dismiss();
                    if (isFailForever) {
                        startAppSettings();
                        finish();
                    } else {
                        requestPermissions(permissions);
                    }
                })
                .setMessages(getResources().getString(R.string.permission_rationale_nearby))
                .show(this, PopupType.POPUP_PERMISSION_RATIONALE_BLUETOOTH_S);
    }

    /**
     * 进入系统权限设置界面
     */
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, PERMISSION_SETTING_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果进入到了设置界面并且成功返回后
        if (requestCode == PERMISSION_SETTING_REQUEST_CODE) {
            requestPermission();
        }
    }
}
