package com.common.commonlib.view.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

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

import com.common.commonlib.R;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限申请Activity
 * 继承与此Activity，调用requestPermission（）方法，即可快速实现权限动态申请功能
 * 默认基于系统的的弹窗样式申请权限
 *
 * @author miracle
 * @since 2021/8/2
 */
public class PermissionCompatActivity extends AppCompatActivity {
    private static final String TAG = "PermissionCompatActivity";
    protected String[] permissionArray;
    private List<String> unAuthorizedPermissionList;
    private static final int REQUEST_PERMISSIONS_CODE = 1608;
    private Dialog mPermissionDialog;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        checkAndRequestPermission();
    }

    protected void requestPermission(String[] args) {
        permissionArray = args;
        checkAndRequestPermission();
    }

    @SuppressLint("LongLogTag")
    private void checkAndRequestPermission() {
        if (permissionArray != null && permissionArray.length > 0) {
            unAuthorizedPermissionList = new ArrayList<>();
            for (int i = 0; i < permissionArray.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissionArray[i]) != PackageManager.PERMISSION_GRANTED) {
                    //添加还未授予的权限
                    unAuthorizedPermissionList.add(permissionArray[i]);
                }
            }
            //申请权限
            if (unAuthorizedPermissionList.size() > 0) {//有权限没有通过，需要申请
                ActivityCompat.requestPermissions(this, permissionArray, REQUEST_PERMISSIONS_CODE);
            } else {
                //说明权限都已经通过，可以做你想做的事情去
                Log.i(TAG, "所有权限都申请到了");
            }
        }
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS_CODE) {
            //有权限没有通过
            boolean hasPermissionDismiss = false;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            //如果有权限没有被允许
            if (hasPermissionDismiss) {
                //跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
                showPermissionDialog();
            } else {
                //全部权限通过
                Log.i(TAG, "所有权限申请完成!");
            }
        }
    }

    private void showPermissionDialog() {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(this)
                    .setMessage(getResources().getString(R.string.default_un_authorized_prompt))
                    .setPositiveButton(getResources().getString(R.string.default_dialog_setting), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cancelPermissionDialog();
                            String packageName = getApplication().getPackageName();
                            Uri packageURI = Uri.parse("package:" + packageName);
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    }).setNegativeButton(getResources().getString(R.string.default_dialog_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //关闭页面或者做其他操作
                            cancelPermissionDialog();
                            finish();
                        }
                    }).create();
        }
        mPermissionDialog.show();
    }

    //关闭对话框
    private void cancelPermissionDialog() {
        if (mPermissionDialog != null && mPermissionDialog.isShowing()) {
            mPermissionDialog.cancel();
        }
    }

}
