package com.yidianling.tests.list.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.viewpager.widget.ViewPager
import android.view.View
import android.widget.PopupWindow
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.PopUtils
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.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.TestListPagerAdapter
import com.yidianling.tests.router.TestsIn
import com.yidianling.tests.search.TestSearchActivity
import kotlinx.android.synthetic.main.tests_activity_test_list.*

@Route(path = "/ceshi/list")
class TestListActivity : BaseMvpActivity<TestListActivityView, TestListActivityPresenter>(), TestListActivityView {

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

    override fun initDataAndEvent() {
        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)
        }
        titleBar.setOnRightTextClick { _, _ ->
            TestSearchActivity.start(this)
        }
        titleBar.setRightImageListener {
            popupWindow = PopUtils.showMoreItem(mContext,
                    titleBar.rootView,
                    0,
                    0)
        }
        mPresenter.fetchTestTypeList()
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

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

            override fun onPageSelected(position: Int) {
                click_category()

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

    private fun click_category() {
    }

    override fun onResume() {
        super.onResume()
        //获取红包列表
        if (TestsIn.isLogin()){
            mPresenter.requestCoupon()
        }
    }

    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, TestListActivity::class.java)
            context.startActivity(intent)
        }

        fun start(context: Context, isMine: Boolean) {
            LogHelper.getInstance().writeLogSync("跳转到测试题")
            val intent = Intent(context, TestListActivity::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, TestListActivity::class.java)
            intent.putExtra(EXTRA_TABNAME, tab)
            context.startActivity(intent)
        }
    }

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

    private var isMine: Boolean = false
    private var tabName: String? = null

    private var testCategorys: MutableList<TestCategory>? = null

    override fun couponResponse(list: ArrayList<TestsRedPacketBean>) {
        if (null == list || list.isEmpty()){
            llTestRedPacketTips.visibility = View.GONE
        }else{
            llTestRedPacketTips.visibility = View.VISIBLE
            val sb = StringBuffer()
            sb.append("还有").append(list.size).append("个心理测试红包等你使用")
            tvTestRedPacketTips.text = sb.toString()
            llTestRedPacketTips.setOnClickListener {
                TestsIn.myRedPockIntent(TestListActivity@this)
            }
        }
    }

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

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

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

            }
            viewPager.currentItem = myTab
        }
    }

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

    override fun createPresenter(): TestListActivityPresenter = TestListActivityPresenter()

    private var popupWindow: PopupWindow? = null

    override fun onBackPressed() {
        if (popupWindow != null && popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        } else {
            super.onBackPressed()
        }
    }
}
