package com.bc_chat.contacts.ui.search

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
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.entity.UserInfo
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.contacts.adapter.SearchContactListAdapter
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
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.activities.ContactDetailActivity.REQUSET_CONTACT_DETAIL
import io.rong.contactcard.message.ContactMessage
import io.rong.imkit.RongIM
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/3/15
 * email：526309416@qq.com
 * desc：联系人搜索
 */
@Route(path = RouteConfig.CONTACT_SEARCH_ACTIVITY)
class ContactSearchActivity : SearchActivity(), Observer<String>, AbsRecyclerAdapter.OnItemClickListener {

    private var allContactsList: ArrayList<UserInfo>? = null
    private var adapterContactsList: ArrayList<UserInfo>? = null
    private var forwardSelectMsgs: ArrayList<Message>? = null
    private var action: String? = null

    override fun init() {
        allContactsList = intent.getParcelableArrayListExtra<UserInfo>("contactsList")
        forwardSelectMsgs = intent.getParcelableArrayListExtra<Message>("selectList")
        action = intent.getStringExtra("action")
        adapterContactsList = arrayListOf()
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }

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

    override fun getAdapter(): RecyclerView.Adapter<*>? {
        val searchContactListAdapter = SearchContactListAdapter(this, adapterContactsList as List<UserInfo>)
        searchContactListAdapter.addOnItemClickListener(this)
        return searchContactListAdapter
    }

    override fun query(query: String?) {
        adapterContactsList?.clear()
        if (!query.isNullOrEmpty()) {
            allContactsList?.forEach {
                if (it.nickname!!.contains(query!!) || it.remark!!.contains(query)) {
                    adapterContactsList?.add(it)
                }
            }
        }
        mAdapter?.notifyDataSetChanged()
    }

    override fun onItemClick(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val contacts = (mAdapter as SearchContactListAdapter).data[position]
        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", Conversation.ConversationType.PRIVATE)
                intent.putExtra("targetId", contacts.userId!!)
                intent.putExtra("title", contacts.remark ?: contacts.nickname!!)
                intent.putExtra("action", Const.Action.FORWARD_MESSAGE)
                startActivityForResult(intent, REQUSET_CONTACT_DETAIL)
                return
            }
            CustomDialog.Builder(this)
                    .setMessage("您确定要转发该信息?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        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(contacts.userId!!, Conversation.ConversationType.PRIVATE, content, "${sendUserName}转发了一条消息")
                        }
                        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FORWARD_MESSAGE, contacts.userId!!)
                        ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.PRIVATE, contacts.userId!!, contacts.remark
                                ?: contacts.nickname!!, null)
                    }
                    .create().show()


        } else {
//            ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.PRIVATE, contacts.userId!!, contacts.remark
//                    ?: contacts.nickname!!, null)
            ARouter.getInstance().build(RouteConfig.USER_INFO_DETAILS_ACTIVITY).withString("userId", contacts.userId).withString("userName", contacts.remark
                    ?: contacts.nickname)
                    .navigation()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 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)
    }
}