package com.yidianling.im.ui.page.fragment

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.ydl.ydlcommon.base.BaseFragment
import com.ydl.ydlcommon.data.http.RxUtils
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.api.event.SelectTabIMEvent
import com.yidianling.im.event.MessageListRefreshEvent
import com.yidianling.im.http.ImHttpImpl
import com.yidianling.im.router.ImIn
import com.yidianling.im.ui.page.fragment.adapter.InteractAdapter
import com.yidianling.im.ui.page.fragment.bean.InteractItemBean
import com.yidianling.im.ui.page.fragment.view.InteractFooterItemView
import com.yidianling.im.ui.page.widget.ChatUnusualView
import com.yidianling.im.ui.param.InteractMessageParam
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.im_interact_fragment.*

/**
 * 互动消息列表页面(该页面不分页)
 * Created by xj on 2019/10/11.
 */
class InteractFragment : BaseFragment(), XRecyclerView.LoadingListener {

    private lateinit var  mContext: Context
    private var interactAdapter: InteractAdapter? = null
    private var interactList: ArrayList<InteractItemBean> = ArrayList()

    private var presentPage: Int = 0 // 当前页面
    private var requestPage: Int = 1 // 请求页面 当请求页面和当前页面不一致的时候，才会进行数据操作，不然请求的为当前页面已经展示的数据
    private var pageSize: Int = 20 //每页展示数量

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

    override fun initDataAndEvent() {
        mContext = requireContext()
        initListPageData()
        initListData()

    }

    private fun initListData() {
        interactAdapter = InteractAdapter(mContext, interactList)
        interact_recyclerview.layoutManager =
            LinearLayoutManager(context)
        interact_recyclerview.adapter = interactAdapter
        interact_recyclerview.setLoadingListener(this)
        val footerView = InteractFooterItemView(mContext)
        interact_recyclerview.setFootView(footerView, object : CustomFooterViewCallBack {
            override fun onSetNoMore(p0: View?, p1: Boolean) {
                footerView.setNoMoreText()
            }

            override fun onLoadingMore(p0: View?) {
                footerView.setOnLoading()
            }

            override fun onLoadMoreComplete(p0: View?) {
                footerView.setOnComplete()
            }
        })
    }

    override fun onLoadMore() {
        getInteractMessageData(true)
    }

    override fun onRefresh() {
        EventBus.getDefault().post(MessageListRefreshEvent(1))
        initListPageData()
        interact_recyclerview.setNoMore(false)
        getInteractMessageData(refresh = true)
    }

    private fun initListPageData() {
        presentPage = 0 // 当前页面
        requestPage = 1 // 请求页面 当请求页面和当前页面不一致的时候，才会进行数据操作，不然请求的为当前页面已经展示的数据
        pageSize = 20 //每页展示数量
    }

    fun getInteractMessageData(onLoadMore: Boolean = false, refresh: Boolean = false) {
        if (refresh) {
            initListPageData()
        }

        if (ImIn.getUserInfo()?.uid != "0") {
            // 由于当前方法会因为各种因素多次调用，因此在接口返回值内判断只有在pageOn=1或者onLoadMore得时候，才将返回值加入展示列表中
            var dis = ImHttpImpl.getInstance().getInteractMessage(InteractMessageParam("${ImIn.getUserInfo()?.uid}", "${requestPage}", "${pageSize}"))
                    .compose(RxUtils.applySchedulers(this))
                    .compose(RxUtils.resultJavaData())
                    .subscribe({ it ->
                        interact_recyclerview.refreshComplete()
                        // 请求页面大于当前页面，才进行数据操作
                        if (requestPage > presentPage) {
                            Log.i("presentPage改变了", presentPage.toString())
                            if (presentPage == 0) {
                                //第一页，先删除所有数据，然后再添加所有返回的数据
                                interactList.clear()
                                interactList.addAll(it.list)
                                presentPage = requestPage
                                requestPage++
                            } else if (onLoadMore) {
                                //如果是上拉加载更多，那么直接将数据加入列表中
                                interactList.addAll(it.list)
                                requestPage++
                            } else if (!onLoadMore) {
                                //进入这边代表请求的是同一页数据，不做任何操作
                            }
                        }
                        if (!it.hasNextPage) {
                            interact_recyclerview.setNoMore(true)
                        } else {
                            interact_recyclerview.setNoMore(false)
                        }
                        updateShowData()
                        interactAdapter?.notifyDataSetChanged()
                        resetPageShow()
                    }, { t ->
                        ToastUtil.toastShort("您的网络出现了问题")
                        interact_recyclerview.refreshComplete()
                    })
        }
    }

    /**
     * 筛选时间（去重并保留最上面一个）
     */
    private fun updateShowData() {
        if (interactList.size > 0) {
            var timeStr = interactList[0].createTimeStr
            interactList.forEachIndexed { index, interactItemBean ->
                if (index != 0 && interactItemBean.createTimeStr != "") {
                    if (timeStr == interactItemBean.createTimeStr) {
                        interactList[index].createTimeStr = ""
                    } else {
                        timeStr = interactItemBean.createTimeStr
                    }
                }
            }
        }
    }

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

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (isVisibleToUser && getIsViewCreated()) {
            // 每次展示的时候都需要处理页面展示逻辑
            getInteractMessageData(false, refresh = true)
        }
    }

    fun nextUnReadItem() {

    }

    fun clearData() {
        interactList.clear()
        interactAdapter?.notifyDataSetChanged()
        resetPageShow()
    }

    /**
     * 页面展示状态逻辑
     */
    fun resetPageShow() {

        if (ImIn.isLogin()) {
            //登录状态
            if (interactList.size != 0) {
                //数据不为空
                interact_recyclerview.visibility = View.VISIBLE
                ll_interact_unusual_view.visibility = View.GONE
            } else {
                interact_recyclerview.visibility = View.GONE
                ll_interact_unusual_view.visibility = View.VISIBLE
                ll_interact_unusual_view.setUnusualType(ChatUnusualView.TYPE_INTERACT_NO_DATA)
                ll_interact_unusual_view.setListener(object : ChatUnusualView.ChatUnusualListener {
                    override fun onButtonClick() {
                        EventBus.getDefault().post(SelectTabIMEvent(1))
                    }
                })
            }
        } else {
            //未登录
            interact_recyclerview.visibility = View.GONE
            ll_interact_unusual_view.visibility = View.VISIBLE
            ll_interact_unusual_view.setUnusualType(ChatUnusualView.TYPE_UNLOGIN)
            ll_interact_unusual_view.setListener(object : ChatUnusualView.ChatUnusualListener {
                override fun onButtonClick() {
                    ImIn.loginByOneKeyLogin(mContext,true)
                }
            })
        }
    }

    override fun initDataAndEventLazy() {
    }
}