package com.gh.gamecenter.qa.editor

import android.os.Bundle
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.constant.Config
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.view.FixLinearLayoutManager
import com.gh.gamecenter.common.view.VerticalItemDecoration
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.entity.EditorInsertDefaultEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Util_System_Keyboard
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

open class GameFragment : ListFragment<GameEntity, NormalListViewModel<GameEntity>>() {
    var searchEt: EditText? = null
    var searchTv: TextView? = null
    var searchBack: View? = null
    var noneText: TextView? = null
    var defaultListContainer: View? = null
    var defaultList: RecyclerView? = null

    protected var mAdapter: GameAdapter? = null

    protected var mSearchKey: String = ""
    protected var mLastSearchKey: String = ""

    override fun handleMessage(msg: Message) {
        if (msg.what == 1) {
            if (mSearchKey.isEmpty()) {
                clearPage()
            } else {
                search()
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_editor_insert_game
    }

    override fun isAutomaticLoad(): Boolean {
        return false
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration? {
        return VerticalItemDecoration(requireContext(), 8f, false)
    }

    private fun findView() {
        searchEt = mCachedView.findViewById(R.id.search_input)
        searchTv = mCachedView.findViewById(R.id.search_button)
        searchBack = mCachedView.findViewById(R.id.search_back)
        noneText = mCachedView.findViewById(R.id.reuseNoneDataTv)
        defaultList = mCachedView.findViewById(R.id.default_list)
        defaultListContainer = mCachedView.findViewById(R.id.default_list_container)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        findView()
        val title = arguments?.getString(EntranceConsts.KEY_NAVIGATION_TITLE) ?: ""
        if (title.isNotEmpty()) {
            setNavigationTitle(title)
        }
        noneText?.text = "搜索结果为空"
        mListLoading?.visibility = View.GONE
        mListRefresh?.isEnabled = false

        searchEt?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                Util_System_Keyboard.hideSoftKeyboard(requireActivity())
                search()
            }
            false
        }

        searchTv?.setOnClickListener {
            search()
            Util_System_Keyboard.hideSoftKeyboard(requireActivity())
        }
        searchBack?.setOnClickListener {
            searchEt?.setText("")
            clearPage()
        }

        searchEt?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable) {
                val newSearchKey = s.toString().trim()
                if (newSearchKey != mSearchKey) {
                    mBaseHandler.removeMessages(1)
                    mSearchKey = newSearchKey
                    if (isAutoSearch()) {
                        mBaseHandler.sendEmptyMessageDelayed(1, 500)
                    } else {
                        if (mSearchKey.isEmpty()) {
                            clearPage()
                        }
                    }
                }
                searchBack?.visibility = if (newSearchKey.isNotEmpty()) View.VISIBLE else View.GONE
            }
        })

//        mListRv.clearOnScrollListeners()

        // default open soft keyboard
        if (isAutoShowKeyboard()) {
            searchEt?.requestFocus()
        }
        Util_System_Keyboard.showSoftKeyboard(requireActivity(), searchEt)

        if (title == GameActivity.SELECT_GAME_TITLE) initDefaultData()
    }

    protected fun clearPage() {
        mLastSearchKey = ""
        mAdapter?.setListData(ArrayList())
        mListLoading?.visibility = View.GONE
        mReuseNoData?.visibility = View.GONE
        mReuseNoConn?.visibility = View.GONE
        mListRv.visibility = View.GONE
    }

    fun search() {
        if (mSearchKey.isEmpty()) {
            toast("请输入搜索关键字")
        } else {
            if (mLastSearchKey != mSearchKey) {
                mLastSearchKey = mSearchKey
                clearPage()
                onLoadRefresh()
            }
        }
    }

    override fun provideListAdapter(): GameAdapter? {
        if (mAdapter == null) {
            mAdapter = GameAdapter(requireContext())
        }
        return mAdapter
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<GameEntity>>? {
        return RetrofitManager
            .getInstance().api
            .getSearchGame(Config.API_HOST + "games:search?keyword=" + searchEt?.text + "&view=digest" + "&channel=" + HaloApp.getInstance().channel + "&version=" + BuildConfig.VERSION_NAME)
    }

    override fun provideListViewModel(): NormalListViewModel<GameEntity> {
        val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
        return ViewModelProviders.of(this, factory)
            .get(NormalListViewModel::class.java) as NormalListViewModel<GameEntity>
    }

    private fun initDefaultData() {
        RetrofitManager.getInstance().api
            .getEditorInsertDefaultData(UserManager.getInstance().userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<EditorInsertDefaultEntity>>() {
                override fun onResponse(response: List<EditorInsertDefaultEntity>?) {
                    if (response == null || response.isEmpty()) return
                    // init default page
                    defaultList?.layoutManager = FixLinearLayoutManager(requireContext())
                    defaultList?.adapter = GameDefaultAdapter(requireContext(), response)
                    defaultListContainer?.visibility = View.VISIBLE
                }
            })
    }

    override fun onLoadRefresh() {
        super.onLoadRefresh()
        mListRv.visibility = View.VISIBLE
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        mListRv.visibility = View.VISIBLE
    }

    override fun onLoadDone() {
        super.onLoadDone()
        mListRv.visibility = View.VISIBLE
    }

    open fun isAutoShowKeyboard(): Boolean = true

    override fun shouldLoadMore(): Boolean = false

    open fun isAutoSearch(): Boolean = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if ((mListRv?.itemDecorationCount ?: 0) > 0) {
            mListRv?.removeItemDecorationAt(0)
            itemDecoration?.let {
                mListRv?.addItemDecoration(it)
            }
        }
    }
}