package com.yidianling.im.ui.activity

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.StatusBarUtils.Companion.setTransparentForImageView
import com.ydl.ydlcommon.utils.StatusBarUtils.Companion.statusBarLightMode
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.event.MessageListRefreshEvent
import com.yidianling.im.event.UpdateTabUnreadNumEvent
import com.yidianling.im.helper.MsgReceiveHelper
import com.yidianling.im.http.ImHttpImpl
import com.yidianling.im.router.ImIn
import com.yidianling.im.ui.page.fragment.adapter.ChatAdapter
import com.yidianling.im.ui.page.fragment.bean.ChatItemBean
import com.yidianling.im.ui.page.fragment.bean.ChatModelBean
import com.yidianling.im.ui.page.fragment.view.ChatFooterItemView
import com.yidianling.im.ui.page.widget.ChatUnusualView
import com.yidianling.im.ui.param.ChatParam
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.im_chat_fragment_layout.*
import kotlinx.android.synthetic.main.im_chat_fragment_layout.chat_recyclerview
import kotlinx.android.synthetic.main.im_chat_fragment_layout.ll_chat_unusual_view
import kotlinx.android.synthetic.main.im_new_multi_message_fragment.*
import kotlinx.android.synthetic.main.medical_chat_list.*

@Route(path = "/im/medical")
class MedicalChatActivity : BaseActivity(), XRecyclerView.LoadingListener {


    companion object{
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, MedicalChatActivity::class.java)
            context.startActivity(starter)
        }
    }
    private var chatAdapter: ChatAdapter? = null
    private var allChatData: ChatModelBean = ChatModelBean() //全部数据

    private var showData: ArrayList<ChatItemBean> = ArrayList() // 最终展示的数据

    private val mCompare: Comparator<ChatItemBean> = Comparator { o1, o2 ->
        val res = o1.timestamp.compareTo(o2.timestamp)
        when {
            res == 0 -> 0
            res > 0 -> -1
            else -> 1
        }
    }
    override fun layoutResId(): Int {
        return R.layout.medical_chat_list
    }

    override fun initDataAndEvent() {
        EventBus.getDefault().register(this)

        initStatus()
        chatAdapter = ChatAdapter(mContext, showData, this@MedicalChatActivity)
        chatAdapter?.setlistener(object : ChatAdapter.ChatRecyclerViewCallback {
            override fun onRefresh() {
                getChatMessageData()
            }
        })

        chat_recyclerview.layoutManager = LinearLayoutManager(this@MedicalChatActivity)
        chat_recyclerview.adapter = chatAdapter
        chat_recyclerview.setLoadingListener(this@MedicalChatActivity)
        chat_recyclerview.setFootView(
            ChatFooterItemView(mContext),
            object : CustomFooterViewCallBack {
                override fun onSetNoMore(p0: View?, p1: Boolean) {
                }

                override fun onLoadingMore(p0: View?) {
                }

                override fun onLoadMoreComplete(p0: View?) {
                }
            })
        iv_back.setOnClickListener { finish() }
    }

    private fun initStatus() {
        setTransparentForImageView(this@MedicalChatActivity, null)
        statusBarLightMode(this@MedicalChatActivity)
    }

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

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)

    }

    fun clearData() {
        showData.clear()
        chatAdapter?.notifyDataSetChanged()
        resetPageShow()
        resetPageShow()
    }

    /**
     * 页面展示状态逻辑
     */
    private fun resetPageShow() {
        ll_chat_unusual_view?.let {
            if (ImIn.isLogin()) {
                //登录状态
                if (showData.size != 0) {
                    //数据不为空
                    chat_recyclerview.visibility = View.VISIBLE
                    ll_chat_unusual_view.visibility = View.GONE
                } else {
                    chat_recyclerview.visibility = View.GONE
                    ll_chat_unusual_view.visibility = View.VISIBLE
                    ll_chat_unusual_view.setUnusualType(ChatUnusualView.TYPE_CHAT_ALL_NO_DATA)
                }
            } else {
                //未登录状态
                chat_recyclerview.visibility = View.GONE
                ll_chat_unusual_view.visibility = View.VISIBLE
                ll_chat_unusual_view.setUnusualType(ChatUnusualView.TYPE_UNLOGIN)
                ll_chat_unusual_view.setListener(object : ChatUnusualView.ChatUnusualListener {
                    override fun onButtonClick() {
                        ImIn.loginByOneKeyLogin(mContext, true)
                    }
                })
            }
        }
    }

    override fun onRefresh() {
        EventBus.getDefault().post(MessageListRefreshEvent(0))
        getChatMessageData()
    }


    override fun onLoadMore() {
        chat_recyclerview.setNoMore(true)

    }

    fun getChatMessageData() {
        if (ImIn.getUserInfo()?.uid != "0") {
            var dis = ImHttpImpl.getInstance()
                .getAllChatMessage(ChatParam("${ImIn.getUserInfo()?.uid}", "${0}"))
                .compose(RxUtils.applySchedulers(this))
                .compose<ChatModelBean>(RxUtils.resultJavaData())
                .subscribe({ it ->
                    if (it.before.data.size != 0 || it.nomal.data.size != 0) {
                        setData(it)
                    }else{
                        resetPageShow()
                    }
                    chat_recyclerview?.let {
                        chat_recyclerview.refreshComplete()
                    }
                }, { t ->
                    ToastUtil.toastShort("您的网络出现了问题")
                    chat_recyclerview?.let {
                        chat_recyclerview.refreshComplete()
                    }
                    resetPageShow()
                })
        }
    }

    /**
     * 设置全部数据
     */
    fun setData(data: ChatModelBean) {
        allChatData = data

        setShowData()
    }

    /**
     * 设置最终显示得数据，（优先置顶，再最近数据，再三周前的消息item，再三周前，其余按照时间排序）
     */
    private fun setShowData() {
        showData.clear()
        chatAdapter?.notifyDataSetChanged()
        selectTopData()
        // 全部
        showData.addAll(allChatData.topData.data.sortedWith(mCompare))
        showData.addAll(allChatData.nomal.data.filter { it.is_top == 0 }
            .sortedWith(mCompare))
        if (allChatData.before.data.any { it.is_top == 0 }) {
            showData.addAll(allChatData.before.data.filter { it.is_top == 0 }
                .sortedWith(mCompare))
        }

        // 重置消息未读数
        MsgReceiveHelper.reQueryUnreadNumber {
            showData.forEachIndexed { index, _ ->
                showData[index].unReadNum =
                    MsgReceiveHelper.getUnNum(showData[index].toUid.toString())
            }
            chatAdapter?.notifyDataSetChanged()
            resetPageShow()
        }
        resetPageShow()
    }

    /**
     * 将before数据和nomal数据里面的置顶数据筛选出来放入topData里面
     */
    private fun selectTopData() {
        allChatData.topData.data.clear()
        allChatData.topData.data.addAll(allChatData.before.data.filter { it.is_top == 1 })
        allChatData.topData.data.addAll(allChatData.nomal.data.filter { it.is_top == 1 })
    }


    /**
     * 私聊未读数变化触发的事件，不进行互动和通知未读数的更新
     */
    fun onEvent(event: UpdateTabUnreadNumEvent) {
        getChatMessageData()
    }
}