package com.gh.gamecenter.common.base.activity;

import static com.gh.gamecenter.common.constant.EntranceConsts.KEY_ENTRANCE;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.TransactionTooLargeException;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.view.LayoutInflaterCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.exception.NoRouteFoundException;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.common.BuildConfig;
import com.gh.gamecenter.common.R;
import com.gh.gamecenter.common.base.CustomLayoutInflaterFactory;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.eventbus.EBShowDialog;
import com.gh.gamecenter.common.tracker.IBusiness;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.DialogUtils;
import com.gh.gamecenter.common.utils.EnvHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.common.utils.DarkModeUtils;
import com.gh.gamecenter.common.utils.PackageFlavorHelper;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.core.provider.IDownloadManagerProvider;
import com.gh.gamecenter.core.provider.IEntranceUtilsProvider;
import com.gh.gamecenter.core.provider.IPackageInstallerProvider;
import com.gh.gamecenter.core.provider.IQuickLoginProvider;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.lightgame.BaseAppCompatActivity;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.FileUtils;
import com.lightgame.utils.Utils;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import kotlin.Pair;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 只提供基础的服务(EventBus/Share/GlobalDialog/Permissions)
 * <p>
 * 需要工具栏的页面请继承{@link ToolBarActivity}
 */

public abstract class BaseActivity extends BaseAppCompatActivity implements EasyPermissions.PermissionCallbacks, IBusiness {

    // global dialog key
    public final static String DOWNLOAD_HIJACK = "hijack";
    public final static String LOGIN_EXCEPTION = "loginException";
    public final static String PLUGGABLE = "plugin";
    public final static String SIGNATURE_CONFLICT = "signature_conflict";
    public final static int ID_ROOT_INDICATOR = 999;
    public final static int ID_NIGHT_INDICATOR = 998;
    public final int MAX_BUNDLE_SIZE = 300;

    @NonNull
    protected String mEntrance;

    private boolean mIsExistLogoutDialog;
    protected boolean mIsDarkModeOn;
    public long startPageTime = 0;

    private int mOldUiMode;
    private boolean mShouldApplyNewUiModeOnNextResume;

    protected final Handler mBaseHandler = new BaseHandler(this);

    protected static class BaseHandler extends Handler {

        private final WeakReference<BaseActivity> mActivityWeakReference;

        BaseHandler(BaseActivity activity) {
            mActivityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BaseActivity activity = mActivityWeakReference.get();
            if (activity != null) activity.handleMessage(msg);
        }
    }

    protected void handleMessage(Message msg) {

    }

    //接收QQ或者QQ空间分享回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ExtensionsKt.tryCatchInRelease(() -> {
            if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
                    || requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
                Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
            }
            return null;
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (isAutoResetViewBackgroundEnabled()) {
            LayoutInflaterCompat.setFactory2(getLayoutInflater(), new CustomLayoutInflaterFactory(this));
        }

        super.onCreate(savedInstanceState);

        mOldUiMode = getResources().getConfiguration().uiMode;

        if (useEventBus()) EventBus.getDefault().register(this);
        mEntrance = getIntent().getStringExtra(KEY_ENTRANCE);
        if (TextUtils.isEmpty(mEntrance)) {
            mEntrance = Constants.ENTRANCE_UNKNOWN;
        }

        if (BuildConfig.DEBUG) {
            Utils.log("ACTIVITY_ENTRANCE -> " + mEntrance);
        }

        disableAutofill();

        if (savedInstanceState != null) {
            String xapkUnzipActivity = SPUtils.getString(Constants.SP_XAPK_UNZIP_ACTIVITY);
            String xapkUrl = SPUtils.getString(Constants.SP_XAPK_URL);
            Utils.log("页面重建了--" + xapkUnzipActivity + "--" + xapkUrl);
            final Postcard postcard = ARouter.getInstance().build(RouteConsts.activity.splashActivity);
            LogisticsCenter.completion(postcard);
            final Class<?> destination = postcard.getDestination();
            if (this.getClass().isAssignableFrom(destination)) {
                SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
                SPUtils.setString(Constants.SP_XAPK_URL, "");
                return;
            }
            if (this.getClass().getName().equals(xapkUnzipActivity) && !TextUtils.isEmpty(xapkUrl)) {
                IDownloadManagerProvider downloadManagerConfig = (IDownloadManagerProvider) ARouter.getInstance().build(RouteConsts.provider.downloadManager).navigation();
                IPackageInstallerProvider packageInstallerConfig = (IPackageInstallerProvider) ARouter.getInstance().build(RouteConsts.provider.packageInstaller).navigation();
                DownloadEntity downloadEntity = downloadManagerConfig.getDownloadEntityByUrl(xapkUrl);
                if (downloadEntity != null) {
                    packageInstallerConfig.install(this, downloadEntity, false);
                    SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
                    SPUtils.setString(Constants.SP_XAPK_URL, "");
                }
            }
        }

        mIsDarkModeOn = DarkModeUtils.INSTANCE.isDarkModeOn(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startPageTime = System.currentTimeMillis();

        if (BuildConfig.IS_DARK_MODE_ON
                && !DarkModeUtils.INSTANCE.isFollowSystemDarkModeFromSp()
                && mIsDarkModeOn != DarkModeUtils.INSTANCE.isDarkModeOn(this)) {

            if (mShouldApplyNewUiModeOnNextResume) {
                // 返回时应用新的 config，否则后续 activity 更新时会无效
                onUiModeChanged(getResources().getConfiguration());
            } else {
                onDarkModeChanged();
            }
        }
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    public void setContentView(View view) {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            try {
                final Postcard postcard = ARouter.getInstance().build(RouteConsts.activity.splashActivity);
                LogisticsCenter.completion(postcard);
                final Class<?> destination = postcard.getDestination();
                if (!(this.getClass().isAssignableFrom(destination))) {
                    view = getRootViewWithEnvIndicator(view);
                }
            } catch (NoRouteFoundException e) {
                e.printStackTrace();
            }
        }
        super.setContentView(view);
    }

    @Override
    protected void onDestroy() {
        if (useEventBus()) EventBus.getDefault().unregister(this);
        mBaseHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    public void toast(String msg) {
        Utils.toast(this, msg);
    }

    public void toast(int msg) {
        toast(getString(msg));
    }

    public void showShare(String url,
                          String icon,
                          String shareTitle,
                          String shareSummary,
                          ShareUtils.ShareEntrance shareEntrance, String id) {
        showShareWithCallback(url, icon, shareTitle, shareSummary, shareEntrance, id, null);
    }

    public void showShareWithCallback(String url,
                                      String icon,
                                      String shareTitle,
                                      String shareSummary,
                                      ShareUtils.ShareEntrance shareEntrance,
                                      String id,
                                      ShareUtils.ShareCallBack callBack) {
        ShareUtils.getInstance(this).showShareWindowsCallback(this,
                getWindow().getDecorView(),
                url,
                icon,
                shareTitle,
                shareSummary,
                shareEntrance,
                id,
                callBack);
        if (shareEntrance == ShareUtils.ShareEntrance.game || shareEntrance == ShareUtils.ShareEntrance.plugin) {
            MtaHelper.onEvent("内容分享", "内容分享", shareTitle + shareSummary);
        } else {
            MtaHelper.onEvent("内容分享", "内容分享", shareTitle);
        }
    }

    /**
     * 关闭 editText 自动填充帐号 （我们也用不上），开启的时候有小概率出发 TimeoutException
     */
    private void disableAutofill() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().getDecorView().setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
        }
    }

    @Nullable
    private View getRootViewWithEnvIndicator(View view) {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            RelativeLayout screenRootView = new RelativeLayout(this);
            screenRootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

            LinearLayout ll = new LinearLayout(this);
            TextView tv = new TextView(this);
            String envText = "正式环境";
            tv.setBackground(ContextCompat.getDrawable(this, R.color.theme));
            if (EnvHelper.isDevEnv()) {
                envText = "测试环境";
                tv.setBackground(ContextCompat.getDrawable(this, R.color.theme_red));
            }
            tv.setText(envText);
            tv.setGravity(Gravity.CENTER);
            tv.setTextColor(Color.WHITE);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            tv.measure(0, 0);
            tv.setAlpha(0.15F);
            tv.setId(ID_ROOT_INDICATOR);
            int height = tv.getMeasuredHeight();
            int width = tv.getMeasuredWidth();
            tv.setPadding(DisplayUtils.dip2px(20), 0, DisplayUtils.dip2px(20), 0);
            ll.setTranslationX(DisplayUtils.dip2px(20));
            ll.setRotation(45);
            ll.addView(tv);
            ll.setPadding(0, (width - height) / 2, 0, (width - height) / 2);

            if (BuildConfig.DEBUG) {
                tv.setOnLongClickListener(v -> {
                    IEntranceUtilsProvider entranceUtilsProvider = (IEntranceUtilsProvider) ARouter.getInstance()
                            .build(RouteConsts.provider.entranceUtils)
                            .navigation();
                    entranceUtilsProvider.saveShortcut(this.getClass().getName(), getIntent().getExtras());
                    return true;
                });
            }

            screenRootView.addView(view);
            screenRootView.addView(ll);
            screenRootView.addView(getDarkModeIndicatorView());

            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ll.getLayoutParams();
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
            return screenRootView;
        } else {
            return null;
        }
    }

    @Nullable
    private View getDarkModeIndicatorView() {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            LinearLayout ll = new LinearLayout(this);
            TextView tv = new TextView(this);
            String envText = DarkModeUtils.INSTANCE.isDarkModeOn(this) ? "深色模式" : "浅色模式";
            tv.setBackground(ContextCompat.getDrawable(this, R.color.theme));
            tv.setText(envText);
            tv.setGravity(Gravity.CENTER);
            tv.setTextColor(Color.WHITE);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            tv.measure(0, 0);
            tv.setAlpha(DarkModeUtils.INSTANCE.isDarkModeOn(this) ? 0.8F : 0.15F);
            tv.setId(ID_NIGHT_INDICATOR);
            int height = tv.getMeasuredHeight();
            int width = tv.getMeasuredWidth();
            tv.setPadding(DisplayUtils.dip2px(20), 0, DisplayUtils.dip2px(20), 0);
            ll.setTranslationX(DisplayUtils.dip2px(-20));
            ll.setRotation(-45);
            ll.addView(tv);
            ll.setPadding(0, (width - height) / 2, 0, (width - height) / 2);
            return ll;
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(final EBShowDialog showDialog) {
        // 当当前实体被标记为使用过以后，不再响应它的内容
        if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
                && !showDialog.isUsed()) {
            showDialog.setUsed(true);
            IPackageInstallerProvider packageInstallerConfig = (IPackageInstallerProvider) ARouter.getInstance().build(RouteConsts.provider.packageInstaller).navigation();
            if (DOWNLOAD_HIJACK.equals(showDialog.getType())) {
                DialogUtils.showQqSessionDialog(this);// 建议用户联系客服
            } else if (PLUGGABLE.equals(showDialog.getType())) {
                DialogHelper.showPluginDialog(this, () -> {
                    if (FileUtils.isEmptyFile(showDialog.getPath())) {
                        toast(R.string.install_failure_hint);
                    } else {
                        packageInstallerConfig.uninstall(BaseActivity.this, showDialog.getPath());
                    }
                    return null;
                });
            } else if (SIGNATURE_CONFLICT.equals(showDialog.getType())) {
                DialogHelper.showSignatureConflictDialog(this, () -> {
                    packageInstallerConfig.uninstall(BaseActivity.this, showDialog.getPath());
                    return null;
                });
            } else if (LOGIN_EXCEPTION.equals(showDialog.getType())) {
                if (mIsExistLogoutDialog) return;
                mIsExistLogoutDialog = true;
                try {
                    JSONObject object = new JSONObject(showDialog.getPath());
                    JSONObject device = object.getJSONObject("device");
                    String model = device.getString("model");
                    DialogHelper.showCenterDialog(this, "你的账号已在另外一台设备登录"
                            , StringUtils.buildString("（", model, "）")
                            , "知道了", "重新登录"
                            , () -> {
                            }
                            , () -> {
                                if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(BaseActivity.this)) {
                                    IQuickLoginProvider quickLoginConfig = (IQuickLoginProvider) ARouter.getInstance().build(RouteConsts.provider.quickLogin).navigation();
                                    quickLoginConfig.startLogin(BaseActivity.this, "你的账号已在另外一台设备登录多设备-重新登录");
                                } else {
                                    ARouter.getInstance().build(RouteConsts.activity.loginActivity)
                                            .withString(EntranceConsts.KEY_ENTRANCE, "你的账号已在另外一台设备登录多设备-重新登录")
                                            .navigation();
                                }
                            }
                    );
                    mBaseHandler.postDelayed(() -> mIsExistLogoutDialog = false, 5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

        if (isFinishing()) {
            onFinish();
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                if (fragment.isAdded() && fragment instanceof BaseFragment) {
                    ((BaseFragment) fragment).onParentActivityFinish();
                }
            }
        }
    }

    /**
     * 此回调可用于确认当前 activity 已经执行了 finish() 方法并处于 isFinishing 状态
     */
    protected void onFinish() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    protected void setStatusBarColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(color);
        }
    }

    /**
     * 提供当前 activity 的中文名 (不重载的话为类名)
     */
    public String getActivityNameInChinese() {
        return getClass().getSimpleName();
    }

    /**
     * @param entrance 上一个页面的链式入口名称
     * @param path     当前页面名称
     * @return 完整的链式入口名称
     */
    public static String mergeEntranceAndPath(String entrance, String path) {
        if (TextUtils.isEmpty(entrance) && TextUtils.isEmpty(path)) return "";
        if (TextUtils.isEmpty(entrance) && !TextUtils.isEmpty(path)) {
            return StringUtils.buildString("(", path, ")");
        }
        if (!TextUtils.isEmpty(entrance) && TextUtils.isEmpty(path)) {
            return entrance;
        }
        return StringUtils.buildString(entrance, "+(", path, ")");
    }

    protected boolean useEventBus() {
        return true;
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources.getConfiguration().fontScale != 1.0f) {
            Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }


    /**
     * ActivityThread每次调用onSaveInstanceState时outState大小都会累加，最终会导致{@link TransactionTooLargeException}异常
     * 解决方案：判断每次获取到的outState大小，当达到300k时手动clear掉
     */
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        if (preventRecreateFragmentByFragmentManager()) {
            outState = discardFragmentFromSaveInstanceState(outState);
        }

        long bundleSize = getBundleSize(outState);
        if (bundleSize > MAX_BUNDLE_SIZE * 1024) {
            outState.clear();
        }
    }

    /**
     * 是否停用 Activity 重建时 FragmentManager 根据 saveState 自动重建保存的 Fragment 的功能
     */
    protected boolean preventRecreateFragmentByFragmentManager() {
        return false;
    }

    private Bundle discardFragmentFromSaveInstanceState(Bundle outState) {
        if (outState != null) {
            outState.remove("android:support:fragments");
        }
        return outState;
    }

    private long getBundleSize(Bundle bundle) {
        long dataSize;
        Parcel obtain = Parcel.obtain();
        try {
            obtain.writeBundle(bundle);
            dataSize = obtain.dataSize();
        } finally {
            obtain.recycle();
        }
        return dataSize;
    }

    @Override
    public Pair<String, String> getBusinessId() {
        return new Pair<>("", "");
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        if (mOldUiMode == newConfig.uiMode) {
            super.onConfigurationChanged(newConfig);
        } else {
            boolean isCalledBySystem = true;

            // 系统回调的 onConfigurationChanged 必须要调用 super.onConfigurationChanged 否则可能会触发卡死
            // 这里根据调用栈是否存在 DarkModeUtils 来确定是否为系统回调
            StackTraceElement[] trace = Thread.currentThread().getStackTrace();
            for (StackTraceElement element : trace) {
                if (element.getClassName().equals(DarkModeUtils.class.getName())) {
                    isCalledBySystem = false;
                    break;
                }
            }

            Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setCategory("onConfigurationChanged");
            breadcrumb.setMessage("IsCalledBySystem " + isCalledBySystem + ","
                    + this.getClass().getSimpleName() + " lifecycle is " + getLifecycle().getCurrentState());
            breadcrumb.setLevel(SentryLevel.INFO);
            Sentry.addBreadcrumb(breadcrumb);

            if (BuildConfig.IS_DARK_MODE_ON && mIsDarkModeOn != DarkModeUtils.INSTANCE.isDarkModeOn(this)) {
                // 当且仅当页面处于可见状态时响应新的 UiMode，并将它传递下去
                // （在不可见的 activity 调用 onConfigurationChanged 方法有一定概率触发 ANR）
                if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
                    onUiModeChanged(newConfig);
                } else {
                    if (isCalledBySystem) {
                        super.onConfigurationChanged(newConfig);
                    }
                    mShouldApplyNewUiModeOnNextResume = true;
                }
            } else {
                if (isCalledBySystem) {
                    super.onConfigurationChanged(newConfig);
                }
            }
        }
    }

    /**
     * 应用新的 UiMode
     */
    private void onUiModeChanged(@NonNull Configuration newConfig) {
        mOldUiMode = newConfig.uiMode;
        super.onConfigurationChanged(newConfig);
        mIsDarkModeOn = DarkModeUtils.INSTANCE.isDarkModeOn(this);
        onDarkModeChanged();
        mShouldApplyNewUiModeOnNextResume = false;
    }

    protected void onDarkModeChanged() {
        if (BuildConfig.IS_DARK_MODE_ON) {
            TextView tv = findViewById(ID_NIGHT_INDICATOR);
            if (tv != null) {
                tv.setText(DarkModeUtils.INSTANCE.isDarkModeOn(this) ? "深色模式" : "浅色模式");
                tv.setAlpha(DarkModeUtils.INSTANCE.isDarkModeOn(this) ? 0.8F : 0.15F);
            }
            if (isAutoResetViewBackgroundEnabled()) {
                updateStaticViewBackground(getWindow().getDecorView());
            }
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(this, R.color.background));
                getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.background_white));
            }
        }
    }

    protected boolean isAutoResetViewBackgroundEnabled() {
        return true;
    }

    /**
     * 自动重置部分 view 的背景颜色/资源
     *
     * @param view 父 view
     */
    protected void updateStaticViewBackground(View view) {
        updateStaticView(view, new ArrayList<>());
    }

    public static void updateStaticView(View view, List<Integer> blackList) {
        for (Integer viewId : blackList) {
            if (viewId == view.getId()) return;
        }

        Context context = view.getContext();
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View child = ((ViewGroup) view).getChildAt(i);
                updateStaticView(child, blackList);
            }
        }

        String backgroundString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_BACKGROUND_ID());
        String textColorString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_TEXT_COLOR_ID());
        String textColorHintString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_TEXT_COLOR_HINT_ID());
        String srcString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_SRC_ID());
        String drawableLeftString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_DRAWABLE_LEFT_ID());
        String drawableTopString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_DRAWABLE_TOP_ID());
        String drawableRightString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_DRAWABLE_RIGHT_ID());
        String drawableBottomString = (String) view.getTag(CustomLayoutInflaterFactory.Companion.getTAG_DRAWABLE_BOTTOM_ID());

        if (view instanceof SimpleDraweeView) {
            ExtensionsKt.dimOnDarkMode((ImageView) view);
        }

        if (backgroundString != null) {
            if (backgroundString.startsWith("#")) return;
            int backgroundId = getIntFromString(backgroundString);

            if (backgroundId != 0) {
                try {
                    TypedValue value = new TypedValue();
                    context.getResources().getValue(backgroundId, value, true);

                    if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
                        view.setBackgroundColor(ExtensionsKt.toColor(backgroundId, context));
                    } else {
                        view.setBackground(ExtensionsKt.toDrawable(backgroundId, context));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (textColorString != null && view instanceof TextView) {
            if (textColorString.startsWith("#")) return;
            int textColorId = getIntFromString(textColorString);

            if (textColorId != 0) {
                try {
                    final ColorStateList colorStateList = ContextCompat.getColorStateList(context, textColorId);
                    ((TextView) view).setTextColor(colorStateList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (textColorHintString != null && view instanceof EditText) {
            if (textColorHintString.startsWith("#")) return;
            int textColorHintId = getIntFromString(textColorHintString);

            if (textColorHintId != 0) {
                try {
                    final ColorStateList colorStateList = ContextCompat.getColorStateList(context, textColorHintId);
                    ((EditText) view).setHintTextColor(colorStateList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (view instanceof ImageView && srcString != null) {
            if (srcString.startsWith("#")) return;
            int srcId = getIntFromString(srcString);
            if (srcId != 0) {
                ((ImageView) view).setImageResource(srcId);
            }
        }

        if (view instanceof TextView) {
            Drawable drawableLeft = null;
            Drawable drawableTop = null;
            Drawable drawableRight = null;
            Drawable drawableBottom = null;
            if (drawableLeftString != null) {
                if (drawableLeftString.startsWith("#")) return;
                int drawableLeftId = getIntFromString(drawableLeftString);
                if (drawableLeftId != 0) {
                    drawableLeft = ExtensionsKt.toDrawable(drawableLeftId, context);
                }
            }
            if (drawableTopString != null) {
                if (drawableTopString.startsWith("#")) return;
                int drawableTopId = getIntFromString(drawableTopString);
                if (drawableTopId != 0) {
                    drawableTop = ExtensionsKt.toDrawable(drawableTopId, context);
                }
            }
            if (drawableRightString != null) {
                if (drawableRightString.startsWith("#")) return;
                int drawableRightId = getIntFromString(drawableRightString);
                if (drawableRightId != 0) {
                    drawableRight = ExtensionsKt.toDrawable(drawableRightId, context);
                }
            }
            if (drawableBottomString != null) {
                if (drawableBottomString.startsWith("#")) return;
                int drawableBottomId = getIntFromString(drawableBottomString);
                if (drawableBottomId != 0) {
                    drawableBottom = ExtensionsKt.toDrawable(drawableBottomId, context);
                }
            }
            if (drawableLeft != null || drawableTop != null || drawableRight != null || drawableBottom != null) {
                ((TextView) view).setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom);
            }
        }
    }

    private static int getIntFromString(String rawString) {
        return Integer.parseInt(rawString.replace("@", "").replace("?", ""));
    }
}
