package com.bc_chat.contacts.ui.group

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.Menu
import android.view.MenuItem
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.entity.group.Group
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.GroupListAdapter
import com.bc_chat.contacts.dataSource.GroupDataSource
import com.zhaohaoting.framework.abs.BaseRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.mvchelper.mvc.IDataAdapter
import com.zhaohaoting.framework.mvchelper.mvc.OnRefreshEndListener
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.Utils
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.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import kotlinx.android.synthetic.main.head_layout_group.view.*

/**
 * author：Created by zhaohaoting on 2019/3/1
 * email：526309416@qq.com
 * desc：群列表
 */
@Route(path = RouteConfig.GROUP_LIST_ACTIVITY)
class GroupListActivity : BaseRecyclerActivity<Group, List<Group>>(), OnRefreshEndListener<List<Group>>, Observer<String> {

    private var headView: View? = null
    private var selectMsgs: ArrayList<Message>? = null
    private var action: String? = null

    override fun onInit() {
        setOnStateChangeListener(this)
        selectMsgs = intent.getParcelableArrayListExtra<Message>("selectList")
        action = intent.getStringExtra("action")
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.CREATE_GROUP, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.EXIT_GROUP, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.DISSOLUTION_GROUP, this)
    }

    override fun getAdapter(): AbsRecyclerAdapter<Group, List<Group>> = GroupListAdapter(this)

    override fun getDataSource(): IAsyncDataSource<List<Group>> = GroupDataSource()

    override fun addHeadViews(adapter: AbsRecyclerAdapter<Group, List<Group>>?) {
        headView = View.inflate(this, R.layout.head_layout_group, null)
        adapter?.addHeaderView(headView)
        if (Const.Action.FORWARD_MESSAGE.equals(action)) { //转发跳转
            headView?.tv_add_group_chat.gone()
        }
        headView?.tv_add_group_chat?.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.CHOOSE_FRIEND_ACTIVITY).withString("action", Const.Action.CREATE_GROUP).navigation()
        }
    }

    override fun onEndRefresh(adapter: IDataAdapter<List<Group>>?, result: List<Group>?) {
        if (!Utils.listIsEmpty(result)) {
            headView?.tv_group_num?.text = getString(R.string._group_num, result?.size)
            headView?.tv_group_num?.visible()
        } else {
            headView?.tv_group_num?.gone()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        if (Const.Action.FORWARD_MESSAGE.equals(action)) {
            return true
        }
        menu.add("").setIcon(R.mipmap.ic_white_search).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        ARouter.getInstance().build(RouteConfig.GROUP_SEARCH_ACTIVITY).withParcelableArrayList("groupList", adapter.data as java.util.ArrayList).navigation()
        return true
    }

    override fun onEvent(key: String?, var1: String?) {
        when (key) {
            Const.ObserverKey.FORWARD_MESSAGE -> finish()
            Const.ObserverKey.CREATE_GROUP -> refresh()
            Const.ObserverKey.EXIT_GROUP -> refresh()
            Const.ObserverKey.DISSOLUTION_GROUP -> refresh()
        }
    }

    override fun onItemClick(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val group = adapter.data[position]
        if (Const.Action.FORWARD_MESSAGE.equals(action)) {
            val message = selectMsgs!![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.GROUP)
                intent.putExtra("targetId", group.groupId!!)
                intent.putExtra("title", group.group_name!!)
                intent.putExtra("action", Const.Action.FORWARD_MESSAGE)
                startActivityForResult(intent, ContactDetailActivity.REQUSET_CONTACT_DETAIL)
                return
            }
            CustomDialog.Builder(this)
                    .setMessage("您确定要转发该信息?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        val sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
                        selectMsgs?.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(group.groupId!!, Conversation.ConversationType.GROUP, content, "${sendUserName}转发了一条消息")
                        }
                        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FORWARD_MESSAGE, group.groupId!!)
                        ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.GROUP, group.groupId!!, group.group_name!!, null)
                    }
                    .create().show()
        } else {
            ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.GROUP, group.groupId!!, group.group_name!!, null)
        }
    }

    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)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.CREATE_GROUP, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.EXIT_GROUP, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.DISSOLUTION_GROUP, this)

    }
}