package com.yidianling.tests.home

import android.os.Build
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.utils.*
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.RxImageTool
import com.yidianling.tests.R
import com.yidianling.tests.home.adapter.AdapterWrapper
import com.yidianling.tests.home.adapter.TestHomeAdapter
import com.yidianling.tests.home.bean.TestHomeDataBean
import com.yidianling.tests.home.config.ITestHomeConfig
import com.yidianling.tests.home.contract.ITestHomeContract
import com.yidianling.tests.home.event.ITestHomeEvent
import com.yidianling.tests.home.event.TestHomeEventImpl
import com.yidianling.tests.home.event.UpdateCouponMoneyEvent
import com.yidianling.tests.home.presenter.TestHomePresenterImpl
import com.yidianling.tests.home.utils.TestHomeUtils
import com.yidianling.tests.home.widget.SwipeToLoadHelper
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.tests_testhome_activity.*
import kotlinx.android.synthetic.main.tests_testhome_bar.*
import org.json.JSONObject

/**
 * @author yuanwai
 * @描述:测评首页Activity
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/7/26
 */
//@Route(path = "/ceshi/home")
class TestHomeActivity : BaseMvpActivity<ITestHomeContract.View,ITestHomeContract.Presenter>(), ITestHomeContract.View, SwipeToLoadHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    /**
     * 适配器包装 处理上拉加载更多
     */
    private var mAdapterWrapper: AdapterWrapper? = null
    /**
     * 测评首页列表适配器
     */
    private var mTestHomeAdapter: TestHomeAdapter? = null
    /**
     * 下拉刷新组件
     */
    private var mLoadMoreHelper: SwipeToLoadHelper? = null
    /**
     * LayoutManager
     */
    private var mLayoutManager: RecyclerView.LayoutManager? = null
    /**
     * 页
     */
    private var page: Int = 1
    /**
     * 测评首页事件处理类
     */
    private var testHomeEvent: ITestHomeEvent? = null

    private var dp150: Int? = 0
    /**
     * 来源
     */
    private var fromStr: String? = null

    override fun createPresenter(): ITestHomeContract.Presenter {
        return TestHomePresenterImpl()
    }

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

    override fun initDataAndEvent() {
        EventBus.getDefault().register(this)
        testHomeEvent = TestHomeEventImpl(this)
        getRouterParam()
        initAdapter()
        loadLocalData()
        newHomeRequest()
        rl_search.setOnClickListener {
            (testHomeEvent as TestHomeEventImpl).jumpSearch()
        }
        img_back.setOnClickListener {
            onBackPressed()
        }
        img_mine.setOnClickListener {
            (testHomeEvent as TestHomeEventImpl).jumpMine()
        }
        initStatus()
    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
            StatusBarUtils.setTransparentForImageView(this, null)
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(this)
            val lp1 = rl_tests_title_layout.layoutParams as LinearLayout.LayoutParams
            lp1.height = (RxImageTool.dp2px(48f) + statusBarHeight)
            rl_tests_title_layout.setPadding(0, statusBarHeight, 0, 0)
        }
    }


    //路由传递过来的参数
    private fun getRouterParam() {
        if (null != intent && intent.hasExtra("routerParam")) {
            val params = intent.getStringExtra("routerParam")
            val paramsJson = JSONObject(params)
            if (paramsJson.has("from")){
                fromStr = paramsJson.getString("from");
            }
        }
    }

    private fun initAdapter() {
        swipe_refresh_layout.setOnRefreshListener(this)
        swipe_refresh_layout.setColorSchemeColors(ContextCompat.getColor(this, R.color.platform_main_theme))
        mLayoutManager = LinearLayoutManager(
            mContext,
            LinearLayoutManager.VERTICAL,
            false
        )
        recyclerview.layoutManager = mLayoutManager
        if (null == mTestHomeAdapter) {
            mTestHomeAdapter = TestHomeAdapter(this, ArrayList<TestHomeDataBean>(), testHomeEvent!!, this)
        }
        if (null == mAdapterWrapper) {
            mAdapterWrapper = AdapterWrapper(mTestHomeAdapter!!)
        }
        mLoadMoreHelper = SwipeToLoadHelper(recyclerview, mAdapterWrapper!!)
        mLoadMoreHelper!!.setLoadMoreListener(this)
        recyclerview.adapter = mAdapterWrapper
    }

    override fun onResume() {
        super.onResume()
        if (null == mTestHomeAdapter) {
            return
        }
        mTestHomeAdapter!!.starBanner()
        TestHomeUtils.updateCouponMoney()
    }

    override fun onStop() {
        super.onStop()
        if (null == mTestHomeAdapter) {
            return
        }
        mTestHomeAdapter!!.stopBanner()
    }

    private fun loadLocalData() {
        //取上次缓存的优惠券数据
        val lastCouponMoney = SharedPreferencesEditor.getString(TestHomeUtils.TEST_MAX_COUPON_MONEY_SP_KEY)
        if (!TextUtils.isEmpty(lastCouponMoney)){
            mTestHomeAdapter?.couponMoney = lastCouponMoney
        }
        YDLAsyncUtils.asyncAsResult(object : YDLAsyncUtils.AsyncObjecyerResult {
            override fun doAsyncAction(): Any {

                //读取缓存数据
                var cacheData = YDLCacheUtils.getTestHomeData()

                if (cacheData.isEmpty()) {
                    cacheData = String(TestHomeUtils.getAssertsFile(mContext, "test_home.json")!!)
                }

                return cacheData
            }

            override fun asyncResult(`object`: Any?) {

                if (`object` is String) {
                    val list = Gson().fromJson<List<TestHomeDataBean>>(`object`, object : TypeToken<List<TestHomeDataBean>>() {

                    }.type)
                    if (null != list && !list.isEmpty()) {
                        newHomeResponse(list)
                    }
                }
            }
        })
    }

    override fun newHomeRequest() {
        page = 1
        mPresenter.newHomeRequest()
    }

    override fun newHomeResponse(datalist: List<TestHomeDataBean>) {
        hideError()
        recyclerview.visibility = View.VISIBLE
        val newDataList = TestHomeUtils.resetData(datalist)
        mTestHomeAdapter!!.updataItems(newDataList)
        swipe_refresh_layout.isRefreshing = false
        // 刷新完成是解禁上拉加载更多
        mLoadMoreHelper!!.setSwipeToLoadEnabled(true)
        mAdapterWrapper!!.notifyDataSetChanged()
        YDLAsyncUtils.async(object : YDLAsyncUtils.AsyncObjecyer {
            override fun doAsyncAction() {
                YDLCacheUtils.saveTestHomeData(Gson().toJson(datalist))
            }
        })
    }

    override fun newHomeRequestFail() {
        showError()
    }

    private fun showError() {
        if (null == mTestHomeAdapter
                || null == mTestHomeAdapter!!.getList()
                || mTestHomeAdapter!!.getList().isEmpty()) {
            recyclerview.visibility = View.GONE
        }
    }

    private fun hideError() {
        recyclerview.visibility = View.VISIBLE
    }

    override fun loadMoreResponse(datalist: List<TestHomeDataBean>) {
        mTestHomeAdapter!!.addItems(datalist)
        swipe_refresh_layout.isEnabled = true
        if (3 == page) {
            mLoadMoreHelper!!.setNoMoreData()
        } else {
            mLoadMoreHelper!!.setLoadMoreFinish()
            mAdapterWrapper!!.notifyDataSetChanged()
        }
    }

    override fun dailyChange() {
        //埋点
        BuryPointUtils.getInstance().createMap()
                .burryPoint("ceping_change")
        showProgressDialog()
        mPresenter.dailyChange()
    }

    override fun dailyChangeResponse(dataBean: TestHomeDataBean) {
        dismissProgressDialog()
        var list = ArrayList<TestHomeDataBean>()
        list.addAll(mTestHomeAdapter!!.getList())
        for (item in list) {
            if (item.type == ITestHomeConfig.TYPE_DAILY) {
                (item.body as ArrayList).clear()
                item.body.addAll(dataBean.body!!)
            }
        }
        mTestHomeAdapter!!.updataItems(list)
        mTestHomeAdapter!!.notifyDataSetChanged()
        mAdapterWrapper!!.notifyDataSetChanged()
    }

    /**
     * 下拉刷新
     */
    override fun onRefresh() {
        mTestHomeAdapter!!.setBannerRefresh()
        newHomeRequest()
        // 刷新时禁用上拉加载更多
        mLoadMoreHelper!!.setSwipeToLoadEnabled(false)
    }

    /**
     * 上拉加载更多
     */
    override fun onLoad() {
        ++page
        if (page > 3) {
            mLoadMoreHelper!!.setNoMoreData()
            return
        }
        swipe_refresh_layout.isEnabled = false
        mPresenter.onLoadMore(page)
    }

    /**
     * 查看全部测评
     */
    override fun selectAll() {
        testHomeEvent!!.selectAll()
    }

    override fun showError(msg: String?) {
        ToastHelper.show("网络不给力")
    }

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

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (null != mTestHomeAdapter) {
            mTestHomeAdapter!!.onDestory()
        }
    }
}