package com.gh.gamecenter.gamedetail.cloudarchive

import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.os.bundleOf
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.catalog.SpecialCatalogFragment
import com.gh.gamecenter.cloudarchive.CloudArchiveManagerActivity
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toResString
import com.gh.gamecenter.databinding.FragmentCloudArchiveBinding
import com.gh.gamecenter.entity.GameEntity

class CloudArchiveFragment : LazyFragment() {

    private var mGameEntity: GameEntity? = null
    private var mBinding: FragmentCloudArchiveBinding? = null
    private var mSearchFragment: CloudArchiveListFragment? = null
    private var mNormalFragment: CloudArchiveListFragment? = null
    private var mIsSearch = false
    private var mOrderList =
        listOf(CloudArchiveListViewModel.SortType.NEWEST, CloudArchiveListViewModel.SortType.HOTTEST)

    override fun getRealLayoutId() = R.layout.fragment_cloud_archive

    override fun onRealLayoutInflated(inflatedView: View) {
        mBinding = FragmentCloudArchiveBinding.bind(inflatedView)
    }

    override fun onFragmentFirstVisible() {
        mGameEntity = arguments?.getParcelable(EntranceConsts.KEY_GAME)
        super.onFragmentFirstVisible()
        changeContentFragment()
    }

    override fun inflateRealView() {
        super.inflateRealView()
        mBinding?.run {
            searchBar.etSearch.hint = R.string.game_detail_cloud_archive_search_hint.toResString()
            orderSfv.setItemList(mOrderList.map { it.value }, 1)
            orderSfv.setOnCheckedCallback {
                if (mIsSearch) {
                    mSearchFragment?.updateSortType(mOrderList[it])
                } else {
                    mNormalFragment?.updateSortType(mOrderList[it])
                }
            }
            searchBar.etSearch.setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchBar.tvSearch.performClick()
                }
                false
            }
            searchBar.tvSearch.setOnClickListener {
                val keyWord = searchBar.etSearch.text.toString().trim { it <= ' ' }
                if (keyWord.isBlank()) {
                    toast(R.string.search_hint)
                } else {
                    changeSearchStatus(true)
                }
            }
            searchBar.tvBack.setOnClickListener {
                changeSearchStatus(false)
                searchBar.etSearch.setText("")
            }
            archiveManageTv.setOnClickListener {
                startActivity(
                    CloudArchiveManagerActivity.getIntent(
                        requireContext(),
                        mGameEntity ?: GameEntity(),
                        arguments?.getString(EntranceConsts.KEY_ARCHIVE_CONFIG_URL) ?: "",
                        "游戏详情页"
                    )
                )
            }
        }
    }

    private fun changeContentFragment() {
        if (mIsSearch) {
            mSearchFragment =
                childFragmentManager.findFragmentByTag("${CloudArchiveListFragment::class.java.name}_search")
                        as? CloudArchiveListFragment ?: CloudArchiveListFragment()
            alterFragment(mSearchFragment!!)
        } else {
            mNormalFragment =
                childFragmentManager.findFragmentByTag("${CloudArchiveListFragment::class.java.name}_normal")
                        as? CloudArchiveListFragment ?: CloudArchiveListFragment()
            alterFragment(mNormalFragment!!)
        }
    }

    private fun alterFragment(fragment: CloudArchiveListFragment) {
        val bundle = bundleOf(
            EntranceConsts.KEY_GAME to (mGameEntity ?: GameEntity())
        )
        if (mIsSearch) {
            val keyWord = mBinding?.searchBar?.etSearch?.text?.toString()?.trim { it <= ' ' }
            bundle.putString(EntranceConsts.KEY_SEARCHKEY, keyWord)
            NewFlatLogUtils.logCloudArchiveSearchKeyUpload(
                mGameEntity?.id ?: "",
                mGameEntity?.name ?: "",
                keyWord ?: ""
            )
        }
        fragment.arguments = bundle
        childFragmentManager
            .beginTransaction()
            .replace(
                R.id.contentFragment,
                fragment,
                SpecialCatalogFragment::class.java.name
            )
            .commitAllowingStateLoss()
    }

    private fun changeSearchStatus(isSearch: Boolean) {
        when {
            mIsSearch != isSearch -> {
                mIsSearch = isSearch
                mBinding?.searchBar?.tvBack?.goneIf(!mIsSearch)
                changeContentFragment()
            }
            mIsSearch -> {
                val keyWord = mBinding?.searchBar?.etSearch?.text?.toString()?.trim { it <= ' ' } ?: ""
                NewFlatLogUtils.logCloudArchiveSearchKeyUpload(mGameEntity?.id ?: "", mGameEntity?.name ?: "", keyWord)
                mSearchFragment?.updateSearchKeyWord(keyWord)
            }
        }
    }
}