package com.mq.oaapp.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.mq.oaapp.R;
import com.xyxsbj.mylibrary.tool.ActivityTool;
import com.xyxsbj.mylibrary.tool.LogTool;

import java.util.ArrayList;

import butterknife.ButterKnife;

/**
 * 创建人 mQ
 * 创建时间 2018/12/10 0010 17:06
 * 文件名称 BaseActivity
 * 说明:
 **/
public abstract class BaseActivity extends AppCompatActivity {

    private int mScreenOrientation = 0;//0 不限制, 1 横向, 2 纵向

    private ArrayList<BaseOnTouchListener> onTouchListeners = new ArrayList<>();

    private boolean active;
    private Gson mGson;
    private View mProgressBar;
    private boolean mIsLight = false;

    protected abstract int getLayoutRes();

    protected abstract void init();

    protected abstract void workTask();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutRes());
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                showLightOrDark();
            }
        });
        ButterKnife.bind(this);
        active = true;
        init();
        workTask();
    }
//    android:fitsSystemWindows="true"

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        //设置沉浸式标题栏颜色
        StatusBarUtil.setTranslucent(this, 0);
        setFitsSystemWindows(this, false);
    }

    /**
     * 设置界面主题的明暗
     */
    public void setActivityLightOrDark(boolean isLight) {
        mIsLight = isLight;
        showLightOrDark();
    }
    private void showLightOrDark() {
        if (mIsLight)
            ActivityTool.hideNavigationAndLight(getContext(), getWindow());
        else
            ActivityTool.hideNavigationAndDark(getContext(), getWindow());

    }

    @Override
    protected void onResume() {
        setScreenOrientation();
        super.onResume();
        //隐藏底部虚拟按键
//        ActivityTool.hideNavigationAndLight(getContext(), getWindow());
//        LogTool.d("基类onResume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        active = false;

    }

    public boolean isActive() {
        return active;
    }

    /*点击屏幕非文本框的区域,关闭键盘*/
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (BaseOnTouchListener l : onTouchListeners) {
            if (l != null)
                l.onTouch(ev);
        }
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /*** 注册触摸事件 ***/
    public void registOnTouchListener(BaseOnTouchListener listener) {
        onTouchListeners.add(listener);
    }

    /*** 解除触摸事件 ***/
    public void unregistOnTouchListener(BaseOnTouchListener listener) {
        onTouchListeners.remove(listener);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom);
        }
        return false;
    }

    /**
     * 设置窗口为全屏
     */
    protected void setWindowIsFullscreen() {
        //隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 是否将屏幕限制为横向, 不调用此方法则不限制横纵切换
     *
     * @param isLandscape true 限制为横向  false 限制为纵向
     */
    protected void setScreenLandscape(boolean isLandscape) {
        if (isLandscape) {
            mScreenOrientation = 1;
        } else {
            mScreenOrientation = 2;
        }
    }


    /**
     * 设置屏幕方向
     */
    private void setScreenOrientation() {
        if (mScreenOrientation == 1) {
            //屏幕切换为横向
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else if (mScreenOrientation == 2) {
            //屏幕切换为纵向
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }
    }

    /**
     * 给整个页面做顶部间距
     */
    public void setStatusHeightForContent() {
        setStatusHeight(findViewById(android.R.id.content));
    }

    /**
     * 获取状态栏高度 给View添加顶部间距
     */
    protected void setStatusHeight(View statusView) {
//        StatusBarUtil.setTranslucent(this, 0);
        //获取状态栏高度
        int height = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            height = getResources().getDimensionPixelSize(resourceId);
        }
        LogTool.i("状态栏高度setStatusHeight: " + height);
        //将高度赋值给View
        statusView.setPadding(0, height, 0, 0);
    }

    private int getNavigationBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Navi height:" + height);
        return height;
    }

    /**
     * 设置页面最外层布局 FitsSystemWindows 属性 *
     *
     * @param activity
     * @param value
     */
    public void setFitsSystemWindows(Activity activity, boolean value) {
        ViewGroup contentFrameLayout = activity.findViewById(android.R.id.content);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null) {
            parentView.setFitsSystemWindows(value);
        }
    }


    /**
     * 根据手机或平板设定横屏或竖屏
     */
    protected void setScreenOrientationForPhoneAndPad() {
        if (!isTabletDevice()) {
            //手机，竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        } else {
            //平板，横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }
    }

    /**
     * 判断是否平板设备
     *
     * @return true:平板,false:手机
     */
    protected boolean isTabletDevice() {
        return (getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public Context getContext() {
        return this;
    }


    public Gson getGson() {
        if (mGson == null)
            mGson = new Gson();
        return mGson;
    }

    /**
     * 弹出等待对话框
     */
    public void showLoading(boolean isTouch) {
        mProgressBar = findViewById(R.id.progressBar);
        if (mProgressBar == null)
            return;
        mProgressBar.setVisibility(View.VISIBLE);
        if (!isTouch) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    /**
     * 隐藏等待对话框
     */
    public void dismissLoading() {
        if (mProgressBar == null)
            return;
        mProgressBar.setVisibility(View.GONE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

}
