package com.yidianling.tests.search

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.ydl.ydlcommon.adapter.MyBaseAdapter
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.view.listener.EndlessRecyclerViewScrollListener
import com.yidianling.common.tools.ToastUtil
import com.yidianling.tests.R
import com.yidianling.tests.home.event.UpdateCouponMoneyEvent
import com.yidianling.tests.home.utils.TestHomeUtils
import com.yidianling.tests.list.model.bean.RecommendSearchItemBean
import com.yidianling.tests.list.model.bean.Test
import com.yidianling.tests.list.view.adapter.TestListRecyclerAdapter
import com.yidianling.tests.router.TestsIn
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.tests_activity_test_key_search.*

class TestSearchKeyActivity : BaseMvpActivity<TestSearchView, TestSearchPresenter>(),
    TestSearchView, View.OnClickListener {

    private var keyWord: String? = ""

    private var searchListCurrentAllPage = 1
    private var searchListCurrentPastPage = 1
    private var searchListCurrentFreePage = 1

    private val TYPE_ALL = "all"
    private val TYPE_PAST = "past"
    private val TYPE_FREE = "free"

    private lateinit var onScrollListener: EndlessRecyclerViewScrollListener


    private var currentSelectedPage = TYPE_ALL

    var title = arrayOf("全部", "付费", "免费")

    private var searchAdapter: TestListRecyclerAdapter? = null

    private val searchedTestList: MutableList<Test> = ArrayList()

    override fun createPresenter(): TestSearchPresenter = TestSearchPresenter()

    override fun layoutResId(): Int {
        return R.layout.tests_activity_test_key_search
    }


    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true, statusBarDarkMode = true)
    }

    override fun initDataAndEvent() {
        EventBus.getDefault().register(this)
        this.keyWord = intent.getStringExtra("keyword")
        setupListeners()
        initView()
        initRecyclerView()
        tv_search_key_empty?.text = String.format("为您找到以下跟“%s”有关的内容", keyWord)
        etKeySearch?.setText(keyWord)
    }

    private fun initView() {
        for (i in title) {
            val tab = tabLayout.newTab().setText(i);
            tabLayout.addTab(tab)
        }
    }

    private fun initRecyclerView() {
        swipe_refresh_layout_key.isEnabled = false
        searchAdapter = TestListRecyclerAdapter(
            this,
            searchedTestList,
            TestListRecyclerAdapter.PAGE_TYPE_SEARCH
        )

        var lastCouponMoney =
            SharedPreferencesEditor.getString(TestHomeUtils.TEST_MAX_COUPON_MONEY_SP_KEY)
        if (!TextUtils.isEmpty(lastCouponMoney)) {
            searchAdapter?.couponMoney = lastCouponMoney
        }

        searchAdapter?.onItemClickListener = MyBaseAdapter.OnItemClickListener { _, _, data ->
            TestsIn.getTestsImpl().testDetailH5(data.id.toString())
        }

        rv_search_key_list.adapter = searchAdapter
        val layoutManager = LinearLayoutManager(
            this,
            LinearLayoutManager.VERTICAL,
            false
        )
        rv_search_key_list.layoutManager = layoutManager


        onScrollListener = object : EndlessRecyclerViewScrollListener(layoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                when (currentSelectedPage) {
                    TYPE_ALL -> {
                        mPresenter.searchTests(keyWord, searchListCurrentAllPage, 0)
                    }

                    TYPE_PAST -> {
                        mPresenter.searchTests(keyWord, searchListCurrentPastPage, 1)
                    }

                    TYPE_FREE -> {
                        mPresenter.searchTests(keyWord, searchListCurrentFreePage, 2)
                    }
                }
            }
        }

        rv_search_key_list.addOnScrollListener(onScrollListener)

    }

    private fun setupListeners() {
        tvKeyBack.setOnClickListener(this)
        etKeySearch.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 (TextUtils.isEmpty(s.toString())) {
                }
            }
        })
        etKeySearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                this.keyWord = etKeySearch.text.toString()
                tv_search_key_empty?.text = String.format("为您找到以下跟“%s”有关的内容", keyWord)
                if (TextUtils.isEmpty(keyWord)) {
                    ToastUtil.toastShort(getString(R.string.tests_no_search_keyword_hint))
                } else {
                    doSearch(keyWord)
                }
            }
            true
        }

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                when (tab?.text.toString()) {
                    "全部" -> {
                        currentSelectedPage = TYPE_ALL
                        searchListCurrentAllPage = 1
                        mPresenter.searchTests(keyWord, searchListCurrentAllPage, 0)
                    }

                    "付费" -> {
                        currentSelectedPage = TYPE_PAST
                        searchListCurrentPastPage = 1
                        mPresenter.searchTests(keyWord, searchListCurrentPastPage, 1)
                    }

                    "免费" -> {
                        currentSelectedPage = TYPE_FREE
                        searchListCurrentFreePage = 1
                        mPresenter.searchTests(keyWord, searchListCurrentFreePage, 2)
                    }
                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
    }

    fun doSearch(keyword: String?) {
        currentSelectedPage = TYPE_ALL
        searchListCurrentAllPage = 1
        mPresenter.searchTests(keyword, searchListCurrentAllPage, 0)
        tabLayout.getTabAt(0)?.select()

    }

    override fun showLoadingView() {
        swipe_refresh_layout_key.isRefreshing = true
    }

    override fun hideLoadingView() {
        swipe_refresh_layout_key.isRefreshing = false
    }

    override fun showError(msg: String) {
        ToastUtil.toastShort(msg)
    }

    override fun showNoResultView() {
        llKeyEmpty.visibility = View.VISIBLE
        iv_Key_empty.visibility = View.VISIBLE
        tv_text_search_empty.visibility = View.VISIBLE
    }

    override fun hideNoResultView() {
        llKeyEmpty.visibility = View.GONE
    }

    override fun showSearchResultView(testList: List<Test>?, page: Int) {
        hideSoftInput()
        if (page == 1) {
            rv_search_key_list.adapter = searchAdapter
            onScrollListener.resetState()
            searchedTestList.clear()
        }
        if (testList != null && testList.isNotEmpty()) {
            searchedTestList.addAll(testList)
            searchAdapter?.notifyDataSetChanged()
        } else {
            searchAdapter?.hasMore = false
            searchAdapter?.notifyDataSetChanged()
        }

        when (currentSelectedPage) {
            TYPE_ALL -> {
                searchListCurrentAllPage++
            }

            TYPE_PAST -> {
                searchListCurrentPastPage++
            }

            TYPE_FREE -> {
                searchListCurrentFreePage++
            }
        }
    }

    fun hideSoftInput() {
        val view = this.currentFocus
        if (view != null) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    override fun onRecommendSearchListResponse(testList: List<RecommendSearchItemBean>) {

    }

    override fun onHotRecommendResponse(datalist: List<Test>) {

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvKeyBack -> {
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        //每次可见，更新优惠券信息
        TestHomeUtils.updateCouponMoney()
    }

    fun onEvent(updateCouponMoneyEvent: UpdateCouponMoneyEvent) {
        searchAdapter?.couponMoney = updateCouponMoneyEvent.money
        searchAdapter?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}
