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

import android.content.Context
import android.graphics.Color
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
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.event.MessageListRefreshEvent
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.*

/**
 * 私聊消息列表页面
 * Created by xj on 2019/9/20.
 */
class ChatFragment : BaseFragment(), XRecyclerView.LoadingListener {

    enum class ChatModelType {
        ALL, // 全部
        SERVICING, // 服务中
        SERVICED // 服务过
    }

    private lateinit var mContext: Context
    private var chatAdapter: ChatAdapter? = null
    private var allChatData: ChatModelBean = ChatModelBean() //全部数据
    private var showData: ArrayList<ChatItemBean> = ArrayList() // 最终展示的数据

    private var threeWeekItem: ChatItemBean =
        ChatItemBean(0, 0, "", 0, 0, "", 0, 0, 0, 0, 0, "", 0, "", "", 0, 0, 0, "", 1, "", true)

    private var mChatModelType: ChatModelType = ChatModelType.ALL // 默认展示全部

    private val mCompare: Comparator<ChatItemBean> = Comparator { o1, o2 ->
        val res = o1.timestamp.compareTo(o2.timestamp)
        when {
            res == 0 -> 0
            res > 0 -> -1
            else -> 1
        }
    }

    //当前未读item下标
    private var curItem = 0

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

    override fun initDataAndEvent() {
        mContext = requireContext()
        selectModel(mChatModelType)

        chat_all_message.setOnClickListener {
            selectModel(ChatModelType.ALL)
        }
        chat_servicing_message.setOnClickListener {
            selectModel(ChatModelType.SERVICING)
        }
        chat_serviced_message.setOnClickListener {
            selectModel(ChatModelType.SERVICED)
        }

        initListData()
    }

    override fun initDataAndEventLazy() {
    }

    fun getChatMessageData() {
        var selectType: Int =
            if (mChatModelType == ChatModelType.ALL) 0 else if (mChatModelType == ChatModelType.SERVICING) 1 else 2

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

    }

    fun nextUnReadItem() {
        if (showData == null) return
        for (i in curItem + 1 until showData.size) {
            var num = 0
            try {
                num = Integer.parseInt(showData[i].unReadNum.toString())
            } catch (e: NumberFormatException) {
                e.printStackTrace()
            }
            if (num > 0 || MsgReceiveHelper.getUnNum(showData[i].toUid.toString()) > 0) {
                if (chat_recyclerview != null) {
                    chat_recyclerview.smoothScrollToPosition(i)
                }

                curItem = i
                break
            }
            if (i == showData.size - 1) {
                curItem = 0
                if (chat_recyclerview != null) {
                    chat_recyclerview.smoothScrollToPosition(0)
                }

            }
        }
    }

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

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

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

        setShowData()
    }

    /**
     * 设置最终显示得数据，（优先置顶，再最近数据，再三周前的消息item，再三周前，其余按照时间排序）
     */
    private fun setShowData() {
        showData.clear()
        chatAdapter?.notifyDataSetChanged()
        selectTopData()
        when (mChatModelType) {
            // 全部
            ChatModelType.ALL -> {
                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.add(threeWeekItem)
                    showData.addAll(allChatData.before.data.filter { it.is_top == 0 }
                        .sortedWith(mCompare))
                }
            }
            // 服务中
            ChatModelType.SERVICING -> {
                showData.addAll(allChatData.topData.data.filter { it.isBusy == 1 }
                    .sortedWith(mCompare))
                showData.addAll(allChatData.nomal.data.filter { it.isBusy == 1 && it.is_top == 0 }
                    .sortedWith(mCompare))
                if (allChatData.before.data.any { it.isBusy == 1 && it.is_top == 0 }) {
                    showData.add(threeWeekItem)
                    showData.addAll(allChatData.before.data.filter { it.isBusy == 1 && it.is_top == 0 }
                        .sortedWith(mCompare))
                }
            }
            // 服务过
            ChatModelType.SERVICED -> {
                showData.addAll(allChatData.topData.data.filter { it.isBusy != 1 && it.orderCount + it.listenOrderCount > 0 }
                    .sortedWith(mCompare))
                showData.addAll(allChatData.nomal.data.filter { it.isBusy != 1 && it.is_top == 0 && (it.orderCount + it.listenOrderCount > 0) }
                    .sortedWith(mCompare))
                if (allChatData.before.data.any { it.isBusy != 1 && it.is_top == 0 && (it.orderCount + it.listenOrderCount > 0) }) {
                    showData.add(threeWeekItem)
                    showData.addAll(allChatData.before.data.filter { it.isBusy != 1 && it.is_top == 0 && (it.orderCount + it.listenOrderCount > 0) }
                        .sortedWith(mCompare))
                }
            }
        }
        // 重置消息未读数
        MsgReceiveHelper.reQueryUnreadNumber {
            showData.forEachIndexed { index, _ ->
                showData[index].unReadNum =
                    MsgReceiveHelper.getUnNum(showData[index].toUid.toString())
            }
            chatAdapter?.notifyDataSetChanged()
            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 })
    }

    private fun initListData() {

        chatAdapter = ChatAdapter(mContext, showData, this)
        chatAdapter?.setlistener(object : ChatAdapter.ChatRecyclerViewCallback {
            override fun onRefresh() {
                getChatMessageData()
            }
        })
        chat_recyclerview.layoutManager = LinearLayoutManager(context)
        chat_recyclerview.adapter = chatAdapter
        chat_recyclerview.setLoadingListener(this)
        chat_recyclerview.setFootView(
            ChatFooterItemView(mContext),
            object : CustomFooterViewCallBack {
                override fun onSetNoMore(p0: View?, p1: Boolean) {
                }

                override fun onLoadingMore(p0: View?) {
                }

                override fun onLoadMoreComplete(p0: View?) {
                }
            })
    }

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

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && getIsViewCreated()) {
            resetPageShow()
        }
    }

    fun clearData() {
        showData.clear()
        chatAdapter?.notifyDataSetChanged()
        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
                    when (mChatModelType) {
                        ChatModelType.ALL -> {
                            ll_chat_unusual_view.setUnusualType(ChatUnusualView.TYPE_CHAT_ALL_NO_DATA)
                        }
                        ChatModelType.SERVICING -> {
                            ll_chat_unusual_view.setUnusualType(ChatUnusualView.TYPE_CHAT_SERVICING_NO_DATA)
                        }
                        ChatModelType.SERVICED -> {
                            ll_chat_unusual_view.setUnusualType(ChatUnusualView.TYPE_CHAT_SERVICED_NO_DATA)
                        }
                    }
                    ll_chat_unusual_view.setListener(object : ChatUnusualView.ChatUnusualListener {
                        override fun onButtonClick() {
                            startActivity(
                                ImIn.getConsultService().expertSearchIntent(activity!!, "0", 0, false)
                            )
                        }
                    })
                }
            } 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)
                    }
                })
            }
        }
    }

    /**
     * 选择私聊列表展示模式
     */
    private fun selectModel(modelType: ChatModelType) {
        mChatModelType = modelType
        setShowData()
        resetPageShow()
        chat_all_message.setBackgroundResource(R.drawable.im_chat_model_unselected_bg)
        chat_servicing_message.setBackgroundResource(R.drawable.im_chat_model_unselected_bg)
        chat_serviced_message.setBackgroundResource(R.drawable.im_chat_model_unselected_bg)
        chat_all_message.setTextColor(Color.parseColor("#666666"))
        chat_servicing_message.setTextColor(Color.parseColor("#666666"))
        chat_serviced_message.setTextColor(Color.parseColor("#666666"))

        when (modelType) {
            ChatModelType.ALL -> {
                chat_all_message.setTextColor(resources.getColor(R.color.platform_but_text_color_selected))
                chat_all_message.setBackgroundResource(R.drawable.im_chat_model_selected_bg)
            }
            ChatModelType.SERVICING -> {
                chat_servicing_message.setTextColor(resources.getColor(R.color.platform_but_text_color_selected))
                chat_servicing_message.setBackgroundResource(R.drawable.im_chat_model_selected_bg)
            }
            ChatModelType.SERVICED -> {
                chat_serviced_message.setTextColor(resources.getColor(R.color.platform_but_text_color_selected))
                chat_serviced_message.setBackgroundResource(R.drawable.im_chat_model_selected_bg)
            }
        }
    }
}