package com.zxhl.cms.common.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.core.content.ContextCompat;

import com.badoo.mobile.util.WeakHandler;
import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar;
import com.zxhl.cms.AppContext;
import com.zxhl.cms.R;
import com.zxhl.cms.utils.ActivityManager;
import com.zxhl.cms.utils.ClipboardManagerUtil;
import com.zxhl.cms.utils.DisplayUtil;
import com.zxhl.cms.utils.JumpUtils;
import com.zxhl.cms.utils.LogUtils;
import com.zxhl.cms.utils.StatusBarUtils;
import com.zxhl.cms.utils.Utils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.zxhl.cms.widget.CenterDialog;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * Created by gaoleichao on 2018/4/25.
 */

public abstract class BaseActivity extends RxAppCompatActivity implements View.OnClickListener {
    public Context mActivity;
    private WeakHandler baseHandler;
    protected boolean mIsNeedGoneNavigationBar = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        before();
        super.onCreate(savedInstanceState);
        if (layoutID() != 0) {
            setContentView(layoutID());
        }
        after();
        init();
        init(savedInstanceState);
        data();
    }

    public void before() {
        mActivity = this;
        baseHandler = new WeakHandler();
        StatusBarUtils.transportStatus(this);
        ActivityManager.getInstance().addActivity(this);
//        setStatusBarIconAndTextBlack();
    }

    protected void after() {
    }

    /**
     * 设置状态栏
     */
    protected void setStatusBarIconAndTextBlack() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isXiaoMiPhone()) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        } else {
            MIUISetStatusBarLightMode(getWindow(), false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                getWindow().setStatusBarColor(getResources().getColor(R.color.white));
            }

        }
    }


    /**
     * 设置小米手机状态栏字体图标颜色模式，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public void MIUISetStatusBarLightMode(Window window, boolean dark) {
        String name = Utils.getSystemProperty("ro.miui.ui.version.name");
        if (TextUtils.equals(name, "V9")) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        } else {
            if (window != null) {
                Class clazz = window.getClass();
                try {
                    int darkModeFlag = 0;
                    Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                    Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                    darkModeFlag = field.getInt(layoutParams);
                    Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                    if (dark) {//状态栏透明且黑色字体
                        extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
                    } else {//清除黑色字体
                        extraFlagField.invoke(window, 0, darkModeFlag);
                    }
                } catch (Exception e) {

                }
            }
        }
    }

    public boolean isXiaoMiPhone() {
        return "Xiaomi".equalsIgnoreCase(Build.MANUFACTURER) || Build.MODEL.contains("Redmi");
    }

    /**
     * 设置状态栏背景色
     *
     * @param color
     */
    protected void setStatusBarBackground(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //注意要清除 FLAG_TRANSLUCENT_STATUS flag
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(color);
        }
    }

    /**
     * 设置状态栏透明
     */
    protected void setStatusBarTranslucent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    public abstract int layoutID();

    public abstract void init();

    public void data() {

    }

    public void init(Bundle savedInstanceState) {

    }

    // 隐藏键盘
    public void hideKeyBoard() {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 显示键盘
    public void showKeyBoard(View view) {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        ActivityManager.getInstance().finishActivity(this);
        Glide.get(this).clearMemory();
        Glide.get(this).trimMemory(TRIM_MEMORY_MODERATE);
        System.gc();
//        RefWatcher refWatcher = Appli.getRefWatcher(this);//1
//        refWatcher.watch(this);
        super.onDestroy();
    }

    /**
     * 短时间显示Toast
     *
     * @param info 显示的内容
     */
    public void showToast(String info) {
        Utils.showToast(this, info);
    }

    public void showSnake(View view, String info) {
        Snackbar.make(view, info, Snackbar.LENGTH_LONG).show();
    }

    public void showSnake(View view, String info, String actionInfo, View.OnClickListener listener) {
        Snackbar.make(view, info, Snackbar.LENGTH_LONG).setAction(actionInfo, listener).show();
    }

    /**
     * 短时间显示Toast
     *
     * @param resId 显示的内容
     */
    public void showToast(int resId) {
        showToast(getString(resId));
    }


    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    public void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    public Context getContext() {
        return this;
    }


    /**
     * 启动Activity
     */
    protected void openActivity(String pAction) {
        openActivity(pAction, null);
    }

    /**
     * 启动Activity
     */
    protected void openActivity(String pAction, Bundle pBundle) {
        Intent intent = new Intent(pAction);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    public void openActivity(Class<?> pClass, Bundle pBundle, int animId, int animId2) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
        overridePendingTransition(animId, animId2);
    }

    /**
     * 关闭Activity
     */
    public void finish() {
        ActivityManager.getInstance().finishActivity(this);
        System.gc();
        super.finish();
    }

    /**
     * 关闭Activity
     */
    public void finish(int animId, int animId2) {
        super.finish();
        overridePendingTransition(animId, animId2);
    }

    /**
     * 关闭Activity
     */
    public void defaultFinish() {
        super.finish();
    }

    /**
     * 设置是否隐藏导航栏
     *
     * @param isNeed
     */
    protected void setNeedGoneNavigationBar(boolean isNeed) {
        mIsNeedGoneNavigationBar = isNeed;
        if (mIsNeedGoneNavigationBar) {
            baseHandler.postDelayed(mHideRunnable, 200);
            final View decorView = getWindow().getDecorView();
            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    decorView.requestLayout();

                }
            });
        }
    }

    // 判断是否缺少权限
    protected boolean needsPermission(String permission) {
        return ContextCompat.checkSelfPermission(getApplication(), permission) != PackageManager.PERMISSION_GRANTED;
    }

    protected Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            int flags;
            int curApiVersion = Build.VERSION.SDK_INT;
            // This work only for android 4.4+
            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {
                // This work only for android 4.4+
                // hide navigation bar permanently in android activity
                // touch the screen, the navigation bar will not show
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN;

            } else {
                // touch the screen, the navigation bar will show
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            // must be executed in main thread :)
            getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    };


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory();
        }
        Glide.get(this).trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).clearMemory();
    }

    @Override
    public void finishActivity(int requestCode) {
        super.finishActivity(requestCode);
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onStart() {
        super.onStart();


    }

    //    static float fontScale = 1f;
//
//    @Override
//    public Resources getResources() {
//        Resources resources = super.getResources();
//        return DisplayUtil.getResources(this,resources,fontScale);
//    }
//
//    @Override
//    protected void attachBaseContext(Context newBase) {
//        super.attachBaseContext(DisplayUtil.attachBaseContext(newBase,fontScale));
//    }
//
//    public void setFontScale(float fontScale) {
//        this.fontScale = fontScale;
//        DisplayUtil.recreate(this);
//    }
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

}
