package com.bc_chat.im.fragment.forword

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.View
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.ListModel
import com.bc_chat.bc_base.entity.contact.Contacts
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.im.R
import com.bc_chat.im.adapter.ForwardContactListAdapter
import com.bc_chat.im.dataSource.ForwardContactDataSource
import com.zhaohaoting.framework.abs.BaseRecyclerFragment
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.ui.dialog.CustomDialog
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_forward_contact.view.*

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：转发联系人
 */
class ForwardContactFragment : BaseRecyclerFragment<Contacts, ListModel<Contacts>>() {

    private var forwardSelectMsgs: ArrayList<Message>? = null

    override fun getAdapter(): AbsRecyclerAdapter<Contacts, ListModel<Contacts>> = ForwardContactListAdapter(activity)

    override fun getDataSource(): IAsyncDataSource<ListModel<Contacts>> = ForwardContactDataSource()

    override fun onInit() {
        isVisibleToUser = true
        forwardSelectMsgs = arguments?.getParcelableArrayList<Message>("selectList")
    }

    override fun addHeadViews(adapter: AbsRecyclerAdapter<Contacts, ListModel<Contacts>>) {
        val headView = View.inflate(activity, R.layout.head_layout_forward_contact, null)
        adapter.addHeaderView(headView)
        headView.tv_group_contact.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.GROUP_LIST_ACTIVITY)
                    .withParcelableArrayList("selectList", forwardSelectMsgs)
                    .withString("action", Const.Action.FORWARD_MESSAGE)
                    .navigation()
        }
        headView.rl_search.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.CONTACT_SEARCH_ACTIVITY)
                    .withParcelableArrayList("selectList", forwardSelectMsgs)
                    .withParcelableArrayList("contactsList", adapter.data.list as ArrayList)
                    .withString("action", Const.Action.FORWARD_MESSAGE)
                    .navigation()
        }
    }

    override fun itemClicked(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val contacts = adapter.data.list[position]
        val message = forwardSelectMsgs!![0]
        val contactMessage = message.content
        if (contactMessage is ContactMessage) {
            val intent = Intent(activity, 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,ContactDetailActivity.REQUSET_CONTACT_DETAIL)
            return
        }
        CustomDialog.Builder(context)
                .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(activity, Conversation.ConversationType.PRIVATE, contacts.userId!!, contacts.remark
                            ?: contacts.nickname!!, null)
                }
                .create().show()

    }

    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(activity, mConversationType, targetId, title)
            ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FORWARD_MESSAGE, targetId);
        }
    }
}
