package com.bc_chat.im.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.im.R
import io.rong.common.RLog
import io.rong.eventbus.EventBus
import io.rong.imkit.RongContext
import io.rong.imkit.RongIM
import io.rong.imkit.fragment.ConversationListFragment
import io.rong.imkit.model.Event
import io.rong.imkit.model.UIConversation
import io.rong.imkit.widget.AsyncImageView
import io.rong.imkit.widget.ProviderContainerView
import io.rong.imkit.widget.adapter.ConversationListAdapter
import io.rong.imkit.widget.provider.IContainerItemProvider
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/2/26
 * email：526309416@qq.com
 * desc：自定义消息列表
 */
class ConversationListAdapterEx(var mContext: Context) : ConversationListAdapter(mContext) {

    private var mOnPortraitItemClick: ConversationListAdapter.OnPortraitItemClick? = null

    public override fun newView(context: Context?, position: Int, group: ViewGroup?): View {
        val itemView = LayoutInflater.from(mContext).inflate(R.layout.rc_item_conversation_ex, group, false)
        val viewHolder = ViewHolder(itemView)
        itemView.tag = viewHolder
        return itemView
    }

    public override fun bindView(v: View, position: Int, data: UIConversation?) {
        val holder = v.tag as ViewHolder
        if (data != null) {
            val provider = RongContext.getInstance().getConversationTemplate(data.conversationType.getName())
            if (provider == null) {
                RLog.e("ConversationListAdapter", "provider is null")
            } else {
                val view = holder.contentView.inflate<IContainerItemProvider.ConversationProvider<*>>(provider)
                provider.bindView(view, position, data)
                if (data.isTop) {
                    holder.layout.setBackgroundResource(R.drawable.rc_item_top_list_selector)
                } else {
                    holder.layout.setBackgroundResource(R.drawable.rc_item_list_selector)
                }

                holder.layout.setOnClickListener { v1 -> mOnPortraitItemClick?.onPortraitItemClick(v1, data) }
                holder.layout.setOnLongClickListener { v -> mOnPortraitItemClick?.onPortraitItemLongClick(v, data)!! }

                val defaultId: Int = when {
                    data.conversationType == Conversation.ConversationType.GROUP -> {
                        holder.tvTag.visible()
                        R.drawable.rc_default_group_portrait
                    }

                    data.conversationType == Conversation.ConversationType.DISCUSSION -> {
                        holder.tvTag.visible()
                        R.drawable.rc_default_discussion_portrait
                    }
                    data.conversationType == Conversation.ConversationType.PRIVATE -> {
                        holder.tvTag.gone()
                        R.drawable.rc_default_portrait
                    }
                    else -> R.drawable.rc_default_portrait
                }
                when {
                    data.conversationGatherState -> holder.leftImageView.setAvatar(null, defaultId)
                    data.iconUrl != null -> holder.leftImageView.setAvatar(data.iconUrl.toString(), defaultId)
                    else -> holder.leftImageView.setAvatar(null, defaultId)
                }

                if (data.unReadMessageCount > 0) {
                    if (data.unReadMessageCount > 99) {
                        holder.rightUnReadView.text = "99+"
                    } else {
                        holder.rightUnReadView.text = Integer.toString(data.unReadMessageCount)
                    }
                    holder.rightUnReadView.visibility = View.VISIBLE
                } else {
                    holder.rightUnReadView.visibility = View.GONE
                }

                val content = data.messageContent
                if (content != null && content.isDestruct) {
                    RongIMClient.getInstance().getMessage(data.latestMessageId, object : RongIMClient.ResultCallback<Message>() {

                        override fun onSuccess(message: Message?) {
                            if (message == null) {
                                EventBus.getDefault().post(Event.MessageDeleteEvent(data.latestMessageId))
                            } else if (message.readTime > 0L) {
                                val readTime = message.readTime
                                val serverTime = System.currentTimeMillis() - RongIMClient.getInstance().deltaTime
                                val delay = message.content.destructTime - (serverTime - readTime) / 1000L
                                if (delay > 0L) {
                                    RongIM.getInstance().createDestructionTask(message, null, ConversationListFragment.TAG)
                                } else {
                                    EventBus.getDefault().post(Event.DestructionEvent(message))
                                }
                            }
                        }

                        override fun onError(e: RongIMClient.ErrorCode) {}
                    })
                }
            }
        }
    }

    override fun notifyDataSetChanged() {
        super.notifyDataSetChanged()
    }
//    override fun add(t: UIConversation?) {
//        if (!Const.SERVICE_ID.equals(t?.conversationTargetId)) {
//            super.add(t)
//        }
//    }
//
//    override fun add(t: UIConversation?, position: Int) {
//        if (!Const.SERVICE_ID.equals(t?.conversationTargetId)) {
//            super.add(t, position)
//        }
//    }
//
//    override fun addCollection(collection: MutableCollection<UIConversation>?) {
//        super.addCollection(collection?.filter {
//            !Const.SERVICE_ID.equals(it.conversationTargetId)
//        })
//    }
//
//    override fun addCollection(vararg collection: UIConversation?) {
//        super.addCollection(collection.filter {
//            !Const.SERVICE_ID.equals(it?.conversationTargetId)
//        })
//    }

    private class ViewHolder(itemView: View) {
        var layout: View = itemView.findViewById(R.id.rc_item_conversation)
        var rightUnReadView: TextView = itemView.findViewById(R.id.tv_unread)
        var leftImageView: AsyncImageView = itemView.findViewById(R.id.rc_left)
        var contentView: ProviderContainerView = itemView.findViewById(R.id.rc_content)
        var tvTag: TextView = itemView.findViewById(R.id.iv_tag)
    }

    override fun setOnPortraitItemClick(onPortraitItemClick: ConversationListAdapter.OnPortraitItemClick?) {
        super.setOnPortraitItemClick(onPortraitItemClick)
        this.mOnPortraitItemClick = onPortraitItemClick
    }
}