package com.ydl.confide.home

import android.content.Context
import android.os.Build
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SimpleItemAnimator
import android.view.View
import android.widget.LinearLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.ydl.confide.R
import com.ydl.confide.home.adapter.ConfideHomeAdapter
import com.ydl.confide.home.bean.ConfideHomeAllFiltersBean
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.confide.home.bean.ConfideHomeDataBean
import com.ydl.confide.home.bean.ConfideHomeFiterItemBean
import com.ydl.confide.home.config.IConfideHomeConfig
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.event.ConfideHomeEventImpl
import com.ydl.confide.home.event.IConfideHomeEvent
import com.ydl.confide.home.listener.ConfideHomeRecycleViewListener
import com.ydl.confide.home.listener.ConfideHomeRecyleSuspendListener
import com.ydl.confide.home.presenter.ConfideHomePresenterImpl
import com.ydl.confide.home.util.ConfideHomeUtils
import com.ydl.ydl_image.listener.YDLImageRecyclerOnScrollListener
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.DrawableRightTextView
import com.ydl.ydlcommon.view.WrapContentLinearLayoutManager
import com.yidianling.common.tools.RxImageTool
import com.yidianling.router.RouterManager
import kotlinx.android.synthetic.main.confide_home_activity.*
import kotlinx.android.synthetic.main.confide_title_bar.*

/**
 * @author yuanwai
 * @描述:倾诉首页Activity
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
@Route(path = "/confide/home")
class ConfideHomeActivity : BaseLceActivity<IConfideHomeContract.View,IConfideHomeContract.Presenter>(),IConfideHomeContract.View,XRecyclerView.LoadingListener {

    override fun getContentViewId(): Int {
        return R.id.rv_list
    }

    override fun getStateViewId(): Int {
        return R.id.lce_state_view
    }

    override fun reLoadData() {

    }


    //是否从启动页直接进入
    var isSplash: Boolean = false
    /**
     * 倾诉首页适配器
     */
    private var mConfideAdapter: ConfideHomeAdapter? = null
    /**
     * 倾诉首页事件处理类
     */
    private var mConfideEvent: IConfideHomeEvent? = null

    /**
     * 数据缓存
     */
    private var cacheList: MutableList<ConfideHomeDataBean>? = null

    // 一键倾诉Url
    private var quickConsultUrl: String? = null

    /**
     * 页（从第二页开始）
     */
    private var page: Int = 2
    //筛选参数bean
    private var allFiltersBean: ConfideHomeAllFiltersBean? = null
    //用于置顶筛选模块监听
    private var listScrollListener: ConfideHomeRecycleViewListener? = null
    //用于显示筛选悬浮View
    private var listSuspendListener: ConfideHomeRecyleSuspendListener? = null
    //是否有下一页（用于判断为你推荐条数，如果首页返回少于10条 那么就可以认为没有下一页了） 默认有下一页
    private var hasMore = true
    private var dp48 = 0

    init {
        //初始化参数
        initParam()
        dp48 = RxImageTool.dip2px(48f)
    }

    private fun initParam() {
        allFiltersBean = ConfideHomeAllFiltersBean(
                page,
                ConfideHomeFiterItemBean("1", ""),
                ConfideHomeFiterItemBean("-1", ""),
                ArrayList(),
                ArrayList())
    }

    override fun getContext(): Context {
        return ConfideHomeActivity@ this
    }

    override fun createPresenter(): IConfideHomeContract.Presenter {
        return ConfideHomePresenterImpl()
    }

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

    /**
     * 下拉刷新回调
     */
    override fun onRefresh() {
        //重置页
        page = 2
        allFiltersBean!!.page = page
        mPresenter.confideHomeRequest(true)
    }

    /**
     * 上拉加载更多
     */
    override fun onLoadMore() {
        recommendList(page)
        page++
    }

    override fun recommendList(page: Int) {
        //需要将当前列表已存在的老师uid数组发送到后端去重，因为排序实时变化
        this.page = page
        allFiltersBean!!.page = page
        if (1 == page) {
            //显示加载中
            showProgressDialog()
            allFiltersBean!!.notInUid = ArrayList()
            mPresenter.recommendList(ConfideHomeUtils.createParam(allFiltersBean!!))
        } else if (page > 1) {
            var listData = mConfideAdapter?.getList()
            var notUidList = ArrayList<Int>()
            if (listData!=null){
                for (bean in listData){
                    //列表类型数组
                    if (bean.type==5 && bean.body!=null){
                        for (bean in bean.body){
                            notUidList.add(bean.uid?:0)
                        }
                    }
                }
            }
            allFiltersBean!!.notInUid = notUidList
            mPresenter.recommendListMore(ConfideHomeUtils.createParam(allFiltersBean!!))
        }
    }

    override fun initDataAndEvent() {
        isSplash = intent.getBooleanExtra("isSplash", false)
        //初始化View
        initView()
        mConfideEvent = ConfideHomeEventImpl(this, this)
        //初始化适配器
        initAdapter()
        //显示加载中
//        showProgressDialog()
        //加载本地缓存
        mPresenter.loadLocalData(this)

        initClick()
        initQuickConsultDialog()
        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_confide_title_layout.layoutParams as LinearLayout.LayoutParams
            lp1.height = (RxImageTool.dp2px(48f) + statusBarHeight)
            rl_confide_title_layout.setPadding(0, statusBarHeight, 0, 0)
        }
    }

    /**
     * 监听控制一键倾诉浮层的显示与隐藏
     */
    private fun initQuickConsultDialog() {
        rv_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager: RecyclerView.LayoutManager = recyclerView?.layoutManager!!
                val linearManager = layoutManager as LinearLayoutManager
                if (linearManager is LinearLayoutManager) {
                    val firstItemPosition = linearManager.findFirstCompletelyVisibleItemPosition()
                    if (firstItemPosition > 3) {
                        quick_consult_card.visibility = View.VISIBLE
                    }else {
                        quick_consult_card.visibility = View.GONE
                    }
                }
            }
        })
    }

    /**
     * 初始化一键倾诉浮层的点击事件
     */
    private fun initClick() {
        quick_consult_btn.setOnClickListener {
            quickConsultUrl?.let {
                mConfideEvent?.categoryClick(quickConsultUrl)
            }
        }
    }

    private fun initView() {
        img_back.setOnClickListener {
            finish()
        }
        img_mine.setOnClickListener {
            mConfideEvent!!.jumpMine()
        }
        ll_bar_root.setOnClickListener {

        }
        //用于滑动筛选模块置顶
        if (null == listScrollListener) {
            listScrollListener = ConfideHomeRecycleViewListener()
        }
        rv_list.addOnScrollListener(listScrollListener)
        //用于显示筛选悬浮按钮
        if (null == listSuspendListener) {
            listSuspendListener = ConfideHomeRecyleSuspendListener()
        }
        rv_list.addOnScrollListener(listSuspendListener)
        rv_list.addOnScrollListener(YDLImageRecyclerOnScrollListener(ConfideHomeActivity@ this))
        if (rv_list.itemAnimator is SimpleItemAnimator) {
            (rv_list.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        }
    }

    /**
     * 初始化适配器
     */
    private fun initAdapter() {
        if (null == mConfideAdapter) {
            mConfideAdapter = ConfideHomeAdapter(ConfideHomeActivity@ this, mConfideEvent!!, this)
        }
        val layoutManager = WrapContentLinearLayoutManager(this, WrapContentLinearLayoutManager.VERTICAL, false)
        rv_list.layoutManager = layoutManager
        rv_list.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader)
        rv_list.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader)
        rv_list.setArrowImageView(R.drawable.confide_downgrey)
        rv_list.setLoadingListener(this)
        rv_list.adapter = mConfideAdapter
    }

    /**
     * 倾诉首页数据请求结果
     */
    override fun confideHomeResponse(list: MutableList<ConfideHomeDataBean>) {
        initParam()
        hideError()
        updateCacheData(list)
        updateAdapter()
        updateQuickConsultUrl()
        setSuspendListener()
        v_filterView.refreshView()
    }

    /**
     * 设置筛选模块悬浮顶部监听数据
     */
    private fun setSuspendListener() {
        listSuspendListener?.setFilterView(v_filterView)
        listSuspendListener?.setSectionAdapter(mConfideAdapter!!)
    }

    private fun setHideFilterView() {
        v_filterView.visibility = View.INVISIBLE
        v_filterView.setHomeView(this)
    }

    /**
     * 更新一键倾诉按钮url
     */
    private fun updateQuickConsultUrl() {
        //这边用try catch的原因是防止因为接口数据结构变化导致cacheList!![1].body!![1].linkUrl获取失败
        quickConsultUrl = try {
            cacheList!![1].body!![1].linkUrl
        }catch (e: Exception) {
            "https://h5.ydl.com/confideMatch"
        }
    }

    /**
     * 更新适配器数据
     */
    private fun updateAdapter() {
        rv_list.removeAllViews()
        //数据重组
        ConfideHomeUtils.resetData(cacheList!!, v_filterView, listScrollListener!!)
        setHideFilterView()
        mConfideAdapter?.updataItems(cacheList!!)
        mConfideAdapter?.notifyDataSetChanged()
        rv_list.refreshComplete()
    }

    /**
     * 更新适配器数据（用于播放 暂停 状态切换 更新整体数据）
     */
    private fun updateAdapterForPlayStatus() {
        mConfideAdapter!!.updataItems(cacheList!!)
        mConfideAdapter!!.notifyDataSetChanged()
    }

    private fun clearCacheData() {
        if (null == cacheList) {
            cacheList = ArrayList()
        } else {
            (cacheList as ArrayList).clear()
        }
    }

    /**
     * 更新缓存数据
     */
    private fun updateCacheData(list: List<ConfideHomeDataBean>) {
        clearCacheData()
        var soundBean: ConfideHomeDataBean? = null
        for (index in 0 until list.size) {
            //将听声寻人数据取出 最后加入
            when {
                //听声寻人
                list[index].type == IConfideHomeConfig.TYPE_SOUND -> soundBean = list[index]
                //为你推荐
                list[index].type == IConfideHomeConfig.TYPE_RECOMMEND -> {
                    //如果为你推荐的数量大于等于10条 就认为有下一页
                    hasMore = null != list[index].body && list[index].body!!.size >= 10
                    list[index].recommendId = page
                    (cacheList as ArrayList).add(list[index])
                }
                //其他模块正常添加
                else -> (cacheList as ArrayList).add(list[index])
            }
        }
        //听声寻人 放在最后添加
        if (null != soundBean) {
            (cacheList as ArrayList).add(soundBean)
        }
    }

    /**
     * 根据筛选条件 更新为你推荐数据
     */
    private fun updateCacheDataByRecommend(bean: ConfideHomeDataBean) {
        //需要重置一下页码
        page = 2
        if (null == cacheList) {
            cacheList = ArrayList()
        }
        if (bean?.body == null) {
            v_filterView.visibility = View.GONE
        } else if (null != bean.body && bean.body.size < 2) {
            v_filterView.visibility = View.GONE
        } else {
            v_filterView.visibility = View.VISIBLE
        }
        var soundBean: ConfideHomeDataBean? = null
        //从后往前循环 这样remove的时候不会有问题
        for (index in (0..(cacheList!!.size - 1)).reversed()) {
            if (cacheList!![index].type == IConfideHomeConfig.TYPE_RECOMMEND) {
                //移除原有的为你推荐数据
                (cacheList as ArrayList).removeAt(index)
            } else if (cacheList!![index].type == IConfideHomeConfig.TYPE_SOUND) {
                //移除听声寻人数据 重新添加
                soundBean = cacheList!![index]
                (cacheList as ArrayList).removeAt(index)
            }
        }
        if (bean?.body != null) {
            bean.recommendId = page
            //添加为你推荐数据
            (cacheList as ArrayList).addAll(ConfideHomeUtils.getRecommendList(bean))
        }
        //添加听声寻人数据
        if (null != soundBean) {
            (cacheList as ArrayList).add(soundBean)
        }
        listScrollListener?.moveToPosition(rv_list)
    }

    /**
     * 为你推荐 翻页 请求结果
     */
    override fun recommendListMoreResponse(bean: ConfideHomeDataBean) {
        dismissProgressDialog()
        bean.recommendId = page
        if(bean.body?.size?:0==0) {
            rv_list.loadMoreComplete()
            mConfideAdapter!!.notifyDataSetChanged()
            return
        }
        (cacheList as ArrayList).add(bean)
        var size = mConfideAdapter!!.itemCount
        mConfideAdapter!!.addItems(ConfideHomeUtils.getRecommendList(bean))
//        if (bean?.body == null || bean.body!!.size < 10) {
//            rv_list.setNoMore(true)
//        } else {
        rv_list.loadMoreComplete()
//        }

        mConfideAdapter!!.notifyItemInserted(if (size > 0) size + 1 else 0)
    }

    /**
     * 为你推荐 筛选 请求结果
     */
    override fun recommendListResponse(bean: ConfideHomeDataBean) {
        dismissProgressDialog()
        updateCacheDataByRecommend(bean)
        mConfideAdapter!!.updataItems(cacheList!!)
        if (bean?.body == null || bean.body!!.size < 10) {
            rv_list.setNoMore(true)
        } else {
            rv_list.loadMoreComplete()
        }
        mConfideAdapter!!.notifyDataSetChanged()
    }

    /**
     * 倾诉首页数据请求失败
     */
    override fun confideHomeRequestFail() {
        showError()
    }

    override fun showProgress() {
    }


    /**
     * 更新section的播放状态
     * 点击列表中的一个播放按钮 其他播放按钮要显示暂停状态
     * @param sectionId
     * @param index 模块中点击播放的索引位置
     */
    override fun updataPlayStatu(type: Int?, index: Int, recommendId: Int, isPlaying: Boolean) {
        ConfideHomeUtils.changeCacheDataPlay(cacheList, type, index, recommendId)
        updateAdapterForPlayStatus()
    }

    override fun moveToFilter() {
        rv_list.scrollBy(0, 400)
        listScrollListener?.moveToPosition(rv_list)
    }

    override fun showSortPopupWindow(v_line_top: View, tvSort: DrawableRightTextView, bodyBean: ConfideHomeBodyBean?) {
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showSortPopupWindow(v_line_top, v_filterView, bodyBean, allFiltersBean!!, mConfideAdapter!!)
    }

    override fun showSexAgePopupWindow(v_line_top: View, tvSexAge: DrawableRightTextView, bodyBean: ConfideHomeBodyBean?) {
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showSexAgePopupWindow(v_line_top, v_filterView, bodyBean, allFiltersBean!!, mConfideAdapter!!)
    }

    override fun showGoodPopupWindow(v_line_top: View, tvGood: DrawableRightTextView, bodyBean: ConfideHomeBodyBean?) {
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showGoodPopupWindow(v_line_top, v_filterView, bodyBean, allFiltersBean!!, mConfideAdapter!!)
    }

    private fun showError() {
        rv_list.refreshComplete()
    }

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

    override fun showError1(msg: String?){
        rv_list.loadMoreComplete()

        msg?.let {
            ToastHelper.show(msg)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mConfideEvent!!.destoryPlayer()
    }

    override fun onBackPressed() {
        if (isSplash) {
            //跳转主页
            var int = RouterManager.getAppRouter()?.mainIntent(this)
            startActivity(int)
        }
        super.onBackPressed()
    }
}