package com.yidianling.tests.search

import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import cn.lankton.flowlayout.FlowLayout
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.router.RouterManager
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 de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.tests_activity_test_search.*
import kotlinx.android.synthetic.main.tests_item_hot_search.view.*


class TestSearchActivity : BaseMvpActivity<TestSearchView, TestSearchPresenter>(), TestSearchView, View.OnClickListener {
    private var isFirstLoad = true

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

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

    override fun initDataAndEvent() {
        init()
    }

    companion object {
        fun start(context: Context) {
            context.startActivity(Intent(context, TestSearchActivity::class.java))
        }
    }

    private var keyword: String? = null
    private val searchedTestList: MutableList<Test> = ArrayList()
    private val hotSearchedTestList: MutableList<Test> = ArrayList()

    private var searchAdapter: TestListRecyclerAdapter? = null
    private var hotSearchAdapter: TestListRecyclerAdapter? = null
    private var isSearch = false

    private var searchListCurrentPage = 1

    private var onRecommendSearchListResponseFinish = false
    private var onHotRecommendResponseFinish = false

    private fun init() {
        EventBus.getDefault().register(this)
        setupListeners()
        initRecyclerView()
        initData()
    }

    fun initData() {
        var lastCouponMoney = SharedPreferencesEditor.getString(TestHomeUtils.TEST_MAX_COUPON_MONEY_SP_KEY)
        if (!TextUtils.isEmpty(lastCouponMoney)) {
            searchAdapter?.couponMoney = lastCouponMoney
            hotSearchAdapter?.couponMoney = lastCouponMoney
        }
        mPresenter.fetchHotTests()
        mPresenter.hotRecommendRequest()
    }

    private lateinit var onScrollListener: EndlessRecyclerViewScrollListener

    private var headerHotSearch: LinearLayout? = null
    private var searchHeader: View? = null

    private var flHotSearch: FlowLayout? = null
    private var tvSearchHint: TextView? = null

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

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

        hotSearchAdapter?.onItemClickListener = MyBaseAdapter.OnItemClickListener { _, _, data ->
            RouterManager.getTestsRouter()?.testDetailH5(data.id.toString())
        }

        headerHotSearch = View.inflate(this, R.layout.tests_header_hot_search, null) as LinearLayout?;
        searchHeader = View.inflate(this, R.layout.tests_header_search_list, null);

        tvSearchHint = searchHeader?.findViewById(R.id.tv_search_hint);
        flHotSearch = headerHotSearch?.findViewById(R.id.flHotSearch)

        searchHeader?.let { searchAdapter?.setHeaderView(it) }
        headerHotSearch?.let { hotSearchAdapter?.setHeaderView(it) }

        rv_search_list.adapter = searchAdapter
        rv_hot_list.adapter = hotSearchAdapter

        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        val hotLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        rv_search_list.layoutManager = layoutManager
        rv_hot_list.layoutManager = hotLayoutManager


        onScrollListener = object : EndlessRecyclerViewScrollListener(layoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                if (isSearch) {
                    mPresenter.searchTests(keyword, searchListCurrentPage)
                }
            }
        }
        rv_hot_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (!isFirstLoad) {
                    hideSoftInput()
                }
            }
        })
        rv_search_list.addOnScrollListener(onScrollListener)
    }

    private fun setupListeners() {
        tvBack.setOnClickListener(this)
        etSearch.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())) {
                    setSearchListVisibility(false)
                    isSearch = false
                    hideNoResultView()
                }
            }
        })
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                doSearch()
            }
            true
        }

    }

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

    private fun doSearch() {
        keyword = etSearch.text.toString()
        if (TextUtils.isEmpty(keyword)) {
            ToastUtil.toastShort(getString(R.string.tests_no_search_keyword_hint))
            return
        }
        hideSoftInput()
        isSearch = true
        searchListCurrentPage = 1
        onScrollListener.resetState()
        mPresenter.searchTests(keyword, searchListCurrentPage)
    }

    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 onHotRecommendResponse(datalist: List<Test>) {
        rv_hot_list.adapter = hotSearchAdapter
        hotSearchedTestList.clear()

        onHotRecommendResponseFinish = true
        hideRefreshView()
        setSearchListVisibility(false)
        if (datalist.isNotEmpty()) {
            hotSearchAdapter?.hasMore = false
            hotSearchedTestList.addAll(datalist)
            hotSearchAdapter?.notifyDataSetChanged()
        }

        rv_hot_list.postDelayed({
            isFirstLoad = false
        }, 500)
    }

    /**
     * 热门搜索
     */
    override fun onRecommendSearchListResponse(keywordData: List<RecommendSearchItemBean>) {
        if (keywordData.isEmpty()) {
            headerHotSearch?.visibility = View.GONE
            return
        }

        onRecommendSearchListResponseFinish = true
        hideRefreshView()
        setSearchListVisibility(false)

        headerHotSearch?.visibility = View.VISIBLE
        flHotSearch?.removeAllViews()
        for (index in keywordData.indices) {
            val view = LayoutInflater.from(this).inflate(R.layout.tests_item_recommend_hot_search, flHotSearch, false)
            view.tvHotSearch.text = keywordData[index].keyWord
            view.setOnClickListener {
                etSearch.setText(keywordData[index].keyWord)
                doSearch()
            }

            flHotSearch?.addView(view)
        }
    }

    /**
     * 搜索结果
     */
    override fun showSearchResultView(testList: List<Test>?, page: Int) {
        if (page == 1) {
            rv_search_list.adapter = searchAdapter
            onScrollListener.resetState()
            searchedTestList.clear()
        }
        if (testList != null && testList.isNotEmpty()) {
            searchedTestList.addAll(testList)
            searchAdapter?.notifyDataSetChanged()
        } else {
            searchAdapter?.hasMore = false
            searchAdapter?.notifyDataSetChanged()
        }
        tvSearchHint?.text = String.format("为您找到以下跟“%s”有关的内容", keyword)
        setSearchListVisibility(true)
        searchListCurrentPage++
    }


    fun setSearchListVisibility(visibility: Boolean) {
        rv_search_list.visibility = if (visibility) View.VISIBLE else View.GONE
        rv_hot_list.visibility = if (visibility) View.GONE else View.VISIBLE
    }

    override fun createPresenter(): TestSearchPresenter = TestSearchPresenter()

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


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


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


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

    override fun showNoResultView() {
        llEmpty.visibility = View.VISIBLE
        iv_empty.visibility = View.VISIBLE
        tv_search_empty.text = "没有搜到相关信息，换个关键词看看吧"
        tv_search_empty.gravity = Gravity.CENTER_HORIZONTAL
    }

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

    /**
     * 更新优惠券信息
     * 刷新列表
     */
    fun onEvent(updateCouponMoneyEvent: UpdateCouponMoneyEvent) {
        searchAdapter?.couponMoney = updateCouponMoneyEvent.money
        searchAdapter?.notifyDataSetChanged()
        hotSearchAdapter?.couponMoney = updateCouponMoneyEvent.money
        hotSearchAdapter?.notifyDataSetChanged()
    }

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

    private fun hideRefreshView() {
        if (onRecommendSearchListResponseFinish && onHotRecommendResponseFinish) {
            hideLoadingView()
        }
    }
}
