package com.yidianling.tests.list.view


import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.adapter.MyBaseAdapter
import com.ydl.ydlcommon.base.BaseFragment
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.bean.ShareData
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.BuryPointUtils
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.TestRetrofitApi
import com.yidianling.tests.home.event.UpdateCouponMoneyEvent
import com.yidianling.tests.home.utils.TestHomeUtils
import com.yidianling.tests.list.model.bean.Test
import com.yidianling.tests.list.model.bean.TestListData
import com.yidianling.tests.list.view.adapter.TestListRecyclerAdapter
import com.yidianling.tests.router.TestsIn
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.tests_fragment_test_list.*
import java.util.*

class TestListFragment : BaseFragment(), MyBaseAdapter.OnItemClickListener<Test> {
    override fun initDataAndEvent() {
        initUiAndListener()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

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

    private var category: String? = null //测试类型id
    private var categoryName: String? = null
    private var categoryId: String? = null
    private var currentPage = 1 //当前页

    private val testList: MutableList<Test> = ArrayList()
    private var share: ShareData? = null
    private var listType = 1 //1测试项目列表，2测试结果列表

    private lateinit var adapter: TestListRecyclerAdapter
    private lateinit var onScrollListener: EndlessRecyclerViewScrollListener

    fun initUiAndListener() {
        if (arguments != null) {
            category = arguments.getString(ARG_CATEGORY)
            categoryName = arguments.getString(ARG_NAME)
            categoryId = arguments.getString(ARG_ID)
        }

        EventBus.getDefault().register(this)
        adapter = TestListRecyclerAdapter(activity, testList, TestListRecyclerAdapter.PAGE_TYPE_CATEGORY)
        adapter.onItemClickListener = this
        rvTestList.adapter = adapter
        val layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        rvTestList.layoutManager = layoutManager
        onScrollListener = object : EndlessRecyclerViewScrollListener(layoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                fetchTestList()
            }
        }
        rvTestList.addOnScrollListener(onScrollListener)
        var lastCouponMoney = SharedPreferencesEditor.getString(TestHomeUtils.TEST_MAX_COUPON_MONEY_SP_KEY)
        if (!TextUtils.isEmpty(lastCouponMoney)){
            adapter?.couponMoney = lastCouponMoney
        }
    }

    override fun initDataAndEventLazy() {
    }

    private var disposable: Disposable? = null
    private var sort:String ="";
    private var filter:String ="";

    fun refreshListData(sort:String , filter:String){
        if (!this.sort.equals(sort)||!this.filter.equals(filter)){
            currentPage = 1
            this.sort = sort
            this.filter = filter
            fetchTestList()
        }

    }

    fun fetchTestList() {
        val loginBean = TestsIn.getYDLUserInfo()

        var userId = loginBean?.userId ?: "";

        disposable = TestRetrofitApi.getTestRetrofitApi()
                .fetchTestListByTag(
                        testTagId = categoryId.toString(),
                        page = currentPage.toString(),
                        uid = userId,
                        testPrice = if(filter=="2"||filter=="3") filter else "",
                        testCreateTime = if (sort=="5") sort else "",
                        testVisitNum = if (sort=="4") sort else ""
                )
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultJavaData())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate { dismissLoading() }
                .subscribe(Consumer {
                    onTestListFetched(it, currentPage)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        dismissLoading()
                        YdlCommonOut.showToast(msg)
                    }
                })
    }

    private fun dismissLoading() {
        //其实不应该这么改 只所以为空 应该是页面被销毁了 应该判断当前页面是否被销毁
        if (null != flLoading){
            flLoading.visibility = View.GONE
        }
    }

    override fun onItemClickListener(v: View?, position: Int, data: Test?) {

        BuryPointUtils.getInstance().createMap()
                .put("test_id", data?.id.toString())
                .put("test_title", data?.name ?: "")
                .put("test_type", categoryName ?: "")
                .burryPoint("testClick")
        if (v == null || data == null) {
            ToastUtil.toastShort(getString(R.string.tests_wrong_args))
            return
        }
        //如果列表是待支付 的话 则跳转 支付界面
        if ("unpay" == category){
            val url = StringBuffer(HttpConfig.MH5_URL)
            url.append("ceshi/")
            url.append(data.id)
            url.append("?payId=")
            url.append(data.pay_id)
            url.append("&couponMoney=")
            url.append(data.coupon_money)
            url.append("&orderId=")
            url.append(data.id)
            //跳转测试详情页
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_H5_H5,
                    YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, Uri.encode(url.toString())),"")

        }else{
            when (listType) {
                1 -> {
                    TestsIn.getTestsImpl().testDetailH5(data.id.toString())
                }
                2 -> {
                    TestsIn.getTestsImpl().testH5Result(data.testResultId.toString());
                }
                else -> TestsIn.getTestsImpl().testDetailH5(data.id.toString())
            }
        }
    }


    private fun onTestListFetched(testListData: TestListData, page: Int) {
        var newTestList = testListData.testList
        if ((newTestList==null||newTestList.size==0)
                &&(testListData.testListContainer.list!=null
                        && testListData.testListContainer.list!!.isNotEmpty())){
            newTestList = testListData.testListContainer.list
        }

        if (page == 1) {
            share = testListData.share
            listType = testListData.listType
            onScrollListener.resetState()
            testList.clear()
            if (testListData.testList?.size == 0 && listType == 2) {
                llNoTest.visibility = View.VISIBLE
            } else {
                llNoTest.visibility = View.GONE
            }
        }
        if (newTestList != null && newTestList.size > 0) {
            testList.addAll(newTestList)
            adapter.notifyDataSetChanged()
        } else {
            adapter.hasMore = false
            adapter.notifyDataSetChanged()
        }
        currentPage++
    }


    private fun initData() {
        currentPage = 1
        if (category == "my" || category == "unpay") {
            if (TestsIn.isLogin()) {
                fetchTestList()
            } else {
                llNoTest.visibility = View.VISIBLE
            }
        } else {
            fetchTestList()
        }
    }

    override fun onStop() {
        super.onStop()
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
        }
    }


    companion object {
        private const val ARG_CATEGORY = "category"
        private const val ARG_NAME = "category_name"
        private const val ARG_ID = "category_id"
        fun newInstance(category: String?, categoryId: String?,categoryName: String?): TestListFragment {
            val fragment = TestListFragment()

            val args = Bundle()
            args.putString(ARG_CATEGORY, category)
            args.putString(ARG_NAME, categoryName)
            args.putString(ARG_ID, categoryId)
            fragment.arguments = args
            return fragment
        }
    }

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

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