package com.zxhl.main.page.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.badoo.mobile.util.WeakHandler;
import com.umeng.analytics.MobclickAgent;
import com.zxhl.cms.common.Constant;
import com.zxhl.cms.common.base.BaseActivity;
import com.zxhl.cms.utils.Utils;
import com.zxhl.main.R;

import java.util.List;


/**
 * Created by gaoleichao on 2018/5/10.
 */

public class PermissionsActivity extends BaseActivity {

    public static final int PERMISSIONS_GRANTED = 0; // 权限授权
    public static final int PERMISSIONS_DENIED = 1; // 权限拒绝

    private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数

    public static final String EXTRA_PERMISSIONS = "permission.extra_permission"; // 权限参数
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案

    private boolean isRequireCheck; // 是否需要系统权限检测
    private AlertDialog.Builder alertBuilder;
    private boolean isAlertDialogShow;

    private WeakHandler mWeakHandler;
    private int mOnbackClickNum = 0;

    @Override
    public void before() {
        super.before();
        if (getIntent() == null || !getIntent().hasExtra(EXTRA_PERMISSIONS)) {
        }
        setNeedGoneNavigationBar(true);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }


    @Override
    public int layoutID() {
        return R.layout.activity_splash;
    }

    @Override
    public void init() {
        mWeakHandler = new WeakHandler();
        isRequireCheck = true;
    }


    private void createDialog() {
        alertBuilder = new AlertDialog.Builder(this)
                .setTitle(R.string.permission_help)
                .setNegativeButton(R.string.permission_quit, (dialog, which) -> {
                    setResult(PERMISSIONS_DENIED);
                    isAlertDialogShow = false;
                    finish();
                })
                .setPositiveButton(R.string.permission_setting, (dialog, which) -> {
                    isAlertDialogShow = false;
                    dialog.dismiss();
                    startAppSettings();
                })
                .setOnKeyListener((dialog, keyCode, event) -> {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        return true;
                    }
                    return false;
                })
                .setCancelable(false);
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }

    private Runnable mResetRunnable;

    @Override
    public void onBackPressed() {
        mOnbackClickNum++;
        if (mOnbackClickNum >= 2) {
            setResult(PERMISSIONS_DENIED);
            isAlertDialogShow = false;
            if (mResetRunnable != null) {
                mWeakHandler.removeCallbacks(mResetRunnable);
            }
            finish();
        } else {
            if (mResetRunnable == null) {
                mResetRunnable = new Runnable() {
                    @Override
                    public void run() {
                        mOnbackClickNum = 0;
                    }
                };
            }
            mWeakHandler.postDelayed(mResetRunnable, 1000);
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        String insertStr = "";
        List<String> list = Utils.noPermissions(getPermissions());
        for (String str : list) {
            if (TextUtils.equals(str, Constant.Permission.PERMISSION_STORAGE)) {
                insertStr += getString(R.string.permission_sdcard_str);
            } else if (TextUtils.equals(str, Constant.Permission.PERMISSION_PHONE)) {
                insertStr += getString(R.string.permission_phone_str);
            } else if (TextUtils.equals(str, Constant.Permission.PERMISSION_COARSE_LOCATION)) {
                insertStr += getString(R.string.permission_soarse_location_str);
            } else if (TextUtils.equals(str, Constant.Permission.PERMISSION_FINE_LOCATION)) {
                insertStr += getString(R.string.permission_fine_location_str);
            } else if (TextUtils.equals(str, Constant.Permission.PERMISSION_CAMERA)) {
                insertStr += getString(R.string.permission_camera_str);
            }
        }
        if (alertBuilder == null) {
            createDialog();
        }
        alertBuilder.setMessage(getString(R.string.permission_help_text, insertStr));
        alertBuilder.show();
        isAlertDialogShow = true;
    }

    // 返回传递的权限参数
    private String[] getPermissions() {
        return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
    }

    // 请求权限兼容低版本
    private void requestPermissions(String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    // 全部权限均已获取
    private void allPermissionsGranted() {
        setResult(PERMISSIONS_GRANTED);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRequireCheck && !isAlertDialogShow) {
            String[] permissions = getPermissions();
            if (Utils.needPermissions(permissions)) {
                requestPermissions(permissions); // 请求权限
            } else {
                allPermissionsGranted(); // 全部权限都已获取
            }
        } else {
            isRequireCheck = true;
        }
//        MobclickAgent.onResume(this);
    }

    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true;
            allPermissionsGranted();
        } else {
//            isRequireCheck = false;
//            showMissingPermissionDialog();
            isRequireCheck = true;
            allPermissionsGranted();
        }
    }


    // 含有全部的权限
    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }


    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }


    @Override
    public void onClick(View view) {

    }
}
