package ezviz.ezopensdkcommon.common;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import android.util.DisplayMetrics;

import java.util.ArrayList;
import java.util.List;
import ezviz.ezopensdkcommon.R;

/**
 * 动态权限申请工具类（静态方式）
 * <p>
 * 封装 Android 6.0+ 动态权限申请流程，提供静态方法供任何 Activity 调用。
 * Activity 端只需在 onRequestPermissionsResult 中一行转发即可。
 * </p>
 *
 * 使用方法：
 * <pre>
 * 1. 发起权限请求：
 *    EZPermissionUtil.requestPermissions(activity, permissions, requestCode, callback);
 *
 * 2. 在 Activity 的 onRequestPermissionsResult 中转发：
 *    EZPermissionUtil.handleResult(requestCode, permissions, grantResults);
 *
 * 3. 在 Activity 的 onResume 中调用（处理从设置页返回）：
 *    EZPermissionUtil.onResume(activity);
 * </pre>
 */
public class EZPermissionUtil {

    /**
     * 权限申请结果回调接口
     */
    public interface PermissionCallback {
        /**
         * 所有权限已授予
         */
        void onPermissionsGranted();

        /**
         * 权限被拒绝（可选实现，默认会弹出引导对话框）
         */
        default void onPermissionsDenied() {
        }
    }

    // 以 requestCode 为 key，存储待处理的权限请求
    private static final SparseArray<PermissionRequest> sPendingRequests = new SparseArray<>();
    // 记录是否从设置页返回
    private static boolean sIsFromPermissionSetting = false;
    // 记录最近一次的 requestCode（用于从设置页返回时重新检查）
    private static int sLastRequestCode = -1;

    /**
     * 权限请求封装
     */
    private static class PermissionRequest {
        final Activity activity;
        final String[] permissions;
        final int requestCode;
        final PermissionCallback callback;

        PermissionRequest(Activity activity, String[] permissions, int requestCode, PermissionCallback callback) {
            this.activity = activity;
            this.permissions = permissions;
            this.requestCode = requestCode;
            this.callback = callback;
        }
    }

    /**
     * 发起权限请求
     * <p>
     * Android 6.0 以下直接回调成功，6.0+ 检查并申请缺少的权限
     * </p>
     *
     * @param activity    宿主 Activity
     * @param permissions 需要申请的权限数组
     * @param requestCode 权限请求码（不同功能使用不同请求码以区分）
     * @param callback    权限回调
     */
    public static void requestPermissions(Activity activity, String[] permissions, int requestCode, PermissionCallback callback) {
        PermissionRequest request = new PermissionRequest(activity, permissions, requestCode, callback);
        sPendingRequests.put(requestCode, request);
        sLastRequestCode = requestCode;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkAndRequestPermission(request);
        } else {
            sPendingRequests.remove(requestCode);
            callback.onPermissionsGranted();
        }
    }

    /**
     * 处理权限请求结果
     * <p>
     * 在 Activity 的 onRequestPermissionsResult 中调用此方法
     * </p>
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 授权结果
     */
    public static void handleResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionRequest request = sPendingRequests.get(requestCode);
        if (request == null) {
            return;
        }
        if (hasAllPermissionsGranted(grantResults)) {
            sPendingRequests.remove(requestCode);
            request.callback.onPermissionsGranted();
        } else {
            request.callback.onPermissionsDenied();
            try {
                showPermissionDialog(request.activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 在 Activity 的 onResume 中调用
     * <p>
     * 用于处理从系统设置页返回后重新检查权限的逻辑
     * </p>
     *
     * @param activity 宿主 Activity
     */
    public static void onResume(Activity activity) {
        if (sIsFromPermissionSetting && sLastRequestCode >= 0) {
            sIsFromPermissionSetting = false;
            PermissionRequest request = sPendingRequests.get(sLastRequestCode);
            if (request != null) {
                // 重新发起权限检查
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkAndRequestPermission(request);
                }
            }
        }
    }

    /**
     * 检查并请求缺少的权限（Android 6.0+）
     */
    @TargetApi(Build.VERSION_CODES.M)
    private static void checkAndRequestPermission(PermissionRequest request) {
        List<String> lackedPermissions = new ArrayList<>();
        for (String permission : request.permissions) {
            if (request.activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                lackedPermissions.add(permission);
            }
        }
        // 权限都已经有了
        if (lackedPermissions.isEmpty()) {
            sPendingRequests.remove(request.requestCode);
            request.callback.onPermissionsGranted();
        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限
            String[] requestPermissions = new String[lackedPermissions.size()];
            lackedPermissions.toArray(requestPermissions);
            request.activity.requestPermissions(requestPermissions, request.requestCode);
        }
    }

    /**
     * 显示权限引导对话框，引导用户前往应用设置页手动授权
     */
    private static void showPermissionDialog(Activity activity) {
        AlertDialog dialog = new AlertDialog.Builder(activity)
                .setMessage(activity.getString(R.string.permission_dialog_message))
                .setPositiveButton(activity.getString(R.string.permission_dialog_go_settings), (dialog1, which) -> {
                    sIsFromPermissionSetting = true;
                    dialog1.dismiss();
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + activity.getPackageName()));
                    activity.startActivity(intent);
                })
                .setNegativeButton(activity.getString(R.string.permission_dialog_cancel), (dialog12, which) -> {
                    dialog12.dismiss();
                }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(activity, R.color.black));
        // 设置居中，解决Android9.0 AlertDialog不居中问题
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow != null) {
            DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
            WindowManager.LayoutParams p = dialogWindow.getAttributes();
            p.width = (int) (metrics.widthPixels * 0.9);
            p.gravity = Gravity.CENTER;
            dialogWindow.setAttributes(p);
        }
    }

    /**
     * 判断是否所有权限都已授予
     *
     * @param grantResults 授权结果数组
     * @return true 表示全部授权
     */
    private static boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }
}
