package com.gh.gamecenter.feedback.view.qa

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.doAfterTextChanged
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.TextHelper
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.databinding.ActivityQaSearchBinding
import com.lightgame.utils.Util_System_Keyboard

/**
 * QA搜索页
 */
class QaSearchActivity : BaseActivity() {

    private lateinit var mBinding: ActivityQaSearchBinding
    private var mDefaultFragment: Fragment? = null
    private var mSearchFragment: Fragment? = null

    override fun getLayoutId(): Int = R.layout.activity_qa_search

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityQaSearchBinding.bind(mContentView)
        changeFragment(true)
        initSearchBar()
    }

    private fun initSearchBar() {
        mBinding.searchToolbar.run {
            // 进入获取焦点
            searchEt.post {
                searchEt.requestFocus()
            }
            searchEt.hint = "输入问题关键词"

            searchEt.setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Util_System_Keyboard.hideSoftKeyboard(this@QaSearchActivity)
                    search(true)
                }
                false
            }

            searchBtn.setOnClickListener {
                Util_System_Keyboard.hideSoftKeyboard(this@QaSearchActivity)
                search(true)
            }

            deleteIv.setOnClickListener {
                deleteIv.visibility = View.GONE
                searchEt.setText("")
            }

            searchEt.doOnTextChanged { text, _, _, _ -> deleteIv.goneIf(text?.length == 0) }
            searchEt.doAfterTextChanged { editable ->
                changeFragment(editable.isNullOrEmpty())
            }
            searchEt.filters = arrayOf(TextHelper.getFilter(50, "最多输入50个字"))

            backBtn.setOnClickListener { onBackPressed() }
        }
    }

    private fun search(isManual: Boolean = false) {
        val searchKey = mBinding.searchToolbar.searchEt.text.toString()
        if (searchKey.isEmpty() && isManual) {
            toast("请输入搜索内容")
        }
        if (searchKey.isNotEmpty() && mSearchFragment is HelpContentFragment) {
            (mSearchFragment as HelpContentFragment).updateSearchKey(searchKey)
        }
    }

    private fun changeFragment(default: Boolean) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        if (default) {
            mDefaultFragment = alterFragment(transaction, HelpQaDefaultFragment::class.java, default)
        } else {
            mSearchFragment = alterFragment(transaction, HelpContentFragment::class.java, default)
            val bundle = mSearchFragment?.arguments ?: Bundle()
            bundle.putString(EntranceConsts.KEY_LOCATION, "帮助与反馈")
            bundle.putString(EntranceConsts.KEY_SEARCH_TYPE, "自动搜索")
            mSearchFragment?.arguments = bundle
        }
        transaction.commitAllowingStateLoss()
    }

    private fun <T : Fragment> alterFragment(transaction: FragmentTransaction, cls: Class<T>, default: Boolean): T {
        val tag = cls.simpleName
        var fragmentByTag = supportFragmentManager.findFragmentByTag(tag) as T?
        try {
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag)
                search()
            } else {
                fragmentByTag = cls.newInstance()
                if (!default) {
                    val bundle = Bundle()
                    bundle.putString(EntranceConsts.KEY_SEARCHKEY, mBinding.searchToolbar.searchEt.text.toString())
                    fragmentByTag.arguments = bundle
                }
                transaction.add(R.id.container, fragmentByTag, tag)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return fragmentByTag!!
    }

    companion object {
        fun getIntent(context: Context): Intent {
            val intent = Intent(context, QaSearchActivity::class.java)

            return intent
        }
    }
}