package com.gh.gamecenter.feedback.view.help

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBNetworkState
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.TextHelper
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.feedback.HaloApp
import com.gh.gamecenter.floatingwindow.R
import com.gh.gamecenter.floatingwindow.databinding.FragmentHelpContaierBinding
import com.lightgame.utils.Util_System_Keyboard
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 该页面会根据来源自动切换数据源
 * 1.帮助反馈-使用帮助(默认，qaCollectionId/qaId 均不存在时)
 * 2.Q&A合集(qaCollectionId 存在时)
 * 3.Q&A(qaId 存在时)
 */
class HelpContainerFragment : LazyFragment() {

    private lateinit var mBinding: FragmentHelpContaierBinding

    private lateinit var mViewModel: HelpContainerViewModel

    private lateinit var mDefaultContentFragment: HelpQaCategoryFragment
    private var mSearchContentFragment: HelpContentFragment? = null

    private var mNavigationTitle = ""

    override fun getRealLayoutId(): Int {
        return R.layout.fragment_help_contaier
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mNavigationTitle = arguments?.getString(EntranceConsts.KEY_NAVIGATION_TITLE) ?: ""
        if (mNavigationTitle.isNotEmpty()) setNavigationTitle(mNavigationTitle)

        val qaCollectionId = arguments?.getString(EntranceConsts.KEY_QA_COLLECTION_ID)
        val qaId = arguments?.getString(EntranceConsts.KEY_QA_ID)
        val factory = HelpContainerViewModel.Factory(HaloApp.getInstance(), qaId, qaCollectionId)
        mViewModel = ViewModelProviders.of(this, factory).get(HelpContainerViewModel::class.java)

        mViewModel.configLiveData.observe(this, Observer {
            if (it == null) {
                mBinding.includeNoneData.root.visibility = View.GONE
                mBinding.includeNoConnection.root.visibility = View.VISIBLE
                mBinding.content.visibility = View.GONE
            } else if (it.first == true) {
                mBinding.searchBar.visibility = if (it.second == true) {
                    View.VISIBLE
                } else View.GONE

                mBinding.includeNoConnection.root.visibility = View.GONE
                mBinding.includeNoneData.root.visibility = View.GONE
                mBinding.content.visibility = View.VISIBLE
            } else {
                mBinding.includeNoneData.root.visibility = View.VISIBLE
                mBinding.includeNoConnection.root.visibility = View.GONE
                mBinding.content.visibility = View.GONE
                mBinding.includeNoneData.root.findViewById<TextView>(R.id.reuseNoneDataTv)
                    .setText(R.string.content_delete_hint)
                toast(R.string.comment_failed_unable)
            }
        })
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)

        val qaId = arguments?.getString(EntranceConsts.KEY_QA_ID)

        mBinding = FragmentHelpContaierBinding.bind(inflatedView)
        if (!qaId.isNullOrEmpty()) {
            changeFragment(default = false)
        } else {
            changeFragment(default = true)
        }

        mBinding.searchInput.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s.isNullOrEmpty()) {
                    if (!qaId.isNullOrEmpty()) {
                        if (mSearchContentFragment != null) {
                            mSearchContentFragment?.updateSearchKey("")
                        }
                    } else {
                        changeFragment(default = true)
                    }
                    mBinding.deleteButton.visibility = View.GONE
                } else {
                    mBinding.deleteButton.visibility = View.VISIBLE
                }
            }
        })
        mBinding.searchInput.filters = arrayOf(TextHelper.getFilter(50, "最多输入50个字"))
        mBinding.searchButton.setOnClickListener {
            search()
        }
        mBinding.deleteButton.setOnClickListener {
            mBinding.searchInput.setText("")
        }
        mBinding.searchInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search()
            }
            false
        }
        mBinding.includeNoConnection.root.setOnClickListener {
            mBinding.content.visibility = View.VISIBLE
            mBinding.includeNoConnection.root.visibility = View.GONE
            mViewModel.initData()
        }
    }

    fun search() {
        val key = mBinding.searchInput.text.toString()
        if (key.isEmpty()) {
            toast("请输入关键词搜索")
        } else {
            if (mSearchContentFragment != null) {
                mSearchContentFragment?.updateSearchKey(key)
            }
            changeFragment(default = false)
            Util_System_Keyboard.hideSoftKeyboard(activity)
            if (!mViewModel.qaId.isNullOrEmpty()) {
                MtaHelper.onEvent("QA", "QA搜索", "$mNavigationTitle+$key")
            } else if (!mViewModel.qaCollectionId.isNullOrEmpty()) {
                MtaHelper.onEvent("QA", "QA合集搜索", "$mNavigationTitle+$key")
                //MtaHelper.onEvent("QA", "QA合集搜索结果", key)
            } else {
                MtaHelper.onEvent("意见反馈", "使用帮助搜索", key)
                //MtaHelper.onEvent("意见反馈", "使用帮助搜索结果", key)
            }

        }
        if (!mViewModel.qaId.isNullOrEmpty()) {
            MtaHelper.onEvent("QA", "QA点击", "点击搜索")
        } else if (!mViewModel.qaCollectionId.isNullOrEmpty()) {
            MtaHelper.onEvent("QA", "QA合集点击", "点击搜索")
        } else {
            MtaHelper.onEvent("意见反馈", "使用帮助点击", "点击搜索")
        }
    }

    private fun changeFragment(default: Boolean) {
        val transaction = childFragmentManager.beginTransaction()
        hideFragments(transaction)
        if (default) {
            mDefaultContentFragment = alterFragment(transaction, HelpQaCategoryFragment::class.java, default)
        } else {
            mSearchContentFragment = alterFragment(transaction, HelpContentFragment::class.java, default)
        }

        transaction.commitAllowingStateLoss()
    }

    private fun <T : Fragment> alterFragment(transaction: FragmentTransaction, cls: Class<T>, default: Boolean): T {
        val tag = cls.simpleName + "" + default
        var fragmentByTag = childFragmentManager.findFragmentByTag(tag) as T?
        try {
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag)
            } else {
                fragmentByTag = cls.newInstance()
                val bundle = Bundle()
                bundle.putString(EntranceConsts.KEY_QA_ID, mViewModel.qaId)
                bundle.putString(EntranceConsts.KEY_QA_COLLECTION_ID, mViewModel.qaCollectionId)
                if (!default) {
                    bundle.putString(EntranceConsts.KEY_SEARCHKEY, mBinding.searchInput.text.toString())
                    bundle.putString(EntranceConsts.KEY_NAVIGATION_TITLE, mNavigationTitle)
                }
                fragmentByTag.arguments = bundle
                transaction.add(R.id.content_container, fragmentByTag, tag)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return fragmentByTag!!
    }


    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busNetworkState: EBNetworkState) {
        if (busNetworkState.isNetworkConnected
            && (mViewModel.categoryLiveData.value?.status == Status.ERROR || mViewModel.configLiveData.value == null)
        ) {
            mViewModel.initData()
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.searchInput.run {
            post {
                setHintTextColor(R.color.text_body.toColor(requireContext()))
                setTextColor(R.color.text_title.toColor(requireContext()))
            }
        }
    }
}