package com.gh.gamecenter.qa.questions.invite;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.R;
import com.gh.gamecenter.databinding.FragmentInviteBinding;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity;
import com.lightgame.utils.Util_System_Keyboard;
import com.lightgame.utils.Utils;

/**
 * Created by khy on 22/03/18.
 */

public class QuestionsInviteWrapperFragment extends ToolbarFragment {

    private FragmentInviteBinding mBinding;

    private final static String INVITE_SEARCH_TAG = "INVITE_SEARCH_TAG";
    private final static String INVITE_NORMAL_TAG = "INVITE_NORMAL_TAG";

    private QuestionsDetailEntity mQuestionsDetailEntity;

    private boolean mIsSearch;

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

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
    }

    @Override
    public void onMenuItemClick(MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.menu_invite_share) {
            // 第三方邀请（QQ/微信/微博）
            String shareIcon;
            if (mQuestionsDetailEntity.getImages().size() > 0) {
                shareIcon = mQuestionsDetailEntity.getImages().get(0);
            } else {
                shareIcon = getString(R.string.share_ghzs_logo);
            }
            String userName;
            if (UserManager.getInstance().getUserInfoEntity() != null) {
                userName = UserManager.getInstance().getUserInfoEntity().getName();
            } else {
                userName = "我";
            }

            String description = mQuestionsDetailEntity.getDescription();
            if (TextUtils.isEmpty(description)) {
                description = getString(R.string.ask_share_default_summary);
            }
            ShareUtils.getInstance(getContext()).showShareWindows(getActivity(), new View(getContext())
                    , getString(R.string.share_invite_url, mQuestionsDetailEntity.getId(), UserManager.getInstance().getUserId())
                    , shareIcon, getString(R.string.ask_share_invite_title, userName, mQuestionsDetailEntity.getTitle())
                    , description, ShareUtils.ShareEntrance.askInvite, mQuestionsDetailEntity.getId());
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setNavigationTitle("邀请回答");
        initMenu(R.menu.menu_question_invite);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = FragmentInviteBinding.bind(mCachedView);
        mBinding.searchBack.setOnClickListener(this);
        mBinding.searchButton.setOnClickListener(this);
        mQuestionsDetailEntity = getArguments().getParcelable(QuestionsDetailEntity.class.getSimpleName());
        changeFragment();

        mBinding.inviteAppbar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            int totalScrollRange = appBarLayout.getTotalScrollRange();
            if (totalScrollRange == -verticalOffset) {
                Util_System_Keyboard.hideSoftKeyboard(getActivity());
            }
        });

        mBinding.searchInput.setHint("搜索光环用户");

        TextHelper.limitTheLengthOfEditText(mBinding.searchInput, 12, () -> Utils.toast(mBinding.searchInput.getContext(), "最多输入12个字"));

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

    private void changeFragment() {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        hideFragments(transaction);
        if (mIsSearch) {
            alterFragment(transaction, QuestionsInviteFragment.class, INVITE_SEARCH_TAG);
        } else {
            alterFragment(transaction, QuestionsInviteFragment.class, INVITE_NORMAL_TAG);
        }

        transaction.commitAllowingStateLoss();
    }

    private <T extends Fragment> T alterFragment(FragmentTransaction transaction, Class<T> cls, String tag) {
        T fragmentByTag = (T) getChildFragmentManager().findFragmentByTag(tag);
        try {
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag);
                if (fragmentByTag instanceof QuestionsInviteFragment && INVITE_SEARCH_TAG.equals(tag)) {
                    ((QuestionsInviteFragment) fragmentByTag).search();
                }
            } else {
                Bundle args = getArguments();
                if (INVITE_SEARCH_TAG.equals(tag)) {
                    args.putString(EntranceConsts.KEY_INVITE_SEARCH_KEY, getSearchKey());
                }
                fragmentByTag = cls.newInstance();
                fragmentByTag.setArguments(args);
                transaction.add(R.id.layout_fragment_content, fragmentByTag, tag);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fragmentByTag;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.search_back:
                mBinding.searchInput.setText("");
                mIsSearch = false;
                break;
            case R.id.search_button:
                String key = mBinding.searchInput.getText().toString();
                if (TextUtils.isEmpty(key)) {
                    toast(R.string.search_hint);
                    return;
                } else if (!mIsSearch) {
                    mIsSearch = true;
                }
                break;
        }
        if (mIsSearch) {
            mBinding.searchBack.setVisibility(View.VISIBLE);
        } else {
            mBinding.searchBack.setVisibility(View.GONE);
        }
        Util_System_Keyboard.hideSoftKeyboard(getActivity());
        changeFragment();
    }

    public String getSearchKey() {
        return mBinding.searchInput.getText().toString();
    }

}
