package com.gh.gamecenter.libao;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.databinding.FragmentLibao1Binding;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.lightgame.utils.Util_System_Keyboard;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by khy on 5/09/17.
 */

public class Libao1Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private FragmentLibao1Binding mBinding;

    public final static String OPEN_LIBAO_APPBAR = "open_libao_appbar";

    private LibaoSearchFragment mSearchFragment;
    private LibaoNewFragment mNewFragment;

    private boolean mIsSearch;
    private boolean mIsTouchScreen;

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = FragmentLibao1Binding.bind(mCachedView);
        mBinding.libaoRefresh.setColorSchemeResources(R.color.theme);
        mBinding.libaoRefresh.setOnRefreshListener(this);
        mBinding.libaoRefresh.setEnabled(false);
        mBinding.searchBar.tvBack.setOnClickListener(this);
        mBinding.searchBar.tvSearch.setOnClickListener(this);

        changeFragment();

        mBinding.libaoAppbar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                mBinding.libaoRefresh.setEnabled(true);
            } else {
                mBinding.libaoRefresh.setEnabled(false);
            }
            int totalScrollRange = appBarLayout.getTotalScrollRange();
            if (totalScrollRange == -verticalOffset) {
                Util_System_Keyboard.hideSoftKeyboard(getActivity());
            }
        });

        mBinding.searchBar.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mBinding.searchBar.tvSearch.performClick();
            }
            return false;
        });

        TextHelper.limitTheLengthOfEditText(mBinding.searchBar.etSearch, 50, () -> Utils.toast(mBinding.searchBar.etSearch.getContext(), "最多输入50个字"));
    }

    private void changeFragment() {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        hideFragments(transaction);
        if (mIsSearch) {
            mSearchFragment = alterFragment(transaction, LibaoSearchFragment.class);
        } else {
            mNewFragment = alterFragment(transaction, LibaoNewFragment.class);
        }

        transaction.commitAllowingStateLoss();
    }

    private <T extends Fragment> T alterFragment(FragmentTransaction transaction, Class<T> cls) {
        T fragmentByTag = (T) getChildFragmentManager().findFragmentByTag(cls.getSimpleName());
        try {
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag);
                if (fragmentByTag instanceof LibaoSearchFragment) {
                    ((LibaoSearchFragment) fragmentByTag).search();
                }
            } else {
                fragmentByTag = cls.newInstance();
                transaction.add(R.id.layout_fragment_content, fragmentByTag, cls.getSimpleName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fragmentByTag;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_back:
                mIsSearch = false;
                mBinding.searchBar.etSearch.setText("");
                break;
            case R.id.tv_search:
                MtaHelper.onEvent("我的光环_新", "礼包中心", "点击搜索");
                String key = mBinding.searchBar.etSearch.getText().toString();
                if (TextUtils.isEmpty(key)) {
                    toast(R.string.search_hint);
                    return;
                } else if (!mIsSearch) {
                    mIsSearch = true;
                }
                break;
        }
        if (mIsSearch) {
            mBinding.searchBar.tvBack.setVisibility(View.VISIBLE);
        } else {
            mBinding.searchBar.tvBack.setVisibility(View.GONE);
        }
        Util_System_Keyboard.hideSoftKeyboard(getActivity());
        changeFragment();
    }

    public String getSearchKey() {
        return mBinding == null ? "" : mBinding.searchBar.etSearch.getText().toString();
    }

    @Override
    public void onRefresh() {
        if (mIsSearch) {
            mSearchFragment.onRefresh();
        } else {
            mNewFragment.onRefresh();
        }
    }

    public void stopRefresh() {
        mBinding.libaoRefresh.setRefreshing(false);
    }

    // 页面切换事件（查看历史礼包的页面）
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (LibaoFragment.LIBAO_OPENPAGE.equals(reuse.getType())) {
            mBinding.libaoAppbar.setVisibility(View.GONE);
            mBinding.libaoRefresh.setEnabled(false);
        } else if (LibaoFragment.LIBAO_CLOSEPAGE.equals(reuse.getType())) {
            mBinding.libaoAppbar.setVisibility(View.VISIBLE);
            mBinding.libaoRefresh.setEnabled(true);
        } else if (OPEN_LIBAO_APPBAR.equals(reuse.getType()) && !mIsTouchScreen) {
            mBinding.libaoAppbar.setExpanded(true, true);
        }
    }

    public void onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mIsTouchScreen = true;
                break;
            case MotionEvent.ACTION_UP:
                mIsTouchScreen = false;
                break;
        }
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.setRootBackgroundColor(mBinding.getRoot(), R.color.background_white);
        ExtensionsKt.setRootBackgroundColor(mBinding.searchBar.getRoot(), R.color.background_white);
        mBinding.searchBar.searchBackground.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.actionbar_search_bg));
        mBinding.searchBar.etSearch.setHintTextColor(ContextCompat.getColor(requireContext(), R.color.text_body));
        mBinding.searchBar.etSearch.setTextColor(ContextCompat.getColor(requireContext(), R.color.text_title));
        mBinding.searchBar.searchIv.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.toolbar_search_icon));
        mBinding.searchBar.tvBack.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_search_bar_clear));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            mBinding.searchBar.etSearch.setTextCursorDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.cursor_color));
        }
    }
}
