package com.yidianling.tests.list.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewPager
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
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.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()

    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 filterPopup: 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()
        }

        dr_filter.setOnClickListener {
            showFilterPopupWindow()
        }

        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.isLogin()) {
                    startActivity(TestsIn.loginWayIntent(this@TestCategoryListActivity))
                }
            }
        })
        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()
            }
        })

        filterPopup = CategoryPopupWindow(this,
                filterList.toList() as ArrayList<CategotyPopItem>, object : CategoryConditionRecyclerViewAdapter.OnItemSelectedListener {
            override fun onSortItemSelected(sortItem: CategotyPopItem) {
                selectFilterItem = sortItem
                if (selectFilterItem.key == filterConditionDefaultKey) {
                    updateFilterTextViewStatus(dr_filter, sortItem.value!!, true)
                } else {
                    updateFilterTextViewStatus(dr_filter, sortItem.value!!, false)
                }
                filterPopup?.dismiss()
            }
        })

        sortPopup?.setOnDismissListener(this)
        filterPopup?.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)
            }

            if (selectFilterItem.key == filterConditionDefaultKey) {
                updateFilterTextViewStatus(dr_filter, selectFilterItem.value!!, true)
            } else {
                updateFilterTextViewStatus(dr_filter, selectFilterItem.value!!, false)
            }
        }else{
            selectSortItem  = CategotyPopItem("综合排序", sortConditionDefaultKey)
            selectFilterItem= CategotyPopItem("全部", filterConditionDefaultKey)

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

        sortPopup?.adapter?.lastSelectText = selectSortItem.value
        filterPopup?.adapter?.lastSelectText = selectFilterItem.value

        sortPopup?.adapter?.notifyDataSetChanged()
        filterPopup?.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 showFilterPopupWindow() {
        filterPopup?.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_colorTextDefault))
            tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.platform_ic_arrow_drop_down_grey_500_18dp, 0)
        } else {
            tv.setTextColor(ContextCompat.getColor(this, R.color.tests_main_theme))
            tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.tests_ic_arrow_drop_down, 0)
        }
    }

    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()
    }
}
