package com.bc_chat.im.fragment.forword

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
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.bc_base.utils.gone
import com.bc_chat.im.R
import com.bc_chat.im.adapter.ConversationListAdapterEx
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.fragment.ConversationListFragment
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
import io.rong.imlib.model.UserInfo
import kotlinx.android.synthetic.main.header_msgs_conversation.view.*
import org.jetbrains.anko.find

/**
 * author：Created by zhaohaoting on 2019/2/26
 * email：526309416@qq.com
 * desc：会话联系人
 */
class ForwardConversationListFragment : ConversationListFragment() {

    private lateinit var rcList: ListView

    private var forwardSelectMsgs: ArrayList<Message>? = null
    private var headerView: View? = null
    private var sendUserInfo: UserInfo? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        forwardSelectMsgs = arguments?.getParcelableArrayList<Message>("selectList")
        sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rcList = view.find(R.id.rc_list)
        headerView = layoutInflater.inflate(R.layout.header_msgs_forward_conversation, rcList, false)
        rcList.addHeaderView(headerView)
        //先隐藏融云有的emptyView
        rcList.emptyView?.gone()
        //再清除sdk 的emptyView
        rcList.emptyView = null
        headerView?.rl_search?.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.SEARCH_CONVERSATION_ACTIVITY).withParcelableArrayList("selectList", forwardSelectMsgs).withString("action", Const.Action.FORWARD_MESSAGE)
                    .navigation()
        }
    }

    override fun onResolveAdapter(context: Context): ConversationListAdapter {
        return ConversationListAdapterEx(context)
    }

    override fun onPortraitItemClick(v: View, data: UIConversation) {
        val type = data.conversationType
        if (this.getGatherState(type)) {
            RongIM.getInstance().startSubConversationList(this.activity!!, type)
        } else {
            val message = forwardSelectMsgs!![0]
            val content = message.content
            if (content is ContactMessage) {
                val intent = Intent(activity, ContactDetailActivity::class.java)
                intent.putExtra("contact", io.rong.imlib.model.UserInfo(content.id, content.name, Uri.parse(content.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(context)
                    .setMessage("您确定要转发该信息?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        data.unReadMessageCount = 0
                        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!!)
                        RongIM.getInstance().startConversation(this.activity!!, type, data.conversationTargetId, data.uiConversationTitle)
                    }
                    .create().show()

        }
    }

//    override fun shouldFilterConversation(type: Conversation.ConversationType?, targetId: String?): Boolean {
//        return type == Conversation.ConversationType.SYSTEM || (type == Conversation.ConversationType.PRIVATE && Const.SERVICE_ID.equals(targetId))
//    }

    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);
        }
    }
}