package com.bc_chat.im.service

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.TipsMessage
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.User
import com.bc_chat.bc_base.entity.dao.GroupMemberDao
import com.bc_chat.bc_base.entity.group.MemberBean
import com.bc_chat.bc_base.task.GroupInfoTask
import com.bc_chat.bc_base.task.GroupMemberDataSource
import com.bc_chat.bc_base.task.UserInfoTask
import com.bc_chat.bc_base.utils.AppConfig
import com.bc_chat.bc_base.utils.Badger
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.im.chat.ChatUtil
import com.bc_chat.im.dataSource.CollectionTask
import com.bc_chat.im.messages.ContactNotificationMessageProvider
import com.bc_chat.im.messages.RecallMessageItemProvider
import com.bc_chat.im.messages.collection.CollectionExtensioModule
import com.bc_chat.im.messages.gif.GIFMessage
import com.bc_chat.im.messages.gif.GIFMessageItemProvider
import com.bc_chat.im.messages.systen.*
import com.bc_chat.im.messages.vibration.RCVibrationMessage
import com.bc_chat.im.messages.vibration.VibrationExtensioModule
import com.bc_chat.im.module.SampleExtensionModule
import com.bc_chat.im.plug.AudioExtensioModule
import com.bc_chat.im.plug.LocationExtensioModule
import com.bc_chat.im.redpackage.MRedPackgeExtensionModule
import com.google.gson.JsonObject
import com.jrmf360.rylib.JrmfClient
import com.zhaohaoting.framework.mvchelper.okhttp.exception.RequestException
import com.zhaohaoting.framework.mvchelper.task.TaskHelper
import com.zhaohaoting.framework.requset.NetWorkCallBack
import com.zhaohaoting.framework.utils.Logger
import com.zhaohaoting.framework.utils.Preferences
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.callkit.RongCallKit
import io.rong.common.FileUtils
import io.rong.common.RLog
import io.rong.contactcard.ContactCardExtensionModule
import io.rong.contactcard.IContactCardClickListener
import io.rong.contactcard.IContactCardInfoProvider
import io.rong.contactcard.message.ContactMessage
import io.rong.imkit.*
import io.rong.imkit.manager.IUnReadMessageObserver
import io.rong.imkit.mention.IMentionedInputListener
import io.rong.imkit.mention.RongMentionManager
import io.rong.imkit.model.ConversationInfo
import io.rong.imkit.model.Event
import io.rong.imkit.model.GroupUserInfo
import io.rong.imkit.model.UIMessage
import io.rong.imkit.notification.MessageNotificationManager
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imkit.widget.provider.MessageItemLongClickAction
import io.rong.imkit.widget.provider.SightMessageItemProvider
import io.rong.imlib.IRongCallback
import io.rong.imlib.MessageTag
import io.rong.imlib.RongIMClient
import io.rong.imlib.location.message.RealTimeLocationStartMessage
import io.rong.imlib.model.*
import io.rong.message.*
import io.rong.push.RongPushClient
import io.rong.push.pushconfig.PushConfig
import io.rong.sight.SightExtensionModule
import org.json.JSONObject
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/25
 * email：526309416@qq.com
 * desc：
 */
@Route(path = RouteConfig.CHAT_RONG_SERVICE)
class ImRongHelper : ImRongService, RongIMClient.OnReceiveMessageListener, RongIM.OnSendMessageListener,
        RongIMClient.OnRecallMessageListener, RongIMClient.ConnectionStatusListener, IUnReadMessageObserver,
        RongIM.UserInfoProvider, RongIM.GroupUserInfoProvider, RongIM.GroupInfoProvider, RongIM.IGroupMembersProvider,
        RongCallKit.GroupMembersProvider, RongIM.ConversationClickListener, IMentionedInputListener {

    private var context: Context? = null
    private var taskHelper: TaskHelper<Any>? = null
    private val handler: Handler = Handler(Looper.getMainLooper())


    override fun init(context: Context?) {
        this.context = context
        taskHelper = TaskHelper()
    }

    override fun initRongIm(context: Context) {
        val builder = PushConfig.Builder()
                .enableOppoPush(Const.App.OPPO_APPKEY, Const.App.OPPO_APPSECRET)
                .enableHWPush(true)
                .enableMiPush(Const.App.XIAOMI_APPID, Const.App.XIAOMI_APPKEY)
                .enableVivoPush(true)
                .enableFCM(true) //配置 FCM 推送
                .enableMeiZuPush(Const.App.MEIZU_APPID, Const.App.MEIZU_APPKEY) //配置魅族推送
        RongPushClient.setPushConfig(builder.build())
        RongIM.init(context)
        setMyExtensionModule()
        RongIM.getInstance().setMessageAttachedUserInfo(true)
        RongIM.getInstance().setSendMessageListener(this)

        //hxm
        //自定义系统消息
        RongIM.registerMessageType(RCSysMessage::class.java)
        RongIM.registerMessageTemplate(RCSysMessageProvider())

        RongIM.registerMessageType(TipsMessage::class.java)

        RongIM.registerMessageType(RCNoticeMessage::class.java)
        RongIM.registerMessageTemplate(RCNoticeMessageProvider())

        RongContext.getInstance().showUnreadMessageIcon(true)
        RongContext.getInstance().showNewMessageIcon(true)

        //好友通知
        RongIM.registerMessageTemplate(ContactNotificationMessageProvider())
        //添加短视频
        RongIM.registerMessageType(SightMessage::class.java)
        RongIM.registerMessageTemplate(SightMessageItemProvider())
        //重写撤回消息
        RongIM.registerMessageTemplate(RecallMessageItemProvider())
        //重写文本消息
        RongIM.registerMessageTemplate(TextMessageItemProvider())
        //添加gif
        RongIM.registerMessageType(GIFMessage::class.java)
        RongIM.registerMessageTemplate(GIFMessageItemProvider())

        initMessageItemLongClickAction()
        setInputProvider()
        RongIM.setConnectionStatusListener(this)

        RongIMClient.setOnRecallMessageListener(this)
        RongMentionManager.getInstance().setMentionedInputListener(this)
        RongMentionManager.getInstance().groupMembersProvider = this
        RongIM.getInstance().addUnReadMessageCountChangedObserver(
                this,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.SYSTEM
        )
    }

    override fun onMentionedInput(p0: Conversation.ConversationType?, p1: String?): Boolean {
        ARouter.getInstance().build(RouteConfig.CHOOSE_FRIEND_ACTIVITY)
                .withString("action", Const.Action.ALTER_GROUP_MEMBER)
                .withString("groupId", p1)
                .navigation()
        return true
    }

    override fun onCountChanged(p0: Int) {
        getUnreadMsgCount()
    }

    /**
     * 登录
     */
    override fun loginIM(uid: String?, token: String?, observer: Observer<Boolean>) {
        val status = RongIM.getInstance().currentConnectionStatus
        if (status != RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            RongIM.connect(token, object : RongIMClient.ConnectCallback() {
                override fun onSuccess(p0: String?) {
                    Logger.e("connection-------------------------->", "聊天服务器连接成功")
                    Preferences.saveString(Const.LAST_LOGIN_USER_ID, uid)
                    setCurrentUserInfo(uid, token)
                    observer.onEvent(Const.ObserverKey.USER_LOGIN, true)
                }

                override fun onError(p0: RongIMClient.ErrorCode?) {
                    observer.onEvent(Const.ObserverKey.USER_LOGIN, false)
                }

                override fun onTokenIncorrect() {
                    observer.onEvent(Const.ObserverKey.USER_LOGIN, false)
                }
            })
        } else {
            observer.onEvent(Const.ObserverKey.USER_LOGIN, true)
        }
    }

    /**
     * 缓存用户信息
     */
    override fun setCurrentUserInfo(uid: String?, token: String?) {
        if (RongIM.getInstance().currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            val saveUser = AppConfig.instance.getUser()

            val userInfo = UserInfo(uid, saveUser.nickname, Uri.parse(saveUser.photo))
            RongIM.getInstance().refreshUserInfoCache(userInfo)
            RongIM.getInstance().setCurrentUserInfo(userInfo)

            saveUser.userId = uid!!
            saveUser.accessToken = token
            GroupMemberDao.instance.saveUserInfo(saveUser)
        }
    }

    /**
     * 获取未读
     */
    override fun getUnreadMsgCount() {
        RongIM.getInstance().getUnreadCount(
                object : RongIMClient.ResultCallback<Int>() {
                    override fun onSuccess(p0: Int) {
                        Logger.e("getUnreadMsgCount———————>>", "" + p0)
                        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.UN_READ_CHANGE, p0)
                        if (p0 >= 99) {
                            Badger.updateBadgerCount(99)
                        } else {
                            Badger.updateBadgerCount(p0)
                        }
                    }

                    override fun onError(p0: RongIMClient.ErrorCode?) {
                    }

                },
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.SYSTEM
        )
    }

    override fun sendMessage(
            targetId: String,
            conversationType: Conversation.ConversationType,
            content: MessageContent,
            pushConten: String?,
            pushData: String?,
            observer: Observer<Boolean>?
    ) {
        RongIM.getInstance().sendMessage(Message.obtain(targetId, conversationType, content), pushConten, pushData,
                object : IRongCallback.ISendMessageCallback {
                    override fun onAttached(message: Message) {

                    }

                    override fun onSuccess(message: Message) {
                        observer?.onEvent(Const.ObserverKey.SEND_MESSAGE_RESULT, true)
                    }

                    override fun onError(message: Message, errorCode: RongIMClient.ErrorCode) {
                        observer?.onEvent(Const.ObserverKey.SEND_MESSAGE_RESULT, false)
                    }
                })
    }

    /**
     * 退出登录
     */
    @SuppressLint("WrongConstant")
    override fun loginOut(context: Context) {
        RongIM.getInstance().logout()
        Preferences.saveString(Const.LAST_LOGIN_USER_ID, "0")
        AppConfig.instance.deleteUser()
        ARouter.getInstance().build(RouteConfig.LOGIN_ACTIVITY)
                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
    }

    /**
     * 钱包
     */
    override fun navigationWallet(activity: Activity) {
        JrmfClient.intentWallet(activity)
    }

    /**
     * 跳转
     */
    override fun startConversation(
            context: Context,
            conversationType: Conversation.ConversationType,
            targetId: String,
            title: String,
            bundle: Bundle?
    ) {
        if (!TextUtils.isEmpty(targetId)) {
            val uri = Uri.parse("rong://" + context.applicationInfo.processName).buildUpon().appendPath("conversation")
                    .appendPath(conversationType.getName().toLowerCase(Locale.US))
                    .appendQueryParameter("targetId", targetId).appendQueryParameter("title", title).build()
            val intent = Intent(Intent.ACTION_VIEW, uri)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            if (bundle != null) {
                intent.putExtras(bundle)
            }
            context.startActivity(intent)
        } else {
            throw IllegalArgumentException()
        }
    }

    /**
     * 收到撤回指令
     */
    override fun onMessageRecalled(message: Message?, recallNotificationMessage: RecallNotificationMessage?): Boolean {
        RongContext.getInstance().eventBus.post(
                Event.RemoteMessageRecallEvent(
                        message?.messageId!!,
                        message.conversationType,
                        recallNotificationMessage,
                        true,
                        message.targetId
                )
        )
        val msgTag = recallNotificationMessage!!.javaClass.getAnnotation(MessageTag::class.java) as MessageTag
        if (msgTag != null && (msgTag.flag == MessageTag.ISCOUNTED || msgTag.flag == MessageTag.ISPERSISTED)) {
            MessageNotificationManager.getInstance().notifyIfNeed(RongContext.getInstance(), message, 0)
        }
        return true
    }

    /**
     * 连接状态
     */
    override fun onChanged(status: RongIMClient.ConnectionStatusListener.ConnectionStatus?) {
        if (status == RongIMClient.ConnectionStatusListener.ConnectionStatus.TOKEN_INCORRECT) {
            val cacheToken = AppConfig.instance.getUser().accessToken
            if (!TextUtils.isEmpty(cacheToken)) {
                RongIM.connect(cacheToken, object : RongIMClient.ConnectCallback() {
                    override fun onSuccess(p0: String?) {
                        Logger.e("connection-------------------------->", "聊天服务器连接成功")
                    }

                    override fun onError(p0: RongIMClient.ErrorCode?) {
                    }

                    override fun onTokenIncorrect() {
                    }
                })
            } else {
                Log.e("seal", "token is empty, can not reconnect")
            }
        } else if (status == RongIMClient.ConnectionStatusListener.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT) {
            quit()
        }
    }

    @SuppressLint("WrongConstant")
    private fun quit() {
        handler.post {
            RongIM.getInstance().logout()
            Preferences.saveString(Const.LAST_LOGIN_USER_ID, "0")
            ARouter.getInstance().build(RouteConfig.LOGIN_ACTIVITY).withString("action", Const.Action.NEED_LOGIN)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
        }
    }

    /**
     * 消息发送成功
     */
    override fun onSend(p0: Message?): Message? {
        val mentionedInfo = MentionedInfo(MentionedInfo.MentionedType.ALL, null, null);
        val mentionedInfo1 = p0?.content?.mentionedInfo
        val mentionedUserIdList = mentionedInfo1?.mentionedUserIdList
        mentionedUserIdList?.let {
            if (it.contains("0")) {
                p0.content?.mentionedInfo = mentionedInfo
            }
        }
        return p0
    }

    override fun onSent(p0: Message?, p1: RongIM.SentMessageErrorCode?): Boolean {
        return true
    }

    /**
     * 收消息
     */
    override fun onReceived(p0: Message?, p1: Int): Boolean {
        if (p0?.senderUserId == Const.SERVICE_ID) { //处理系统消息
            if (p0.conversationType == Conversation.ConversationType.SYSTEM) {
            } else if (p0.conversationType == Conversation.ConversationType.PRIVATE) {
            }
        }

        if (p0?.content is TipsMessage) {

            var tipsMessage = p0?.content as TipsMessage;
            if (tipsMessage.type.toInt() == 1) {
                //好友请求更新
                ObserverManager.getInstance().notifyObserver(Const.ObserverKey.NEW_FRIEND, "add")
            } else if (tipsMessage.type.toInt() == 2) {
                //群组踢人不提示
                ObserverManager.getInstance().notifyObserver(Const.ObserverKey.GROUP_KICKING, tipsMessage.content)
            } else if (tipsMessage.type.toInt() == 3) {

            }
            return true;
        }
        if (p0?.content is GroupNotificationMessage) {
            //群消息，屏蔽邀请入群通知
            if (ChatUtil.isGroupInvite(p0)) {
                ChatUtil.removeMessage(p0)
                return false;
            }
        }

        getUnreadMsgCount()
        //将消息分发到插件上
        val iterator = RongExtensionManager.getInstance().extensionModules.iterator()
        while (iterator.hasNext()) {
            val extensionModule = iterator.next() as IExtensionModule
            extensionModule.onReceivedMessage(p0)
        }
        if (p0?.content is RCVibrationMessage) {
            if (!isInConversationPager(p0.targetId, p0.conversationType) && isNotify(
                            p0?.sentTime!!,
                            p0.targetId,
                            p0.conversationType
                    )
            ) {
                ARouter.getInstance().build(RouteConfig.VIBRATION_DETAILS_ACTIVITY).withParcelable("message", p0)
                        .navigation()
            }
        } else if (p0?.content is RCNoticeMessage) {
            receivedNotice(p0.content as RCNoticeMessage?, p0, p1)
        } else {
            if (isNotify(p0?.sentTime!!, p0.targetId, p0.conversationType))
                MessageNotificationManager.getInstance().notifyIfNeed(RongContext.getInstance(), p0, p1)
        }
        return true
    }

    /**
     * 收到自定义通知消息
     */
    private fun receivedNotice(noticeMessage: RCNoticeMessage?, message: Message?, p1: Int) {
        noticeMessage?.let {
            Logger.e("NoticeMessage", it.content + "---------" + it.extra)
            val jsonObject = JSONObject(noticeMessage.extra)
            val type = jsonObject.optString("type")
            when (type) {
                Const.PushMethod.DISS_GROUP -> {//解散群
                    val groupId = jsonObject.optString("groupId")
                    RongIM.getInstance().clearMessages(
                            Conversation.ConversationType.GROUP,
                            groupId,
                            object : RongIMClient.ResultCallback<Boolean>() {
                                override fun onSuccess(aBoolean: Boolean?) {
                                    RongIM.getInstance()
                                            .removeConversation(Conversation.ConversationType.GROUP, groupId, null)
                                }

                                override fun onError(errorCode: RongIMClient.ErrorCode) {}
                            })
                }
                Const.PushMethod.FOLLOW_LIST -> {
                    MyMessageNotificationManager.getInstance().notifyIfNeed(RongContext.getInstance(), message)
                    ObserverManager.getInstance().notifyObserver(Const.ObserverKey.FOLLOW_TOPIC, null)
                }
                Const.PushMethod.TOPIC_COMMENT -> {
                    MyMessageNotificationManager.getInstance().notifyIfNeed(RongContext.getInstance(), message)
                    ObserverManager.getInstance().notifyObserver(Const.ObserverKey.TOPIC_COMMENT, null)
                }
                Const.PushMethod.TOPIC_CHILD_COMMENT -> {
                    MyMessageNotificationManager.getInstance().notifyIfNeed(RongContext.getInstance(), message)
                    ObserverManager.getInstance().notifyObserver(Const.ObserverKey.TOPIC_CHILD_COMMENT, null)
                }
            }
        }
    }


    override fun getUserInfo(p0: String): UserInfo? {
//        if (Const.SERVICE_ID.equals(p0)) {
//            return UserInfo(Const.SERVICE_ID, Const.SERVICE_NAME, Uri.parse("android.resource://${context?.packageName}/${com.bc_chat.im.R.mipmap.ic_sys_message}"))
//        }
        val tMember = GroupMemberDao.instance.findMemberById(p0)
        if (tMember == null) {
            taskHelper?.execute(UserInfoTask(p0), object : NetWorkCallBack<User>() {
                override fun onPostExecuteSuccess(task: Any?, data: User?) {
                }

                override fun onPostExecuteFailure(task: Any?, exception: Exception?) {
                    if (exception is RequestException && exception.code == -3) { //用户被注销
                        RongIM.getInstance().clearMessages(
                                Conversation.ConversationType.PRIVATE,
                                p0,
                                object : RongIMClient.ResultCallback<Boolean>() {
                                    override fun onSuccess(aBoolean: Boolean?) {
                                        RongIM.getInstance()
                                                .removeConversation(Conversation.ConversationType.PRIVATE, p0, null)
                                    }

                                    override fun onError(errorCode: RongIMClient.ErrorCode) {}
                                })
                    } else {
                        super.onPostExecuteFailure(task, exception)
                    }
                }
            })
            return null
        } else {
            return UserInfo(
                    tMember.userId,
                    if (TextUtils.isEmpty(tMember.remarkName)) tMember.nickName else tMember.remarkName,
                    Uri.parse(tMember.photo)
            )
        }
    }

    override fun getGroupUserInfo(p0: String, p1: String): GroupUserInfo? {
//        if (Const.SERVICE_ID.equals(p1)) {
//            return GroupUserInfo(p0, p1, Const.SERVICE_NAME)
//        }
        val tGroupMember = GroupMemberDao.instance.findGroupMemberById(p0, p1)
        if (tGroupMember == null) {
            taskHelper?.execute(UserInfoTask(p1), object : NetWorkCallBack<User>() {
                override fun onPostExecuteSuccess(task: Any?, data: User?) {
                }
            })
            return null
        } else {
            return GroupUserInfo(p0, p1, tGroupMember.groupUserName)
        }

    }

    override fun getGroupInfo(p0: String): Group? {
//        val tGroup = LitePal.where("groupId=$p0").findLast(TGroup::class.java)
        val tGroup = GroupMemberDao.instance.findGroupById(p0)
        if (tGroup == null) {
            taskHelper?.execute(GroupInfoTask(p0), object : NetWorkCallBack<com.bc_chat.bc_base.entity.group.Group>() {
                override fun onPostExecuteSuccess(task: Any?, data: com.bc_chat.bc_base.entity.group.Group?) {
                }

                override fun onPostExecuteFailure(task: Any?, exception: Exception?) {
                    if (exception is RequestException && exception.code == -3) { //群被解散
                        RongIM.getInstance().clearMessages(
                                Conversation.ConversationType.GROUP,
                                p0,
                                object : RongIMClient.ResultCallback<Boolean>() {
                                    override fun onSuccess(aBoolean: Boolean?) {
                                        RongIM.getInstance()
                                                .removeConversation(Conversation.ConversationType.GROUP, p0, null)
                                    }

                                    override fun onError(errorCode: RongIMClient.ErrorCode) {}
                                })
                    } else {
                        super.onPostExecuteFailure(task, exception)
                    }
                }
            })
            return null
        } else {
            return Group(p0, tGroup.group_name, Uri.parse(tGroup.photo))
        }
    }

    override fun getGroupMembers(p0: String?, p1: RongIM.IGroupMemberCallback?) {
        var userInfos: ArrayList<UserInfo> = ArrayList()
        taskHelper?.execute(GroupMemberDataSource(p0!!), object : NetWorkCallBack<ListModel<MemberBean>>() {
            override fun onPostExecuteSuccess(task: Any?, data: ListModel<MemberBean>?) {
                data?.let {
                    it.list?.forEach {
                        userInfos.add(
                                UserInfo(
                                        it.userId, it.remark
                                        ?: it.nickname, Uri.parse(it.photo)
                                )
                        )
                    }
                }
                p1?.onGetGroupMembersResult(userInfos)
            }
        })
    }

    override fun getMemberList(
            groupId: String?,
            result: RongCallKit.OnGroupMembersResult?
    ): java.util.ArrayList<String> {
        var userInfos: ArrayList<String> = ArrayList()
        taskHelper?.execute(GroupMemberDataSource(groupId!!), object : NetWorkCallBack<ListModel<MemberBean>>() {
            override fun onPostExecuteSuccess(task: Any?, data: ListModel<MemberBean>?) {
                data?.let {
                    it.list?.forEach {
                        userInfos.add(it.userId!!)
                    }
                }
                result?.onGotMemberList(userInfos)
            }
        })
        return userInfos
    }

    override fun clearMessages(
            conversationType: Conversation.ConversationType,
            targetId: String,
            listener: (isSuccess: Boolean) -> Unit
    ) {
        RongIM.getInstance().clearMessages(conversationType, targetId, object : RongIMClient.ResultCallback<Boolean>() {
            override fun onSuccess(aBoolean: Boolean?) {
                listener(true)

            }

            override fun onError(e: RongIMClient.ErrorCode) {
                listener(false)

            }
        })
    }

    override fun removeConversation(
            conversationType: Conversation.ConversationType,
            targetId: String,
            listener: (isSuccess: Boolean) -> Unit
    ) {
        RongIM.getInstance()
                .removeConversation(conversationType, targetId, object : RongIMClient.ResultCallback<Boolean>() {
                    override fun onSuccess(aBoolean: Boolean?) {
                        listener(true)

                    }

                    override fun onError(e: RongIMClient.ErrorCode) {
                        listener(false)

                    }
                })
    }

    override fun onUserPortraitLongClick(
            p0: Context?,
            p1: Conversation.ConversationType?,
            p2: UserInfo?,
            p3: String?
    ): Boolean {
        return false
    }

    override fun onMessageLinkClick(p0: Context?, p1: String?, p2: Message?): Boolean {
        return false
    }

    override fun onMessageLongClick(p0: Context?, p1: View?, p2: Message?): Boolean {
        return false
    }

    override fun onUserPortraitClick(
            p0: Context?,
            conversationType: Conversation.ConversationType?,
            userInfo: UserInfo?,
            targetId: String
    ): Boolean {
        if (conversationType == Conversation.ConversationType.CUSTOMER_SERVICE ||
                conversationType == Conversation.ConversationType.PUBLIC_SERVICE ||
                conversationType == Conversation.ConversationType.APP_PUBLIC_SERVICE
        ) {
            return false
        }
        if (conversationType == Conversation.ConversationType.GROUP) {
            if (!Const.SERVICE_ID.contains(userInfo?.userId!!)) {
                val tGroupMember =
                        GroupMemberDao.instance.findGroupMemberById(targetId, RongIM.getInstance().currentUserId)
                if (tGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_ORDINARY) {
                    return true
                } else {
                    ARouter.getInstance().build(RouteConfig.GROUP_MEMBER_ACTIVITY)
                            .withString("userId", userInfo?.userId).withString("groupId", targetId).navigation()
                }
            }
        } else if (conversationType == Conversation.ConversationType.PRIVATE) {
            if (!Const.SERVICE_ID.contains(targetId!!)) {
                ARouter.getInstance().build(RouteConfig.USER_INFO_DETAILS_ACTIVITY)
                        .withString("userId", userInfo?.userId).navigation()
            }
        }
        return false
    }

    override fun onMessageClick(p0: Context?, p1: View?, p2: Message?): Boolean {
        return false
    }

    private fun setInputProvider() {
        RongIM.setOnReceiveMessageListener(this)
        RongIM.setUserInfoProvider(this, true)
        RongIM.setGroupUserInfoProvider(this, true)
        RongIM.setGroupInfoProvider(this, true)
        RongIM.setConversationClickListener(this)
        RongCallKit.setGroupMemberProvider(this)
    }

    private fun setMyExtensionModule() {
        var moduleList = RongExtensionManager.getInstance().extensionModules
        val iterator = moduleList.iterator()
        while (iterator.hasNext()) {
            val next = iterator.next()
            iterator.remove()
            RongExtensionManager.getInstance().unregisterExtensionModule(next);
        }

        //图片
        RongExtensionManager.getInstance().registerExtensionModule(SampleExtensionModule())
        //小视频
        RongExtensionManager.getInstance().registerExtensionModule(SightExtensionModule())
        RongExtensionManager.getInstance().registerExtensionModule(MRedPackgeExtensionModule())
//        RongExtensionManager.getInstance().registerExtensionModule(RedPackgeExtensionModule())
        RongExtensionManager.getInstance().registerExtensionModule(AudioExtensioModule())
        RongExtensionManager.getInstance().registerExtensionModule(VibrationExtensioModule())
        RongExtensionManager.getInstance().registerExtensionModule(LocationExtensioModule())
//        RongExtensionManager.getInstance().registerExtensionModule(contactCardExtensionModule)
        RongExtensionManager.getInstance().registerExtensionModule(CollectionExtensioModule())


    }

    private val contactCardExtensionModule = ContactCardExtensionModule(object : IContactCardInfoProvider {

        override fun getContactAllInfoProvider(contactInfoCallback: IContactCardInfoProvider.IContactCardInfoCallback) {
            //自定义列表 忽略此方法
        }

        override fun getContactAppointedInfoProvider(
                userId: String,
                name: String,
                portrait: String,
                contactInfoCallback: IContactCardInfoProvider.IContactCardInfoCallback
        ) {
//                val tMember = LitePal.where("userId = $userId ").findLast(TMember::class.java)
            val tMember = GroupMemberDao.instance.findMemberById(userId)

            if (tMember == null) {
                taskHelper?.execute(UserInfoTask(userId), object : NetWorkCallBack<User>() {
                    override fun onPostExecuteSuccess(task: Any?, data: User?) {
                        val userInfo = UserInfo(
                                userId, data?.remark
                                ?: data?.nickname, Uri.parse(data?.photo)
                        )
                        contactInfoCallback.getContactCardInfoCallback(arrayListOf(userInfo))
                    }
                })
            } else {
                contactInfoCallback.getContactCardInfoCallback(
                        arrayListOf(
                                UserInfo(
                                        tMember.userId,
                                        if (TextUtils.isEmpty(tMember.remarkName)) tMember.nickName else tMember.remarkName,
                                        Uri.parse(tMember.photo)
                                )
                        )
                )
            }
        }

    }, IContactCardClickListener { view, content ->
        ARouter.getInstance().build(RouteConfig.USER_INFO_DETAILS_ACTIVITY).withString("userId", content.id)
                .navigation()
    })

    /**
     * 获取消息推送显示内容
     */
    private fun getPushContent(context: Context, message: UIMessage): String {
        var userName = ""
        val userInfo = RongUserInfoManager.getInstance().getUserInfo(message.senderUserId)
        if (userInfo != null) {
            userName = userInfo.name
        }

        return context.getString(R.string.rc_user_recalled_message, *arrayOf<Any>(userName))
    }

    /**
     * 重写添加撤回消息事件
     */
    private fun initMessageItemLongClickAction() {
        val messageRecallAction =
                MessageItemLongClickAction.Builder().titleResId(R.string.rc_dialog_item_message_recall)
                        .actionListener { context, message ->
                            if (RongIM.getInstance().currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.NETWORK_UNAVAILABLE) {
                                ToastUtils.show(context.resources.getString(R.string.rc_recall_failed_for_network_unavailable))
                                true
                            } else {
                                RongIM.getInstance().recallMessage(message.message, getPushContent(context, message))
                                true
                            }
                        }.showFilter { message ->
                            if (message.content !is NotificationMessage && message.content !is HandshakeMessage && message.content !is PublicServiceRichContentMessage && message.content !is RealTimeLocationStartMessage && message.content !is UnknownMessage && message.content !is PublicServiceMultiRichContentMessage && message.sentStatus != Message.SentStatus.CANCELED && message.conversationType != Conversation.ConversationType.ENCRYPTED) {
                                val deltaTime = RongIM.getInstance().deltaTime
                                val normalTime = System.currentTimeMillis() - deltaTime
                                var enableMessageRecall = false
                                var messageRecallInterval = -1
                                val hasSent =
                                        message.sentStatus != Message.SentStatus.SENDING && message.sentStatus != Message.SentStatus.FAILED

                                try {
                                    enableMessageRecall =
                                            RongContext.getInstance().resources.getBoolean(R.bool.rc_enable_message_recall)
                                    messageRecallInterval =
                                            RongContext.getInstance().resources.getInteger(R.integer.rc_message_recall_interval)
                                } catch (var10: Resources.NotFoundException) {
                                    RLog.e(
                                            "RongMessageItemLongClickActionManager",
                                            "rc_message_recall_interval not configure in rc_config.xml"
                                    )
                                    var10.printStackTrace()
                                }

                                hasSent && enableMessageRecall && normalTime - message.sentTime <= (messageRecallInterval * 1000).toLong() && (message.senderUserId == RongIM.getInstance().currentUserId || (message.conversationType == Conversation.ConversationType.GROUP && isReCall(
                                        message.targetId,
                                        message.senderUserId
                                ))) && message.conversationType != Conversation.ConversationType.CUSTOMER_SERVICE && message.conversationType != Conversation.ConversationType.APP_PUBLIC_SERVICE && message.conversationType != Conversation.ConversationType.PUBLIC_SERVICE && message.conversationType != Conversation.ConversationType.SYSTEM && message.conversationType != Conversation.ConversationType.CHATROOM
                            } else {
                                false
                            }
                        }.build()
        RongMessageItemLongClickActionManager.getInstance().addMessageItemLongClickAction(messageRecallAction)

        val collectAction = MessageItemLongClickAction.Builder()
                .title("收藏")
                .showFilter {
                    (it.sentStatus != Message.SentStatus.SENDING && it.sentStatus != Message.SentStatus.FAILED) &&
                            (it.content is TextMessage || it.content is VoiceMessage || it.content is ImageMessage || it.content is SightMessage)
                }
                .actionListener { context, uiMessage ->
                    if (RongIM.getInstance().currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.NETWORK_UNAVAILABLE) {
                        true
                    } else {
                        collectionMessage(uiMessage)
                        true
                    }
                }
                .build()
        RongMessageItemLongClickActionManager.getInstance().addMessageItemLongClickAction(collectAction)

        val forwardAction = MessageItemLongClickAction.Builder()
                .title("转发")
                .showFilter {
                    (it.sentStatus != Message.SentStatus.SENDING && it.sentStatus != Message.SentStatus.FAILED) &&
                            (it.content is TextMessage || it.content is VoiceMessage || it.content is ImageMessage || it.content is SightMessage || it.content is ContactMessage)
                }
                .actionListener { context, uiMessage ->
                    if (RongIM.getInstance().currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.NETWORK_UNAVAILABLE) {
                        true
                    } else {
                        ARouter.getInstance().build(RouteConfig.FORWARD_ACTIVITY)
                                .withParcelableArrayList("selectList", arrayListOf(uiMessage.message)).navigation()
                        true
                    }
                }
                .build()
        RongMessageItemLongClickActionManager.getInstance().addMessageItemLongClickAction(forwardAction)
    }

    private fun isReCall(targetId: String, sendId: String): Boolean {
        val memberMe = GroupMemberDao.instance.findGroupMemberById(targetId, AppConfig.instance.getUser().userId)
        val memberOther = GroupMemberDao.instance.findGroupMemberById(targetId, sendId)
//        val memberMe = LitePal.where("groupId=$targetId and userId=${AppConfig.instance.getUser().userId}").findLast(TGroupMember::class.java)
//        val memberOther = LitePal.where("groupId=$targetId and userId=$sendId").findLast(TGroupMember::class.java)
        if (memberOther != null) {
            if (memberMe?.role == Const.GROUP_ROLE.ROLE_GROUP_LORDE) return true
            if (memberMe?.role == Const.GROUP_ROLE.ROLE_GROUP_ADMIN && memberOther.role == Const.GROUP_ROLE.ROLE_GROUP_ORDINARY) return true
        }
        return false
    }

    private fun isNotify(sendTime: Long, targetId: String, conversationType: Conversation.ConversationType): Boolean {
        if (conversationType == Conversation.ConversationType.GROUP) {
            val tGroup = GroupMemberDao.instance.findGroupById(targetId)
//            val tGroup = LitePal.where("groupId=$targetId").findLast(TGroup::class.java)
            return if (tGroup == null) {
                true
            } else {
                when (tGroup.type) { //1-开 2-关闭1小时 3-关闭8小时 4-关闭2天 5-关闭
                    "0" -> true
                    "5" -> false
                    else -> if (tGroup.endTime.isNullOrEmpty()) {
                        0L
                    } else {
                        tGroup.endTime!!.toLong()
                    } < sendTime / 1000
                }
            }
        } else if (conversationType == Conversation.ConversationType.PRIVATE) {
            val tMember = GroupMemberDao.instance.findMemberById(targetId)
//            val tMember = LitePal.where("userId=$targetId").findLast(TMember::class.java)
            return if (tMember == null) {
                true
            } else {
                when (tMember.type) {
                    "0" -> true
                    "5" -> false
                    else -> if (tMember.endTime.isNullOrEmpty()) {
                        0L
                    } else {
                        tMember.endTime!!.toLong()
                    } < sendTime / 1000
                }
            }
        }
        return true
    }

    /**
     * 判断当前所在页面是否是在聊天
     */
    private fun isInConversationPager(id: String, type: Conversation.ConversationType): Boolean {
        val list = RongContext.getInstance().currentConversationList
        val var4 = list.iterator()
        if (!var4.hasNext()) {
            return false
        } else {
            val conversationInfo = var4.next() as ConversationInfo
            return id == conversationInfo.targetId && type == conversationInfo.conversationType
        }
    }

    private fun collectionMessage(uiMessage: UIMessage) {
        val colType = when {
            uiMessage.content is TextMessage -> Const.CollectionType.TYPE_TEXT_MESSAGE
            uiMessage.content is ImageMessage -> Const.CollectionType.TYPE_IMAGE_MESSAGE
            uiMessage.content is VoiceMessage -> Const.CollectionType.TYPE_VOICE_MESSAGE
            uiMessage.content is SightMessage -> Const.CollectionType.TYPE_SIGHT_MESSAGE
            else -> 0
        }
        val content = when {
            uiMessage.content is TextMessage -> String(uiMessage.content.encode(), charset("utf-8"))
            uiMessage.content is ImageMessage -> {
                val imageMessage = uiMessage.content as ImageMessage
                if (imageMessage.base64 == null) {
                    val imageData = FileUtils.getByteFromUri(imageMessage.thumUri)
                    imageMessage.base64 = Base64.encodeToString(imageData, Base64.NO_WRAP)
                }
                String(imageMessage.encode(), charset("utf-8"))
            }
            uiMessage.content is VoiceMessage -> {
                val voiceMessage = uiMessage.content as VoiceMessage
                if (voiceMessage.base64 == null) {
                    val voiceData = FileUtils.getByteFromUri(voiceMessage.uri)
                    voiceMessage.base64 = Base64.encodeToString(voiceData, Base64.NO_WRAP)
                }
                String(voiceMessage.encode(), charset("utf-8"))
            }
            uiMessage.content is SightMessage -> {
                val sightMessage = uiMessage.content as SightMessage
                if (sightMessage.base64 == null) {
                    val sightData = FileUtils.getByteFromUri(sightMessage.thumbUri)
                    sightMessage.base64 = Base64.encodeToString(sightData, Base64.NO_WRAP)
                }
                String(sightMessage.encode(), charset("utf-8"))
            }
            else -> ""
        }
        taskHelper?.execute(CollectionTask(colType, content), object : NetWorkCallBack<JsonObject>() {
            override fun onPostExecuteSuccess(task: Any?, data: JsonObject?) {
                ToastUtils.show("收藏成功")
            }
        })
    }
}
