package com.mq.mylibrary.base;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.mq.mylibrary.R;
import com.mq.mylibrary.tool.LogTool;
import com.mq.mylibrary.tool.PermissionTool;

import java.util.Arrays;


/**
 * 创建人 mQ
 * 创建时间 2019/8/16 0016 17:03
 * 文件名称 BaseOpenActivity
 * 说明:
 **/
public abstract class BaseOpenActivity extends AppCompatActivity {

    private PermissionTool mPermissionTool;

    public abstract Class<?> startLogin();

    private int flg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open);
        PackageManager pm = getPackageManager();
        boolean b = pm.hasSystemFeature(PackageManager.FEATURE_NFC);
        LogTool.d("是否有NFC: " + b);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (flg == 1) {
//            Intent intent = new Intent(this, BaseOpenActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
            Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //判断读写权限
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            showSettingDialog();
        } else {
            checkPermission();
        }
    }

    private void checkPermission() {
        mPermissionTool = PermissionTool.get().init(
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_PHONE_STATE
//                        Manifest.permission.ACCESS_COARSE_LOCATION,
//                        Manifest.permission.CAMERA
                });

        //系统权限是否同意
        if (!mPermissionTool.checkPermissionAll(this)) {
            mPermissionTool.requestPermission(this);
        } else {
            startActivity(new Intent(BaseOpenActivity.this, startLogin()));
            finish();
        }
    }

    /**
     * 权限申请结果回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionTool.onRequestPermissionsResult(requestCode, permissions, grantResults, new PermissionTool.PermissionCallBack() {
            @Override
            public void onGrantedPermissionAll() {
                //权限全部通过
                startActivity(new Intent(BaseOpenActivity.this, startLogin()));
                finish();
            }

            @Override
            public void onDeniedPermission(String[] deniedPermissions) {
                LogTool.i("onDeniedPermission: 权限拒绝 " + Arrays.toString(deniedPermissions));
                //权限拒绝 重新申请
                if (mPermissionTool.getIsRequestUI(BaseOpenActivity.this, deniedPermissions)) {
                    mPermissionTool.requestPermission(BaseOpenActivity.this);
                } else {
                    mPermissionTool.showSettingDialog(BaseOpenActivity.this, true);
                }

            }
        });
    }


    /**
     * 弹出对话框提示去设置权限通过
     * 是否强制
     */
    public void showSettingDialog() {
        flg = 1;
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("权限申请")
                .setMessage("请您前往设置，\n【读写手机存储】权限设为允许！\n否则程序无法正常运行。")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(getAppDetailSettingIntent());
                    }
                });

        builder.setNegativeButton("退出程序", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.create().show();
    }

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