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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.common.R;
import com.gh.gamecenter.common.base.fragment.ToolbarController;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.lightgame.OnTitleClickListener;

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

/**
 * 需要用到工具栏的页面使用
 * <p>
 * 特殊页面请参考{@link BaseActivity}
 */

public abstract class ToolBarActivity extends BaseActivity implements ToolbarController, ActionMenuView.OnMenuItemClickListener {

    public static final String NORMAL_FRAGMENT_NAME = "normalFragmentName";
    public static final String NORMAL_FRAGMENT_BUNDLE = "normalFragmentBundle";

    private Fragment mTargetFragment;

    protected View mToolbarContainer;

    protected Toolbar mToolbar;

    protected TextView mTitleTv;

    protected TextView mAdLabelTv;

    protected LinearLayout mTitleContainer;

    protected LinearLayout mIconTitleContainer;

    protected FrameLayout mBackContainer;

    protected ActionMenuView mActionMenuView;

    protected View mBackBtn;

    protected SimpleDraweeView mUserAvatarIv;

    protected TextView mIconTitle;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_normal;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarDarkMode(true, this);
        initToolbar();

        if (getIntent() != null) {
            if (savedInstanceState == null) {
                handleIntent(getIntent());
            } else {
                for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                    if (fragment instanceof ToolbarFragment) mTargetFragment = fragment;
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (getIntent() != null) handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        String fraName = intent.getStringExtra(NORMAL_FRAGMENT_NAME);
        Bundle bundle = intent.getBundleExtra(NORMAL_FRAGMENT_BUNDLE);
        if (TextUtils.isEmpty(fraName)) {
            if (provideNormalIntent() == null) {
                return;
            }
            fraName = provideNormalIntent().getStringExtra(NORMAL_FRAGMENT_NAME);
            if (bundle == null) bundle = getIntent().getExtras();
            if (TextUtils.isEmpty(fraName)) return;
        }
        mTargetFragment = getSupportFragmentManager().findFragmentByTag(fraName);
        if (mTargetFragment == null) {
            mTargetFragment = Fragment.instantiate(this, fraName, bundle);
        }
        getSupportFragmentManager().beginTransaction().replace(getFragmentPlaceholderId(), mTargetFragment, fraName).commitNowAllowingStateLoss();
    }

    // 小米沉浸式黑色字体
    @SuppressLint("PrivateApi")
    public void setStatusBarDarkMode(boolean darkmode, Activity activity) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
        } catch (Exception ignore) {

        }
    }

    private void initToolbar() {
        mToolbarContainer = findViewById(R.id.normal_toolbar_container);
        mToolbar = findViewById(R.id.normal_toolbar);
        mTitleTv = findViewById(R.id.normal_title);
        mAdLabelTv = findViewById(R.id.adLabelTv);
        mActionMenuView = findViewById(R.id.actionMenuView);
        mTitleContainer = findViewById(R.id.titleContainer);
        mIconTitleContainer = findViewById(R.id.iconTitleContainer);
        mBackContainer = findViewById(R.id.backContainer);
        mBackBtn = findViewById(R.id.backBtn);
        mUserAvatarIv = findViewById(R.id.userAvatar);
        mIconTitle = findViewById(R.id.iconTitle);
        if (mToolbar != null) {
//            setSupportActionBar(mToolbar); // 替换actionBar后 toolBar无法控制
            if (mBackBtn != null) mBackBtn.setOnClickListener(provideNavigationItemClickListener());
            if (mBackContainer != null) mBackContainer.setOnClickListener(provideNavigationItemClickListener());
            if (mTitleTv != null) {
                mTitleTv.setOnClickListener(view -> {
                    final List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
                    for (Fragment fragment : fragmentList) {
                        if (fragment instanceof OnTitleClickListener) {
                            ((OnTitleClickListener) fragment).onTitleClick();
                        }
                    }
                });
            }
        }
    }

    @DrawableRes
    public int provideNavigationIcon() {
        return R.drawable.ic_bar_back; // default navigation icon
    }

    @Override
    public void setNavigationTitle(String title) {
        if (mTitleTv != null) mTitleTv.setText(title);
        if (mIconTitle != null) mIconTitle.setText(title);
    }

    @Override
    public void setNavigationTitle(@StringRes int res) {
        setNavigationTitle(getString(res));
    }

    /**
     * 重写此方法以将标题靠左显示
     */
    public boolean showToolbarAtLeft() {
        return false;
    }

    @Override
    public void setToolbarMenu(int res) {
        if (mActionMenuView == null) return;
        inflateMenu(res);
        mActionMenuView.setOnMenuItemClickListener(this);
        Menu menu = mActionMenuView.getMenu();
        for (int i = 0; i < menu.size(); i++) {
            MenuItem menuItem = menu.getItem(i);
            // menu设置actionLayout后，无法捕捉点击事件，以icon为tag，如果icon is null 手动设置menuItem点击事件
            if (menuItem != null && menuItem.getIcon() == null) {
                if (menuItem.getActionView() != null) {
                    menuItem.getActionView().setOnClickListener((v) -> this.onMenuItemClick(menuItem));
                }
            }
        }

        if (showToolbarAtLeft() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mTitleTv != null) {
            mTitleTv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }
        setTitleCenter();
    }

    public void inflateMenu(int res) {
        getMenuInflater().inflate(res, mActionMenuView.getMenu());
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitleCenter();
    }

    // 设置标题居中
    public void setTitleCenter() {
        if (mActionMenuView != null && mTitleContainer != null && mBackContainer != null && !showToolbarAtLeft()) {
            mActionMenuView.post(() -> {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTitleContainer.getLayoutParams();
                params.setMargins(mActionMenuView.getWidth() - mBackContainer.getWidth(), 0, 0, 0);
                mTitleContainer.setLayoutParams(params);
            });
        }
    }

    public void setUserAvatarIconToolbar(String icon) {
        mTitleContainer.setVisibility(View.GONE);
        ImageUtils.display(mUserAvatarIv, icon);
        mUserAvatarIv.setVisibility(View.VISIBLE);
        mIconTitleContainer.setVisibility(View.VISIBLE);
    }

    @Override
    public MenuItem getMenuItem(int res) {
        if (mToolbar == null) return null; //后续页面做好判断
        return mActionMenuView.getMenu().findItem(res);
    }

    public void clearMenu() {
        if (mToolbar != null) {
            mActionMenuView.getMenu().clear();
            setTitleCenter();
        }
    }

    public Menu getMenu() {
        return mActionMenuView.getMenu();
    }

    public ActionMenuView getActionMenuView() {
        return mActionMenuView;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (mTargetFragment instanceof ToolbarFragment) {
            ((ToolbarFragment) mTargetFragment).onMenuItemClick(item);
        }
        return false;
    }

    protected View.OnClickListener provideNavigationItemClickListener() {
        return view -> onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (mTargetFragment != null) {
            if (mTargetFragment instanceof ToolbarFragment
                    && mTargetFragment.isAdded()
                    && !((ToolbarFragment) mTargetFragment).onBackPressed()) {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mTargetFragment instanceof ToolbarFragment) {
            ((ToolbarFragment) mTargetFragment).onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public Fragment getTargetFragment() {
        return mTargetFragment;
    }

    public int getFragmentPlaceholderId() {
        return R.id.normal_content;
    }

    @Override
    public void hideToolbar(boolean isHide) {
        if (mToolbarContainer != null) {
            mToolbarContainer.setVisibility(isHide ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void showAdLabel(boolean isAd) {
        mAdLabelTv.setVisibility(isAd ? View.VISIBLE : View.GONE);
    }

    // 针对部分跳转不符合ToolbarActivity规则的额外处理，主要绑定ToolbarFragment
    protected Intent provideNormalIntent() {
        return null;
    }

    protected static Intent getTargetIntent(Context context, Class<? extends ToolBarActivity> cls, Class<? extends ToolbarFragment> t, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        intent.putExtra(NORMAL_FRAGMENT_NAME, t.getCanonicalName());
        intent.putExtra(NORMAL_FRAGMENT_BUNDLE, bundle);
        return intent;
    }

    protected static Intent getTargetIntent(Context context, Class<? extends ToolBarActivity> cls, Class<? extends ToolbarFragment> t) {
        Intent intent = new Intent(context, cls);
        intent.putExtra(NORMAL_FRAGMENT_NAME, t.getCanonicalName());
        return intent;
    }


    public static void startFragmentNewTask(Context context, Class<? extends ToolbarFragment> t, Bundle bundle) {
        Intent intent = new Intent(context, ToolBarActivity.class);
        intent.putExtra(NORMAL_FRAGMENT_NAME, t.getCanonicalName());
        intent.putExtra(NORMAL_FRAGMENT_BUNDLE, bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void startFragment(Context context, Class<? extends ToolbarFragment> t, Bundle bundle) {
        Intent intent = new Intent(context, ToolBarActivity.class);
        intent.putExtra(NORMAL_FRAGMENT_NAME, t.getCanonicalName());
        intent.putExtra(NORMAL_FRAGMENT_BUNDLE, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        if (mToolbar != null) {
            mToolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.background_white));
        }
        if (mBackBtn != null) {
            if (mBackBtn instanceof ImageView) {
                ((ImageView) mBackBtn).setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_bar_back));
            } else if (mBackBtn instanceof TextView) {
                ((TextView) mBackBtn).setTextColor(ContextCompat.getColor(this, R.color.text_subtitle));
            }
        }
        if (mTitleTv != null) {
            mTitleTv.setTextColor(ContextCompat.getColor(this, R.color.text_black));
        }
    }

    /**
     * 更新 targetFragment 引用
     */
    protected void updateTargetFragment(Fragment fragment) {
        mTargetFragment = fragment;
    }

}
