IMChatUtil.kt 24 KB
Newer Older
1 2 3
package com.yidianling.im.helper

import android.annotation.SuppressLint
4
import android.app.Activity
5 6 7
import android.content.Context
import android.text.TextUtils
import android.view.View
8 9
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
10 11 12 13
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.data.http.BaseAPIResponse
import com.ydl.ydlcommon.data.http.BaseResponse
刘鹏 committed
14
import com.ydl.ydlcommon.data.http.RxUtils
15 16
import com.ydl.ydlcommon.data.http.RxUtils.applySchedulers
import com.ydl.ydlcommon.data.http.UpLoadLogUtils.upLoadLog
konghaorui committed
17
import com.ydl.ydlcommon.modular.ModularServiceManager
konghaorui committed
18 19
import com.ydl.ydlcommon.ui.LoadingDialogFragment
import com.ydl.ydlcommon.ui.LoadingDialogFragment.Companion.newInstance
20
import com.ydl.ydlcommon.utils.NetworkParamsUtils
21
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
22
import com.ydl.ydlcommon.utils.UserInfoCache
23
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
24
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
25 26 27 28 29 30 31 32 33 34
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils.Companion.handleError
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.api.bean.IMExpertBuild
import com.yidianling.im.bean.GetExpert
import com.yidianling.im.bean.UserTypeBean
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl
import com.yidianling.im.config.constants.ImConstants
刘鹏 committed
35
import com.yidianling.im.http.ImRetrofitApi
36 37
import com.yidianling.im.http.ImRetrofitApi.Companion.getImJavaApi
import com.yidianling.im.http.ImRetrofitApi.Companion.getImRetrofitApi
38
import com.yidianling.im.router.ImIn
39 40
import com.yidianling.im.router.ImIn.isLogin
import com.yidianling.im.session.SessionHelper
41
import com.yidianling.im.ui.activity.CmsExamQuestionPaperActivity
42
import com.yidianling.im.ui.page.fragment.bean.ChatItemBean
konghaorui committed
43
import com.yidianling.uikit.business.session.fragment.YDLMessageFragment
44 45 46 47 48 49 50
import com.yidianling.uikit.business.session.helper.ChatStatusCacheHelper
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler
import com.yidianling.uikit.custom.http.ServiceImpl.Companion.instance
import com.yidianling.uikit.custom.http.response.ChatStatusBean
import com.yidianling.uikit.custom.http.response.RecommendExpertBean
import com.yidianling.uikit.custom.widget.TitleBarBottom
konghaorui committed
51
import com.yidianling.user.api.service.IUserService
52 53 54 55 56 57
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException
import java.net.URLEncoder

/**
konghaorui committed
58
 * 私聊页面相关接口封装
59 60
 */
object IMChatUtil {
konghaorui committed
61
    private var loadingDialog: LoadingDialogFragment? = null
62 63 64 65 66
    private const val USER_TYPE_EXPERT = 2//专家
    private const val USER_TYPE_ASSISTANT = 3//助理
    private const val USER_TYPE_USER = 1//用户
    lateinit var doctorId: String

konghaorui committed
67 68 69
    /**
     * 接口数据请求完成回调
     */
70
    interface ChatDataRequestListener {
konghaorui committed
71
        fun onSuccess(expertInfo: IMExpertBuild)
72 73
    }

konghaorui committed
74 75 76 77
    /**
     * 客服专用
     */
    fun startKefuChat(context: AppCompatActivity?) {
78 79 80 81 82 83 84
        SessionHelper.startP2PSession(
            context,
            -1,
            ImConstants.KEFUXIAOYI,
            null,
            P2PCustomActionHandlerImpl(ImConstants.KEFUXIAOYI, "客服小壹", ImConstants.KEFUXIAOYI)
        )
85 86
    }

87 88
    /**
     * 跳转前置信息收集页
刘鹏 committed
89
     * 悬浮导医进来的
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
     * */
    @SuppressLint("CheckResult")
    fun startCms(context: Activity, location: Int, ffrom2: String?) {
        ImRetrofitApi.Companion.getImRetrofitApi()
            .getSystemConfigByKeyword("lx_collect_card_config")
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                val skipTime = it.value1.toLong()
                if (isJumpToIm(skipTime)) {
                    // 请求接口获取咨询助理的uid
                    getImJavaApi().getConsultAssistantUidRequest(location, ffrom2)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe { uidBean ->
                            /*
                            * location=1首页,3问答列表页,4我的入口,5亲子在线咨询入口,6咨询列表页导医入口,
                            * 7使用心理课进入,8使用心理课列表页进入,9测评解读页进入,10搜索页进入,11注册引导页
                            * 0小壹点击前往
                            * */
                            if (uidBean.code == "200" && uidBean.data != 0.toLong()) {
                                startChat(context as AppCompatActivity, uidBean.data.toString(), 0)
                            } else {
                                ToastUtil.toastShort("咨询助理忙碌中,请稍后再试")
                            }
                        }
                } else {
                    //没有时间限制,跳转到前置信息收集
                    CmsExamQuestionPaperActivity.start(context, location, ffrom2)
                }
            }
    }

    /***
     * 判断今天是否展示过
     * */
    private fun isJumpToIm(skip_time: Long): Boolean {
        val time = System.currentTimeMillis()
        val skipTime = SharedPreferencesEditor.getString("skip_time_")
        if (skipTime == null || skipTime.isEmpty()) {
            return false
        }
        val timeDifference = (time - skipTime.toLong()) / 1000
        return timeDifference < skip_time
    }

137
    /**
konghaorui committed
138
     * 私聊列表进入,后置数据请求
139 140 141 142
     *
     * @param context
     * @param chatItemBean
     */
143
    @SuppressLint("CheckResult")
144
    fun startChat(context: AppCompatActivity?, chatItemBean: ChatItemBean) {
刘鹏 committed
145 146
        SessionHelper.startP2PSession(
            context,
刘鹏 committed
147
            3,
刘鹏 committed
148 149 150 151
            chatItemBean.toUid.toString(),
            null,
            P2PCustomActionHandlerImpl(chatItemBean)
        )
刘鹏 committed
152
    }
153

刘鹏 committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    /**
     * 非私聊列表进入,前置数据请求
     * */
    @SuppressLint("CheckResult")
    fun startCms(context: AppCompatActivity, toUid: String, isFromQingShu: Int) {
        if (!isLogin(context, true)) {
            return
        }
        if (loadingDialog == null) {
            loadingDialog = newInstance(null)
        }
        if (context.supportFragmentManager != null && !context.isDestroyed) {
            loadingDialog?.show(context.supportFragmentManager, null)
        }
        ImRetrofitApi.Companion.getImRetrofitApi()
            .getSystemConfigByKeyword("lx_collect_card_config")
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                //请求接口获取 前置信息收集间隔时间
                val skipTime = it.value1.toLong()
                if (isJumpToIm(skipTime)) {
                    //时间内已收集过信息,直接跳转到聊天页
                    startChat(context, toUid, isFromQingShu)
                } else {
刘鹏 committed
180 181 182 183 184 185 186 187 188 189 190
                    prepareAssistantChatData(
                        context,
                        toUid,
                        object : ChatDataRequestListener {
                            override fun onSuccess(expertInfo: IMExpertBuild) {
                                startChatSession(
                                    toUid,
                                    expertInfo,
                                    isFromQingShu,
                                    context
                                )
刘鹏 committed
191 192 193 194
                            }
                        })
                }
            }
195 196
    }

konghaorui committed
197 198 199 200 201 202 203
    /**
     * 非私聊列表进入,前置数据请求
     *
     * @param context
     * @param toUid
     * @param isFromQingShu     用于判断是否从倾诉流程跳转私聊:1:是   其他:不是    从倾述流程跳转私聊,需要发送自定义消息
     */
204
    @SuppressLint("CheckResult")
konghaorui committed
205
    fun startChat(context: AppCompatActivity, toUid: String, isFromQingShu: Int) {
206 207 208
        if (!isLogin(context, true)) {
            return
        }
konghaorui committed
209 210 211 212 213 214
        if (loadingDialog == null) {
            loadingDialog = newInstance(null)
        }
        if (context.supportFragmentManager != null && !context.isDestroyed) {
            loadingDialog?.show(context.supportFragmentManager, null)
        }
刘鹏 committed
215 216 217 218

        prepareAssistantChatData(context, toUid, object : ChatDataRequestListener {
            override fun onSuccess(expertInfo: IMExpertBuild) {
                startChatSession(toUid, expertInfo, isFromQingShu, context)
219
            }
刘鹏 committed
220
        })
221 222
    }

严久程 committed
223

224
    fun startChatCloseReplaceChat(context: AppCompatActivity, toUid: String) {
严久程 committed
225 226 227 228 229 230 231 232 233 234
        if (!isLogin(context, true)) {
            return
        }
        if (loadingDialog == null) {
            loadingDialog = newInstance(null)
        }
        if (context.supportFragmentManager != null && !context.isDestroyed) {
            loadingDialog?.show(context.supportFragmentManager, null)
        }
        prepareChatData(context, toUid, object :
235
            ChatDataRequestListener {
严久程 committed
236 237 238 239 240 241
            override fun onSuccess(expertInfo: IMExpertBuild) {
                startChatSession(toUid, expertInfo, 0, context)
            }
        })
    }

242
    /**
konghaorui committed
243
     * 开启聊天会话
244
     */
245 246 247 248 249 250
    private fun startChatSession(
        toUid: String,
        expertInfo: IMExpertBuild,
        isFromQingShu: Int,
        context: AppCompatActivity
    ) {
251 252
        AliYunRichLogsHelper.getInstance()
            .sendRichLog(AliYunLogConfig.YUNXIN, "startChatSession  开启聊天会话")
konghaorui committed
253 254
        val p2PCustomActionHandlerImpl = P2PCustomActionHandlerImpl(toUid, expertInfo)
        p2PCustomActionHandlerImpl.isFromQingShu = isFromQingShu
255 256
        SessionHelper.startP2PSession(
            context,
刘鹏 committed
257
            3,
258 259 260 261
            toUid,
            null,
            p2PCustomActionHandlerImpl
        )
konghaorui committed
262 263
    }

264 265 266 267 268 269 270 271 272 273 274 275
    /**
     * 信息收集前置页调用方法
     * */
    open fun startChatSessionByCms(
        toUid: String,
        expertInfo: IMExpertBuild,
        isFromQingShu: Int,
        context: AppCompatActivity
    ) {
        startChatSession(toUid, expertInfo, isFromQingShu, context)
    }

konghaorui committed
276 277 278 279
    //====================准备私聊数据====================
    /**
     * 初始化聊天数据
     */
280 281 282 283 284
    fun prepareChatData(
        context: AppCompatActivity,
        toUid: String,
        listener: ChatDataRequestListener
    ) {
konghaorui committed
285 286 287
        if (!isLogin(context, true)) {
            return
        }
刘鹏 committed
288 289 290

        prepareAssistantChatData(context, toUid, listener)

291 292 293
    }

    /**
konghaorui committed
294
     * 专家私聊数据请求
295
     */
296 297 298 299 300
    fun prepareExpertChatData(
        context: AppCompatActivity,
        toUid: String?,
        listener: ChatDataRequestListener
    ) {
konghaorui committed
301
        val disposable = getImJavaApi().getPersonalChat(toUid!!)
302 303 304 305 306 307 308 309 310 311 312 313 314 315
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp: BaseResponse<IMExpertBuild> ->
                if (null != loadingDialog && loadingDialog?.isVisible!!) {
                    loadingDialog?.dismissAllowingStateLoss()
                }
                if (resp.code == 200) {
                    val expert = resp.data
                    UserInfoCache.getInstance().saveYDLUser(
                        expert.shareData.toUid,
                        expert.shareData.doctorName,
                        expert.shareData.cover
                    )
                    listener.onSuccess(expert)
316
                    doctorId = expert.shareData.doctorId
317 318 319
                } else {
                    upLoadLog("consult/get-expert", resp.code, resp.msg)
                    if (resp.code == ImConstants.HTTP_CODE_UNLOGIN) {
刘鹏 committed
320
                        ImIn.loginByOneKeyLogin(context, true)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                        ToastUtil.toastShort(resp.msg)
                    } else if (resp.code == ImConstants.SILENCED_CODE) { //禁言
                        showSilencedDialog(context, resp.data.tips, resp.data.url)
                    } else {
                        ToastUtil.toastShort(resp.msg)
                    }
                }
            }
            ) { throwable: Throwable ->
                if (null != loadingDialog && loadingDialog!!.isVisible) {
                    loadingDialog?.dismissAllowingStateLoss()
                }
                handleError(context, throwable)
                if (throwable is HttpException) {
                    upLoadLog("consult/get-expert", throwable.code(), throwable.message!!)
                }
            }
    }

    /**
     * 助理私聊数据请求
     */
    fun prepareAssistantChatData(
        context: AppCompatActivity,
        toUid: String,
        listener: ChatDataRequestListener
    ) {
        val cmd = GetExpert(toUid.toInt(), 0)
        val disposable =
            getImRetrofitApi().getExpert(NetworkParamsUtils.getMaps(cmd))
351 352
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
konghaorui committed
353
                .subscribe({ resp: BaseResponse<IMExpertBuild> ->
354 355 356 357 358 359 360 361 362 363
                    if (null != loadingDialog && loadingDialog!!.isVisible) {
                        loadingDialog?.dismissAllowingStateLoss()
                    }
                    if (resp.code == 0) {
                        val expert = resp.data
                        UserInfoCache.getInstance().saveYDLUser(
                            expert.shareData.toUid,
                            expert.shareData.doctorName,
                            expert.shareData.cover
                        )
霍志良 committed
364
                        listener.onSuccess(expert)
365 366 367
                    } else {
                        upLoadLog("consult/get-expert", resp.code, resp.msg)
                        if (resp.code == ImConstants.HTTP_CODE_UNLOGIN) {
刘鹏 committed
368
                            ImIn.loginByOneKeyLogin(context, true)
369 370 371 372 373
                            ToastUtil.toastShort(resp.msg)
                        } else if (resp.code == ImConstants.SILENCED_CODE) { //禁言
                            showSilencedDialog(context, resp.data.tips, resp.data.url)
                        } else {
                            ToastUtil.toastShort(resp.msg)
374
                        }
375 376
                    }
                }
377
                ) { throwable: Throwable ->
378
                    if (null != loadingDialog && loadingDialog?.isVisible!!) {
konghaorui committed
379 380
                        loadingDialog?.dismissAllowingStateLoss()
                    }
381 382
                    handleError(context, throwable)
                    if (throwable is HttpException) {
383
                        upLoadLog("consult/get-expert", throwable.code(), throwable.message!!)
384 385 386 387
                    }
                }
    }

konghaorui committed
388 389 390
    //====================私聊页面 初始化操作====================
    /**
     * 初始化在线状态接口
391 392
     *
     * 只有专家显示在线、离线标识,其他用户Type隐藏在线、离线标识
konghaorui committed
393
     */
394 395 396 397 398 399
    fun initChatOnlineState(
        tb: TitleBarBottom,
        context: Context,
        toUid: String,
        messageFragment: YDLMessageFragment
    ) {
400 401 402 403
        val actionHandler = ActionHandlerStorage.getL(toUid)
        //获取私聊对方在线状态
        if (null != actionHandler) {
            val docInfo = actionHandler.info
404 405
            docInfo.doctorBriefInfoFeedbackRate
            if (null != docInfo && (ImConstants.KEFUXIAOYI == docInfo.toUid || "4108805" == docInfo.toUid)) { //小壹客服  不显示是否在线
406 407
                tb.setmMinTitleVisiable(View.GONE)
            } else {
konghaorui committed
408
                //对方是用户,自己是助理
刘鹏 committed
409 410 411
                if (actionHandler.userType == USER_TYPE_USER && ModularServiceManager.provide(
                        IUserService::class.java
                    )
霍志良 committed
412
                        .getUserInfo()?.user_type == USER_TYPE_ASSISTANT
413
                ) {
konghaorui committed
414 415 416 417
                    tb.setTitleTextRightIcon(R.drawable.user_info_icon) {
                        messageFragment.showUserInfoDialog()
                    }
                }
霍志良 committed
418
                if (actionHandler.userType == USER_TYPE_EXPERT) { // 专家
419
                    tb.setmMinTitleVisiable(View.VISIBLE)
420 421
                    // 调取接口获取专家状态
                    val dis = instance
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
                        .getDoctorChatStatus(actionHandler.info.toUid.toLong())
                        .compose(applySchedulers())
                        .subscribe(
                            { chatStatusBean: BaseAPIResponse<ChatStatusBean> ->
                                if (actionHandler != null) {
                                    val status = chatStatusBean.data.status
                                    actionHandler.setDoctorStatus(status)
                                    actionHandler.setDoctorBusyNum(chatStatusBean.data.busyTotal)
                                    //1.在线,2.离线,3.忙碌 4咨询中, 5倾述中  6咨询前准备
                                    if (status == 2) { //离线
                                        tb.setMinTitleText("离线")
                                        tb.setMinTitleColor(
                                            ContextCompat.getColor(
                                                context,
                                                R.color.platform_color_666666
                                            )
                                        )
                                        tb.setMinTitleDrawable(
                                            ContextCompat.getDrawable(
                                                context,
                                                R.drawable.im_background_chat_top_status_off_line
                                            )
                                        )
                                    } else if (status == 4 || status == 5) { //服务中
                                        tb.setMinTitleText("服务中")
                                        tb.setMinTitleColor(
                                            ContextCompat.getColor(
                                                context,
                                                R.color.platform_color_666666
                                            )
                                        )
                                        tb.setMinTitleDrawable(
                                            ContextCompat.getDrawable(
                                                context,
                                                R.drawable.im_background_chat_top_status_online_server
                                            )
                                        )
                                    } else { //在线  1,3,6..
                                        tb.setMinTitleText("在线")
                                        tb.setMinTitleColor(
                                            ContextCompat.getColor(
                                                context,
                                                R.color.platform_color_666666
                                            )
                                        )
                                        tb.setMinTitleDrawable(
                                            ContextCompat.getDrawable(
                                                context,
                                                R.drawable.im_background_chat_top_status_online
                                            )
                                        )
473
                                    }
474 475 476 477 478 479 480
                                    initSystemMessage(
                                        chatStatusBean.data.promptRule,
                                        status,
                                        toUid,
                                        actionHandler
                                    )
                                }
481
                            }
482 483 484
                        ) { throwable: Throwable ->
                            LogUtil.i("getDoctorChatStatus throwable:$throwable")
                        }
霍志良 committed
485
                } else if (actionHandler.userType == USER_TYPE_ASSISTANT) { // 助理
486
                    tb.setmMinTitleVisiable(View.GONE)
487 488
                    // 调取接口获取助理状态
                    instance.getAssistantChatStatus(
489
                        actionHandler.info.toUid.toLong()
490
                    )
491 492 493 494 495 496 497 498 499 500 501 502
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ res: BaseAPIResponse<Int> ->
                            if (actionHandler != null) {
                                if (res.data == 1) { //在线
                                    /*tb.setMinTitleText("在线")
                                    tb.setMinTitleColor(context.resources.getColor(R.color.platform_color_666666))
                                    tb.setMinTitleDrawable(context.resources.getDrawable(R.drawable.im_background_chat_top_status_online))*/
                                } else { //离线
                                    /* tb.setMinTitleText("离线")
                                     tb.setMinTitleColor(context.resources.getColor(R.color.platform_color_666666))
                                     tb.setMinTitleDrawable(context.resources.getDrawable(R.drawable.im_background_chat_top_status_off_line))*/
503 504
                                }
                            }
505 506
                        }
                        ) { throwable: Throwable? -> }
507 508 509 510 511 512 513 514 515
                } else {
                    tb.setmMinTitleVisiable(View.GONE)
                }
            }
        }
    }

    // promptRule 判断是否推荐专家  4,5直接不走文本提示和推荐逻辑,1,3不走推荐逻辑
    //初始化 根据专家在线状态来发送提示消息或者推荐消息
516 517 518 519 520 521
    private fun initSystemMessage(
        promptRule: Int,
        status: Int,
        toUid: String,
        actionHandler: IP2PCustomActionHandler
    ) {
522 523
        if (!(promptRule == 4 || promptRule == 5)) {
            val showExpertList = !(promptRule == 1 || promptRule == 3)
霍志良 committed
524
            if (actionHandler.userType == USER_TYPE_EXPERT && status == 2) { //当该专家离线时
525
                sendRecommendExpertListMessage(1, showExpertList, toUid, actionHandler)
526
            } else if (actionHandler.userType == USER_TYPE_EXPERT && status >= 3) { //当该专家忙碌时
527 528 529 530 531 532 533 534 535
                sendRecommendExpertListMessage(2, showExpertList, toUid, actionHandler)
            }
        }
    }

    /**
     * 发送推荐专家列表
     */
    @SuppressLint("CheckResult")
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    fun sendRecommendExpertListMessage(
        type: Int,
        showExpertList: Boolean,
        toUid: String,
        actionHandler: IP2PCustomActionHandler
    ) { // 调取接口获取推荐专家列表
        instance.getRecommendExpertList(
            actionHandler.info.toUid.toLong(),
            URLEncoder.encode(actionHandler.info.tag1),
            3
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ res: BaseAPIResponse<ArrayList<RecommendExpertBean>> ->
                //发送推荐专家列表消息
                actionHandler.sendRecommendExpertListMessage(toUid, res.data, type, showExpertList)
            }, { throwable: Throwable -> ToastUtil.toastShort(throwable.toString()) })
553 554
    }

konghaorui committed
555 556 557
    //====================展示提示====================
    fun showSilencedDialog(context: Context, tips: String?, url: String?) {
        CommonDialog.create(context)
558 559 560 561 562 563 564 565 566 567 568
            .setMessage(tips)
            .setCancelAble(false)
            .setLeftOnclick(
                context.getString(R.string.im_details)
            ) {
                val realUrl = if (TextUtils.isEmpty(url)) ImConstants.HELP_URL else url!!
                val params = H5Params(realUrl, "")
                NewH5Activity.start(context, params)
            }
            .setRightClick(context.getString(R.string.im_approval), null)
            .show()
konghaorui committed
569
    }
570
}