package com.duben.microtribe.ui.activitys.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.core.content.ContextCompat;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.gyf.barlibrary.ImmersionBar;
import com.duben.microtribe.MintsApplication;
import com.duben.microtribe.R;
import com.duben.microtribe.common.Constant;
import com.duben.microtribe.mvp.views.BaseView;
import com.duben.microtribe.ui.widgets.LoadingDialog;
import com.duben.microtribe.utils.StatusBarUtil;
import com.duben.microtribe.utils.ToastUtil;
import com.duben.library.base.BaseAppCompatActivity;


public abstract class BaseActivity extends BaseAppCompatActivity implements BaseView {

    protected LoadingDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 禁止截图
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        try {
            if (TextUtils.equals(getClass().getSimpleName(), "SplashActivity") ||
                    TextUtils.equals(getClass().getSimpleName(), "GuideActivity")) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } else if (TextUtils.equals(getClass().getSimpleName(), "VideoActivity")) {
                StatusBarUtil.transparencyBar(this); //设置状态栏全透明
            } else {
                StatusBarUtil.transparencyBar(this); //设置状态栏全透明
                StatusBarUtil.StatusBarLightMode(this); //设置白底黑字
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                getWindow().setNavigationBarColor(Color.BLACK);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isApplyKitKatTranslucency()) {
            setSystemBarTintDrawable(ContextCompat.getDrawable(getContext(), R.drawable.sr_primary));
        }

        registerExitApp();
    }

    public void statusBarDark(boolean isDark) {
        ImmersionBar.with(this).statusBarDarkFont(isDark, 0.5f).init();
    }

    @Override
    public MintsApplication getBaseApplication() {
        return (MintsApplication) getApplication();
    }

    public Context getContext() {
        return this;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            View v = getCurrentFocus();

            //如果不是落在EditText区域，则需要关闭输入法
            if (HideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                FixUtils.fixInputMethodManagerLeak(this);
            }
        }
        return super.dispatchTouchEvent(ev);

    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean HideKeyboard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {

            int[] location = {0, 0};
            view.getLocationInWindow(location);

            //获取现在拥有焦点的控件view的位置，即EditText
            int left = location[0], top = location[1], bottom = top + view.getHeight(), right = left + view.getWidth();
            //判断我们手指点击的区域是否落在EditText上面，如果不是，则返回true，否则返回false
            boolean isInEt = (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom);
            return !isInEt;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        unRegisterExitApp();
        super.onDestroy();
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
    }


    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean toggleIsBack2Left() {
        return false;
    }

    /**
     * 显示加载进度条（自定义message）
     *
     * @param message
     */
    @Override
    public void showLoading(String message) {
        if (this.getWindow() != null && !this.isFinishing()) {
            if (progressDialog == null) {
                progressDialog = new LoadingDialog(this);
                progressDialog.setLoadText(message);
            }

            progressDialog.show();
            setProgressOnTouchOutside(false);
            setProgressNoDismiss();
        }
    }

    /**
     * 设置Progress是否手触消失
     *
     * @param onTouchOutside
     */
    public void setProgressOnTouchOutside(boolean onTouchOutside) {
        if (progressDialog != null)
            progressDialog.setCanceledOnTouchOutside(onTouchOutside);
    }

    /**
     * 设置点击返回是否消失加载进度条
     */
    public final void setProgressNoDismiss() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        return true;
                    }
                    return false;
                }
            });
        }
    }

    /**
     * 消失加载进度条
     */
    @Override
    public void hideLoading() {
        try {
            if (this.getWindow() != null && !this.isFinishing()) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            progressDialog = null;
        }
    }

    protected abstract boolean isApplyKitKatTranslucency();

    /**
     * 弹出系统的Toast
     */
    @Override
    public void showToast(String msg) {
        if (!TextUtils.isEmpty(msg))
            ToastUtil.show(MintsApplication.getContext(), msg);
    }

    /**
     * 注册退出app本地广播
     */
    private void registerExitApp() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_EXIT_APP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        MintsApplication.getLocalBroadcastManager().registerReceiver(mExitReceiver, filter);
    }

    private BroadcastReceiver mExitReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_EXIT_APP)) {
                finish();
            }
        }
    };

    /**
     * 注销退出app本地广播
     */
    private void unRegisterExitApp() {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.ACTION_EXIT_APP);
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            MintsApplication.getLocalBroadcastManager().unregisterReceiver(mExitReceiver);
        } catch (Exception e) {

        }

    }

}
