package com.mq.mylibrary.tool;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

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

/**
 * 创建人 mQ
 * 创建时间 2019/1/12 0012 16:09
 * 文件名称 PermissionTool
 * 说明:
 **/
public class PermissionTool {

    private String[] mPermissions;

    private static final int mRequestPermissionCode = 1001;

//    private Activity mActivity;

    private PermissionTool() {
    }

    private static class SingleHelper {
        private static final PermissionTool INSTANCE = new PermissionTool();
    }

    public static PermissionTool get() {
        return SingleHelper.INSTANCE;
    }

    public PermissionTool init(String[] permissions) {
        mPermissions = permissions;
        return this;
    }

    /**
     * 权限是否全部授权
     */
    public boolean checkPermissionAll(Activity mActivity) {
        for (String p : mPermissions) {
            if (!(ContextCompat.checkSelfPermission(mActivity, p) == PackageManager.PERMISSION_GRANTED)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 申请权限
     */
    public PermissionTool requestPermission(Activity mActivity) {
        //申请权限
        ActivityCompat.requestPermissions(mActivity, mPermissions, mRequestPermissionCode);
        return this;
    }

    /**
     * 是否可以显示申请UI
     */
    public boolean getIsRequestUI(Activity mActivity, String[] permissions) {
        //是否可以显示UI
        boolean isRequestUI = false;
        for (String permission : permissions) {
            LogTool.i("requestPermission: " + ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permission));
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permission)) {
                isRequestUI = true;
            }
        }
        return isRequestUI;
    }

    /**
     * 处理权限申请结果
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults, PermissionCallBack callBack) {
        if (requestCode == mRequestPermissionCode) {
            if (grantResults.length > 0) {
                List<String> mDeniedPermissions = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        mDeniedPermissions.add(permissions[i]);
                        LogTool.i("权限被拒绝: " + permissions[i]);
                    }
                }
                if (mDeniedPermissions.size() == 0) {
                    LogTool.i("权限全部通过");
                    if (callBack != null)
                        callBack.onGrantedPermissionAll();
                } else {
                    //权限申请被拒绝
                    if (callBack != null)
                        callBack.onDeniedPermission(mDeniedPermissions.toArray(new String[mDeniedPermissions.size()]));
                }
            }
        }
    }

    public interface PermissionCallBack {
        void onGrantedPermissionAll();

        void onDeniedPermission(String[] deniedPermissions);

    }


    /**
     * 弹出对话框提示去设置权限通过
     * 是否强制
     */
    public void showSettingDialog(final Activity mActivity, boolean force) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                .setCancelable(false)
                .setTitle("权限申请")
                .setMessage("权限被拒绝, 请您前往设置,将必要权限设为同意! 否则程序无法正常运行.")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mActivity.startActivity(getAppDetailSettingIntent(mActivity));
                    }
                });
        //强制
        if (force) {
            builder.setNegativeButton("退出程序", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mActivity.finish();
                }
            });
        } else {
            //非强制
            builder.setNegativeButton("取消", null);
        }
        builder.create().show();
    }

    /**
     * 获取应用详情页面intent（把用户引导到系统设置页面）
     */
    private Intent getAppDetailSettingIntent(Activity mActivity) {
        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", mActivity.getPackageName(), 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", mActivity.getPackageName());
        }
        return localIntent;
    }


}
