package com.yidianling.tests.list.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.flyco.tablayout.CommonTabLayout
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.DisplayUtils
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.tests.R
import com.yidianling.tests.home.utils.TestHomeUtils
import com.yidianling.tests.list.model.bean.CategotyPopItem
import com.yidianling.tests.list.model.bean.TestCategory
import com.yidianling.tests.list.model.bean.TestsRedPacketBean
import com.yidianling.tests.list.model.bean.TrendTabEntity
import com.yidianling.tests.list.presenter.TestListActivityPresenter
import com.yidianling.tests.list.view.adapter.CategoryConditionRecyclerViewAdapter
import com.yidianling.tests.list.view.adapter.TestListPagerAdapter
import com.yidianling.tests.list.view.widget.CategoryPopupWindow
import com.yidianling.tests.router.TestsIn
import com.yidianling.tests.search.TestSearchActivity
import kotlinx.android.synthetic.main.tests_activity_test_category_list.*

@Route(path = "/ceshi/category_list")
class TestCategoryListActivity : BaseMvpActivity<TestListActivityView, TestListActivityPresenter>(),
    TestListActivityView, PopupWindow.OnDismissListener {

    private var isMine: Boolean = false
    private var tabName: String? = null
    private var popMarginLeft: Int = 0

    private var testCategory: MutableList<TestCategory> = ArrayList()
    private var sortList: MutableList<CategotyPopItem> = ArrayList()
    private var filterList: MutableList<CategotyPopItem> = ArrayList()
    private val titleList = java.util.ArrayList<CustomTabEntity>()

    var sortConditionDefaultKey: String = "1"
    var filterConditionDefaultKey: String = "1"

    var selectSortItem: CategotyPopItem = CategotyPopItem("综合排序", sortConditionDefaultKey);
    var selectFilterItem: CategotyPopItem = CategotyPopItem("全部", filterConditionDefaultKey);

    var selectedConditionList: HashMap<Int, HashMap<String, CategotyPopItem>> = HashMap()

    var sortPopup: CategoryPopupWindow? = null;

    var currentPageIndex: Int = 0

    val SELECT_SORT: String = "SELECT_SORT"
    val SELECT_FILTER: String = "SELECT_FILTER"
    private var testCategoryAdapter: TestListPagerAdapter? = null


    companion object {
        private const val EXTRA_IS_MINE = "is_mine"
        private const val EXTRA_TABNAME = "tab"
        private const val payRequestCode = 33

        fun start(context: Context) {
            LogHelper.getInstance().writeLogSync("跳转到测试题")
            val intent = Intent(context, TestCategoryListActivity::class.java)
            context.startActivity(intent)
        }

        fun start(context: Context, isMine: Boolean) {
            LogHelper.getInstance().writeLogSync("跳转到测试题")
            val intent = Intent(context, TestCategoryListActivity::class.java)
            intent.putExtra(EXTRA_IS_MINE, isMine)
            context.startActivity(intent)
        }

        /**
         * 根据所传的tab标签 定位到指定标签下
         */
        fun start(context: Context, tab: String?) {

            LogHelper.getInstance().writeLogSync("跳转到测试题")
            val intent = Intent(context, TestCategoryListActivity::class.java)
            intent.putExtra(EXTRA_TABNAME, tab)
            context.startActivity(intent)
        }
    }

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

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

    override fun initDataAndEvent() {
        initConditionView()
        popMarginLeft = DisplayUtils.dip2px(this, 72F)
        if (null != intent && intent.hasExtra(EXTRA_IS_MINE)) {
            isMine = intent.getBooleanExtra(EXTRA_IS_MINE, false)
        }
        if (null != intent && intent.hasExtra(EXTRA_TABNAME)) {
            tabName = intent.getStringExtra(EXTRA_TABNAME)
        }
        tv_test_search.setOnClickListener {
            TestSearchActivity.start(this)
        }
        iv_test_list_back.setOnClickListener {
            this.finish()
        }

        dr_sort.setOnClickListener {
            showSortPopupWindow()
        }

        titleList.add(TrendTabEntity("全部", 0, 0));
        titleList.add(TrendTabEntity("付费", 0, 0));
        titleList.add(TrendTabEntity("免费", 0, 0));

        tab_tabLayout.setTabData(titleList)

        tab_tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> {
                        selectFilterItem = filterList[0]
                    }

                    1 -> {
                        selectFilterItem = filterList[1]
                    }

                    2 -> {
                        selectFilterItem = filterList[2]
                    }
                }

                onDismiss()
            }

            override fun onTabReselect(position: Int) {}
        })

        mPresenter.fetchTestTypeList()
        vvp_test.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                currentPageIndex = position
                setConditionContent();

                click_category()

                LogUtil.d("page selected: " + testCategory?.get(position)?.name)
                BuryPointUtils.getInstance().createMap()
                    .put("test_type_click", testCategory?.get(position)?.name + "")
                    .burryPoint("Testtype_click")
                if (("my" == testCategory?.get(position)?.tab || "unpay" == testCategory?.get(
                        position
                    )?.tab)
                ) {
                    TestsIn.loginByOneKeyLogin(this@TestCategoryListActivity, true)
                }
            }
        })
        StatusBarUtils.statusBarLightMode(this)

    }

    private fun initConditionView() {
        sortList.add(selectSortItem)
        sortList.add(CategotyPopItem("人气优选", "4"))
        sortList.add(CategotyPopItem("最新上新", "5"))

        filterList.add(selectFilterItem)
        filterList.add(CategotyPopItem("付费", "3"))
        filterList.add(CategotyPopItem("免费", "2"))

        sortPopup = CategoryPopupWindow(this,
            sortList.toList() as ArrayList<CategotyPopItem>,
            object : CategoryConditionRecyclerViewAdapter.OnItemSelectedListener {
                override fun onSortItemSelected(sortItem: CategotyPopItem) {
                    selectSortItem = sortItem
                    if (selectSortItem.key == sortConditionDefaultKey) {
                        updateFilterTextViewStatus(dr_sort, sortItem.value!!, true)
                    } else {
                        updateFilterTextViewStatus(dr_sort, sortItem.value!!, false)
                    }
                    sortPopup?.dismiss()
                }
            })

        sortPopup?.setOnDismissListener(this)

    }

    override fun onDismiss() {
        view_mask.visibility = View.GONE
        updateConditionList()
    }

    private fun setConditionContent() {
        var conditionList = selectedConditionList[currentPageIndex];
        if (conditionList != null && conditionList[SELECT_SORT] != null && conditionList[SELECT_FILTER] != null) {
            selectSortItem = conditionList[SELECT_SORT]!!
            selectFilterItem = conditionList[SELECT_FILTER]!!

            if (selectSortItem.key == sortConditionDefaultKey) {
                updateFilterTextViewStatus(dr_sort, selectSortItem.value!!, true)
            } else {
                updateFilterTextViewStatus(dr_sort, selectSortItem.value!!, false)
            }

            updateTabLayoutStatus(tab_tabLayout, selectFilterItem.value!!)

        } else {
            selectSortItem = CategotyPopItem("综合排序", sortConditionDefaultKey)
            selectFilterItem = CategotyPopItem("全部", filterConditionDefaultKey)

            updateFilterTextViewStatus(dr_sort, selectSortItem.value!!, true)
            updateTabLayoutStatus(tab_tabLayout, selectFilterItem.value!!)
        }

        sortPopup?.adapter?.lastSelectText = selectSortItem.value
        sortPopup?.adapter?.notifyDataSetChanged()
    }

    private fun updateConditionList() {
        var conditionList = selectedConditionList[currentPageIndex];
        if (conditionList == null) {
            conditionList = HashMap();
        }
        conditionList[SELECT_SORT] = selectSortItem
        conditionList[SELECT_FILTER] = selectFilterItem

        selectedConditionList[currentPageIndex] = conditionList
        refreshFragmentPageData(selectSortItem.key!!, selectFilterItem.key!!)
    }

    private fun refreshFragmentPageData(sort: String, filter: String) {
        testCategoryAdapter?.getFragmentByPosition(currentPageIndex)?.refreshListData(sort, filter)

    }

    private fun click_category() {
    }


    override fun onError(t: Throwable) {
        HttpErrorUtils.handleError(mContext, t)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == payRequestCode && resultCode == Activity.RESULT_OK) {
            //如果 是待付款列表 则需要刷新界面
            if (null != mPresenter) {
                mPresenter.fetchTestTypeList()
            }
        }
    }


    override fun onTestCategoryListFetched(testCategoryList: MutableList<TestCategory>) {
        testCategory = testCategoryList
        testCategoryAdapter = TestListPagerAdapter(supportFragmentManager, this, testCategoryList);
        vvp_test.adapter = testCategoryAdapter
        vt_test_search.setupWithViewPager(vvp_test)
        if (isMine) {
            var myTab = 0
            for ((index, cat) in testCategoryList.withIndex()) {
                if (cat.tab == "my") {
                    myTab = index
                    break
                }

            }
            currentPageIndex = myTab
        } else if (null != tabName && !tabName!!.isEmpty()) {
            var myTab = 0
            for ((index, cat) in testCategoryList.withIndex()) {
                if (cat.tab == tabName) {
                    myTab = index
                    break
                }

            }
            currentPageIndex = myTab
        }
        if (currentPageIndex != 0) {
            vvp_test.currentItem = currentPageIndex
        }
    }


    //显示排序弹窗
    private fun showSortPopupWindow() {
        sortPopup?.showAsDropDown(ll_sort)
        view_mask.visibility = View.VISIBLE
    }

    private fun updateFilterTextViewStatus(tv: TextView, text: String, isNormal: Boolean) {
        tv.text = text
        if (isNormal) {
            tv.setTextColor(ContextCompat.getColor(this, R.color.platform_color_999999))
            tv.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.platform_ic_arrow_drop_down_grey_500_18dp,
                0
            )
        } else {
            tv.setTextColor(ContextCompat.getColor(this, R.color.platform_main_theme))
            tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.tests_ic_arrow_drop_down, 0)
        }
    }

    private fun updateTabLayoutStatus(tabLayout: CommonTabLayout, text: String) {
        when (text) {
            "全部" -> {
                tabLayout.currentTab = 0
            }

            "付费" -> {
                tabLayout.currentTab = 1
            }

            "免费" -> {
                tabLayout.currentTab = 2
            }
        }
    }

    override fun onFailed(msg: String?) {
        ToastUtil.toastShort(msg ?: "")
    }

    override fun createPresenter(): TestListActivityPresenter = TestListActivityPresenter()
    override fun couponResponse(list: ArrayList<TestsRedPacketBean>) {}

    override fun onResume() {
        super.onResume()
        TestHomeUtils.updateCouponMoney()
    }
}
