package com.bc_chat.contacts.ui.search

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.contacts.adapter.ConversationRecyclerAdapter
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.contactcard.activities.ContactDetailActivity
import io.rong.contactcard.message.ContactMessage
import io.rong.imkit.RongIM
import io.rong.imkit.model.UIConversation
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imkit.widget.adapter.ConversationListAdapter
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/3/14
 * email：526309416@qq.com
 * desc：最近联系人搜索
 */
@Route(path = RouteConfig.SEARCH_CONVERSATION_ACTIVITY)
class ConversationSearchActivity : SearchActivity(), ConversationListAdapter.OnPortraitItemClick, Observer<String> {


    private var allConversationList: ArrayList<UIConversation>? = null
    private var adapterConversationList: ArrayList<UIConversation>? = null

    private var forwardSelectMsgs: ArrayList<Message>? = null

    private var action: String? = null

    private val conversationTypes: Array<Conversation.ConversationType> =
            arrayOf(Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP,
                    Conversation.ConversationType.DISCUSSION, Conversation.ConversationType.SYSTEM,
                    Conversation.ConversationType.CUSTOMER_SERVICE, Conversation.ConversationType.CHATROOM,
                    Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE,
                    Conversation.ConversationType.ENCRYPTED)

    override fun init() {
        allConversationList = arrayListOf()
        adapterConversationList = arrayListOf()
        getConversationList(conversationTypes)
        action = intent.getStringExtra("action")
        forwardSelectMsgs = intent.getParcelableArrayListExtra<Message>("selectList")
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }

    override fun onEvent(key: String?, var1: String?) {
        finish()
    }

    override fun onPortraitItemClick(p0: View?, data: UIConversation) {
        val type = data.conversationType
        if (Const.Action.FORWARD_MESSAGE.equals(action)) {
            val message = forwardSelectMsgs!![0]
            val contactMessage = message.content
            if (contactMessage is ContactMessage) {
                val intent = Intent(this, ContactDetailActivity::class.java)
                intent.putExtra("contact", io.rong.imlib.model.UserInfo(contactMessage.id, contactMessage.name, Uri.parse(contactMessage.imgUrl)))
                intent.putExtra("conversationType", type)
                intent.putExtra("targetId", data.conversationTargetId!!)
                intent.putExtra("title", data.uiConversationTitle)
                intent.putExtra("action", Const.Action.FORWARD_MESSAGE)
                startActivityForResult(intent, ContactDetailActivity.REQUSET_CONTACT_DETAIL)
                return
            }
            CustomDialog.Builder(this)
                    .setMessage("您确定要转发该信息?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        data.unReadMessageCount = 0
                        val sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
                        forwardSelectMsgs?.forEach {
                            val content = it.content
                            content.userInfo = sendUserInfo
                            it.senderUserId = RongIMClient.getInstance().currentUserId
                            val sendUserName = if (sendUserInfo == null) "" else sendUserInfo?.name
                            ARouter.getInstance().navigation(ImRongService::class.java).sendMessage(data.conversationTargetId!!, type, content, "${sendUserName}转发了一条消息")
                        }
                        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FORWARD_MESSAGE, data.conversationTargetId!!)
                        ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, type, data.conversationTargetId!!, data.uiConversationTitle, null)
                    }
                    .create().show()
        } else {
            ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, type, data.conversationTargetId!!, data.uiConversationTitle, null)
        }
    }

    override fun onPortraitItemLongClick(p0: View?, p1: UIConversation?): Boolean {
        return true
    }

    override fun getAdapter(): RecyclerView.Adapter<*> {
        val conversationRecylearAdapter = ConversationRecyclerAdapter(this, adapterConversationList)
        conversationRecylearAdapter.setOnPortraitItemClick(this)
        return conversationRecylearAdapter
    }

    override fun query(query: String?) {
        adapterConversationList?.clear()
        if (!query.isNullOrEmpty()) {
            allConversationList?.forEach {
                if (it.conversationType == Conversation.ConversationType.GROUP) {
                    val groupInfo = RongUserInfoManager.getInstance().getGroupInfo(it.conversationTargetId)
                    if (groupInfo != null) {
                        if (groupInfo.name.contains(query!!)) {
                            adapterConversationList?.add(it)
                        }
                    }
                } else if (it.conversationType == Conversation.ConversationType.PRIVATE) {
                    val userInfo = RongUserInfoManager.getInstance().getUserInfo(it.conversationTargetId)
                    if (userInfo != null) {
                        if (userInfo.name.contains(query!!)) {
                            adapterConversationList?.add(it)
                        }
                    }
                }
            }
        }
        mAdapter?.notifyDataSetChanged()
    }

    private fun getConversationList(conversationTypes: Array<Conversation.ConversationType>) {
        RongIMClient.getInstance().getConversationList(object : RongIMClient.ResultCallback<List<Conversation>>() {
            override fun onSuccess(conversations: List<Conversation>?) {
                if (conversations != null) {
                    makeUiConversationList(conversations)
                }
            }

            override fun onError(e: RongIMClient.ErrorCode) {

            }
        }, *conversationTypes)
    }

    private fun makeUiConversationList(conversationList: List<Conversation>) {
        allConversationList?.clear()
        val var3 = conversationList.iterator()
        while (var3.hasNext()) {
            val conversation = var3.next()
//            if (!(conversation.conversationType == Conversation.ConversationType.SYSTEM || (conversation.conversationType == Conversation.ConversationType.PRIVATE && Const.SERVICE_ID.equals(conversation.targetId)))) {
                val uiConversation: UIConversation = UIConversation.obtain(this, conversation, false)
                allConversationList?.add(uiConversation)
//            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == ContactDetailActivity.REQUSET_CONTACT_DETAIL) {
            val mConversationType = data?.getSerializableExtra("type") as Conversation.ConversationType
            val targetId = data.getStringExtra("targetId")
            val title = data.getStringExtra("title")
            RongIM.getInstance().startConversation(this, mConversationType, targetId, title)
            ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FORWARD_MESSAGE, targetId);
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }
}
