NewMultiMessageFragment.kt 18 KB
Newer Older
konghaorui committed
1 2 3
package com.yidianling.im.ui.page

import android.animation.ObjectAnimator
4
import android.annotation.SuppressLint
5
import android.content.Context
konghaorui committed
6 7 8
import android.os.Bundle
import android.view.View
import android.view.WindowManager
刘鹏 committed
9 10
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
konghaorui committed
11
import com.alibaba.android.arouter.facade.annotation.Route
konghaorui committed
12 13 14 15 16 17 18
import com.alibaba.android.arouter.launcher.ARouter
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.ydl.ydlcommon.base.BaseFragment
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.RxUtils
霍志良 committed
19
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
霍志良 committed
20
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils.Companion.count
konghaorui committed
21 22
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
ydl committed
23 24
import com.yidianling.im.api.event.ImLogoutEvent
import com.yidianling.im.api.event.UpdateBottomBarUnreadNumEvent
25 26
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl
import com.yidianling.im.config.constants.ImConstants
konghaorui committed
27 28 29
import com.yidianling.im.event.MessageListRefreshEvent
import com.yidianling.im.event.ReQureyUnreadNum
import com.yidianling.im.event.UpdateTabUnreadNumEvent
konghaorui committed
30 31 32
import com.yidianling.im.helper.MsgReceiveHelper
import com.yidianling.im.http.ImHttpImpl
import com.yidianling.im.router.ImIn
33
import com.yidianling.im.session.SessionHelper
konghaorui committed
34 35 36 37 38 39 40 41 42
import com.yidianling.im.ui.page.dialog.MessageChatSettingDialog
import com.yidianling.im.ui.page.fragment.ChatFragment
import com.yidianling.im.ui.page.fragment.InteractFragment
import com.yidianling.im.ui.page.fragment.NoticeFragment
import com.yidianling.im.ui.page.fragment.adapter.ChatPagerAdapter
import com.yidianling.im.ui.page.fragment.bean.UnreadMessageBean
import com.yidianling.im.ui.page.popupWindow.ChatSettingPopupWindow
import com.yidianling.im.ui.param.ClearMessageParam
import com.yidianling.im.ui.param.UnreadParam
43
import com.yidianling.uikit.api.NimUIKit
konghaorui committed
44 45 46 47
import de.greenrobot.event.EventBus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
konghaorui committed
48
import kotlinx.android.synthetic.main.im_new_multi_message_fragment.*
霍志良 committed
49
import java.lang.String
konghaorui committed
50 51 52 53 54
import java.util.concurrent.TimeUnit

/**
 * Created by xj on 2019/10/14.
 */
konghaorui committed
55
@Route(path = "/im/im")
konghaorui committed
56 57
class NewMultiMessageFragment : BaseFragment() {

刘鹏 committed
58
    private lateinit var mContext: Context
konghaorui committed
59 60 61 62 63 64 65 66
    private var defaultTranslateX: Float? = null
    private var mFragmentsList: ArrayList<Fragment> = ArrayList(3)
    private var chatSettingPopupWindow: ChatSettingPopupWindow? = null  //右上角弹框
    private var messageChatSettingtDialog: MessageChatSettingDialog? = null //全部已读弹框

    private var chatListUnreadNum: Int = 0 // 私聊列表未读数
    private var interactListUnreadNum: Int = 0 //互动列表未读数
    private var noticeListUnreadNum: Int = 0 //通知列表未读数
霍志良 committed
67 68
    private var startTime: Long = 0L
    private var endTime: Long = 0L
konghaorui committed
69 70 71 72
    override fun initDataAndEventLazy() {
    }

    override fun layoutResId(): Int {
konghaorui committed
73
        return R.layout.im_new_multi_message_fragment
konghaorui committed
74 75 76
    }

    override fun getStatusViewOptions(): StatusBarOptions {
77
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
konghaorui committed
78 79 80 81
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
82
        mContext = requireContext()
konghaorui committed
83 84 85 86 87
        EventBus.getDefault().register(this)
    }

    override fun onResume() {
        super.onResume()
88
        getMsgData()
刘鹏 committed
89 90 91 92
        NIMClient.getService(MsgService::class.java).setChattingAccount(
            MsgService.MSG_CHATTING_ACCOUNT_NONE,
            SessionTypeEnum.None
        )
konghaorui committed
93 94 95 96
    }

    override fun onPause() {
        super.onPause()
刘鹏 committed
97 98 99 100
        NIMClient.getService(MsgService::class.java).setChattingAccount(
            MsgService.MSG_CHATTING_ACCOUNT_NONE,
            SessionTypeEnum.None
        )
霍志良 committed
101 102 103 104 105 106 107
        if (startTime!=0L){
            endTime = System.currentTimeMillis()
            count(
                "ydl_user_message_page|ydl_user_message_page_stay_visit",
                String.valueOf(endTime - startTime)
            )
        }
konghaorui committed
108 109 110 111 112 113 114 115 116 117
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && getIsViewCreated()) {
霍志良 committed
118
            startTime = System.currentTimeMillis()
konghaorui committed
119
            getMsgData()
霍志良 committed
120 121 122
            count("ydl_user_message_page|ydl_user_message_page_visit")
        }
        if (!isVisibleToUser){
霍志良 committed
123 124 125 126 127 128
            if (startTime!=0L){
                endTime = System.currentTimeMillis()
                count(
                    "ydl_user_message_page|ydl_user_message_page_stay_visit",
                    String.valueOf(endTime - startTime)
                )
霍志良 committed
129
                startTime=0L
霍志良 committed
130
            }
konghaorui committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        }
    }

    //跳转到下一个未读消息列
    fun nextUnReadItem() {
        if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
            (mFragmentsList[0] as ChatFragment).nextUnReadItem()
        }
        if (mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
            (mFragmentsList[1] as InteractFragment).nextUnReadItem()
        }
        if (mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
            (mFragmentsList[2] as NoticeFragment).nextUnReadItem()
        }
    }

    override fun initDataAndEvent() {

        chat_btn.setOnClickListener {
            view_pager.currentItem = 0
        }
        communite_btn.setOnClickListener {
            view_pager.currentItem = 1
        }
        notification_btn.setOnClickListener {
            view_pager.currentItem = 2
        }

        defaultTranslateX = custom_indicator.translationX

        initKefu()

        initMore()

        initViewPager()

    }

    /**
     * 刷新当前展示的消息列表的数据,刷新顶部三个消息未读数,刷新底部消息未读数
     */
172
    fun getMsgData(isRefreshInteractList: Boolean = false) {
konghaorui committed
173 174 175 176 177 178 179
        /**
         * 登录状态
         */
        if (ImIn.isLogin()) {
            if (view_pager.currentItem == 0 && mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
                (mFragmentsList[0] as ChatFragment).getChatMessageData()
            }
180 181 182 183 184
            //互动列表单独刷新被点击的item。不进行列表的刷新,列表的刷新操作只在互动列表从私聊或者通知或者其余fragment切换过来的时候刷新
            if (isRefreshInteractList) {
                if (view_pager.currentItem == 1 && mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
                    (mFragmentsList[1] as InteractFragment).getInteractMessageData(refresh = true)
                }
konghaorui committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198
            }
            if (view_pager.currentItem == 2 && mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
                (mFragmentsList[2] as NoticeFragment).getNoticeMessageData()
            }
        }

        requestTopUnReadNumber()
    }

    /**
     * 刷新顶部未读数量(接口返回成功后调用的方法中会触发事件刷新底部导航栏的角标)
     */
    fun requestTopUnReadNumber() {
        if (ImIn.getUserInfo()?.uid != "0") {
刘鹏 committed
199 200
            var dis =
                ImHttpImpl.getInstance().getUnreadMessage(UnreadParam("${ImIn.getUserInfo()?.uid}"))
konghaorui committed
201
                    .compose<UnreadMessageBean>(RxUtils.resultJavaData())
202
                    .compose(RxUtils.applySchedulers(this))
konghaorui committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                    .subscribe({ it ->
                        resetTopUnReadNumber(it)
                    }, { t ->
                        ToastUtil.toastShort("您的网络出现了问题")
                    })
        } else {
            //退出登录情况下,全部不显示
            chat_top_unread_num.visibility = View.GONE
            chatListUnreadNum = 0
            interact_top_unread_num.visibility = View.GONE
            interactListUnreadNum = 0
            notice_top_unread_num.visibility = View.GONE
            noticeListUnreadNum = 0
            EventBus.getDefault().post(UpdateBottomBarUnreadNumEvent(0))
        }
    }

    /**
     * 重置顶部未读数量
     */
    private fun resetTopUnReadNumber(bean: UnreadMessageBean) {

        val chatUnreadNum = ImIn.getInUnreadNum()//私聊未读数移动端自己读取云信
        if (chatUnreadNum > 0) {
            chatListUnreadNum = chatUnreadNum
            chat_top_unread_num.visibility = View.VISIBLE
            chat_top_unread_num.text = if (chatUnreadNum > 99) "99+" else "${chatUnreadNum}"
        } else {
            chat_top_unread_num.visibility = View.GONE
            chatListUnreadNum = 0
        }

        if (bean.interactiveNum > 0) {
            interactListUnreadNum = bean.interactiveNum
            interact_top_unread_num.visibility = View.VISIBLE
刘鹏 committed
238 239
            interact_top_unread_num.text =
                if (bean.interactiveNum > 99) "99+" else "${bean.interactiveNum}"
konghaorui committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253
        } else {
            interact_top_unread_num.visibility = View.GONE
            interactListUnreadNum = 0
        }

        if (bean.notifyNum > 0) {
            noticeListUnreadNum = bean.notifyNum
            notice_top_unread_num.visibility = View.VISIBLE
            notice_top_unread_num.text = if (bean.notifyNum > 99) "99+" else "${bean.notifyNum}"
        } else {
            notice_top_unread_num.visibility = View.GONE
            noticeListUnreadNum = 0
        }

刘鹏 committed
254 255
        MsgReceiveHelper.isHasUnread =
            chatListUnreadNum > 0 || interactListUnreadNum > 0 || noticeListUnreadNum > 0
konghaorui committed
256
        // 同步底部导航栏的角标数量
ydl committed
257 258 259 260 261
        EventBus.getDefault().post(
            UpdateBottomBarUnreadNumEvent(
                chatListUnreadNum + interactListUnreadNum + noticeListUnreadNum
            )
        )
konghaorui committed
262 263 264 265 266 267 268
    }

    /**
     * 初始化更多点击
     */
    private fun initMore() {
        ll_more.setOnClickListener {
霍志良 committed
269
            ActionCountUtils.count("ydl_user_message_page|ydl_user_message_more_click")
konghaorui committed
270 271 272
            if (!ImIn.isLogin()) {
                ToastUtil.toastShort("请登录后再试")
            } else {
刘鹏 committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
                chatSettingPopupWindow = ChatSettingPopupWindow(
                    mContext,
                    object : ChatSettingPopupWindow.OnChatSettingClickListener {
                        override fun onAllReadClick() {
                            messageChatSettingtDialog = MessageChatSettingDialog(
                                mContext,
                                object : MessageChatSettingDialog.OnMessageChatSettingDialog {
                                    override fun onSure() {
                                        markAllMessageRead()
                                        messageChatSettingtDialog?.dismiss()
                                    }

                                    override fun onCancel() {
                                        messageChatSettingtDialog?.dismiss()
                                    }
                                })
                            messageChatSettingtDialog?.show()
                        }
konghaorui committed
291

刘鹏 committed
292 293 294
                        override fun onChatSettingClick() {
                            ARouter.getInstance().build("/user/notifysetting").navigation()
                        }
konghaorui committed
295

刘鹏 committed
296 297 298
                        override fun onSafeInfoSetting() {
                            startActivity(ImIn.getUserService().privacyIntent(activity!!))
                        }
konghaorui committed
299

刘鹏 committed
300 301 302 303 304 305 306 307
                        override fun onDismissAction() {
                            setWindowBg(1f)
                        }
                    })
                chatSettingPopupWindow?.contentView!!.measure(
                    View.MeasureSpec.UNSPECIFIED,
                    View.MeasureSpec.UNSPECIFIED
                ); //这句代码必须要才能获得正确的popupwindow的宽度
konghaorui committed
308 309
                val popupWindowWidth = chatSettingPopupWindow?.contentView!!.measuredWidth
                setWindowBg(0.4f)
刘鹏 committed
310 311 312 313 314
                chatSettingPopupWindow?.showAsDropDown(
                    ll_more,
                    -(popupWindowWidth - ll_more.measuredWidth + 20),
                    0
                )
konghaorui committed
315 316 317 318 319 320 321 322
            }
        }
    }

    /**
     * 全部已读(私聊是单独处理的)
     */
    fun markAllMessageRead() {
刘鹏 committed
323 324 325 326 327 328
        var dis = ImHttpImpl.getInstance().clearMessage(
            ClearMessageParam(
                "${ImIn.getUserInfo()?.uid}",
                "1"
            )
        )
329
            .compose(RxUtils.applySchedulers(this))
刘鹏 committed
330 331 332 333 334 335 336 337 338 339 340 341
            .subscribe({ it ->
                if (it.data) {
                    //清除私聊群聊未读数
                    MsgReceiveHelper.markAllRead()
                    getMsgData(true)
                    ToastUtil.toastShort("已全部标记为已读")
                } else {
                    ToastUtil.toastShort("标记失败")
                }
            }, { t ->
                ToastUtil.toastShort("您的网络出现了问题")
            })
konghaorui committed
342 343 344 345 346 347 348
    }

    /**
     * 初始化客服点击
     */
    private fun initKefu() {
        ll_kefu.setOnClickListener {
349 350 351 352 353 354 355 356
            ActionCountUtils.count("ydl_user_message_page|ydl_user_message_xiaoyi_click")
            if (ImIn.isLogin()) {
                SessionHelper.startP2PSession(context, -1, ImConstants.KEFUXIAOYI, null,
                        P2PCustomActionHandlerImpl(ImConstants.KEFUXIAOYI, "客服小壹", ImConstants.KEFUXIAOYI)
                )
            } else {
                ToastUtil.toastShort("请登录后再试")
            }
konghaorui committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        }
    }
    /**
     * 设置页面背景色
     */
    private fun setWindowBg(alpha: Float) {
        val lp = activity?.window!!.attributes
        lp.alpha = alpha
        activity?.window!!.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity?.window!!.attributes = lp
    }

    /**
     * 初始化viewPager
     */
    private fun initViewPager() {

        if (mFragmentsList.size == 0) {
            mFragmentsList.add(0, ChatFragment())
            mFragmentsList.add(1, InteractFragment())
            mFragmentsList.add(2, NoticeFragment())
        }
        view_pager.offscreenPageLimit = 3
        view_pager.adapter = ChatPagerAdapter(childFragmentManager, mFragmentsList!!)

        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(p0: Int) {
            }

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
            }

389
            @SuppressLint("CheckResult")
konghaorui committed
390
            override fun onPageSelected(index: Int) {
霍志良 committed
391 392
                when (index) {
                    0 -> {
霍志良 committed
393
                        ActionCountUtils.count("ydl_user_message_page|ydl_user_message_type_click","私聊")
霍志良 committed
394 395
                    }
                    1 -> {
霍志良 committed
396
                        ActionCountUtils.count("ydl_user_message_page|ydl_user_message_type_click","互动")
霍志良 committed
397 398
                    }
                    else -> {
霍志良 committed
399
                        ActionCountUtils.count("ydl_user_message_page|ydl_user_message_type_click","通知")
霍志良 committed
400 401
                    }
                }
konghaorui committed
402 403 404
                setSelectTab(index)
                // 这边延迟300毫秒加载,是为了不让动画进行时有卡顿
                Observable.timer(300, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
刘鹏 committed
405 406 407 408
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        getMsgData(true)
                    }
konghaorui committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
            }
        })
    }

    /**
     * tab选择
     */
    private fun setSelectTab(index: Int) {
        if (index == 0) {
            setLeftMargin(0)
        } else if (index == 1) {
            setLeftMargin(1)
        } else if (index == 2) {
            setLeftMargin(2)
        }
    }

    /**
     * 属性动画设置下划线距离左边的距离
     */
    private fun setLeftMargin(index: Int) {
        val currentTranslateX = custom_indicator.translationX
刘鹏 committed
431 432 433 434 435 436
        var anim = ObjectAnimator.ofFloat(
            custom_indicator,
            "translationX",
            currentTranslateX,
            defaultTranslateX!! + index * chat_btn.width
        )
konghaorui committed
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
        anim.duration = 300
        anim.start()
    }

    fun onEvent(event: ReQureyUnreadNum) {
        getMsgData()
    }

    /**
     * 私聊未读数变化触发的事件,不进行互动和通知未读数的更新
     */
    fun onEvent(event: UpdateTabUnreadNumEvent) {
        try {
            val chatUnreadNum = ImIn.getInUnreadNum() //私聊未读数移动端自己读取云信
            if (chatUnreadNum > 0) {
                chatListUnreadNum = chatUnreadNum
                chat_top_unread_num.visibility = View.VISIBLE
                chat_top_unread_num.text = if (chatUnreadNum > 999) "999+" else "${chatUnreadNum}"
            } else {
                chat_top_unread_num.visibility = View.GONE
                chatListUnreadNum = 0
            }
            // 刷新私聊列表
            if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
                (mFragmentsList[0] as ChatFragment).getChatMessageData()
            }
            // 同步底部导航栏的角标数量
ydl committed
464 465 466 467 468
            EventBus.getDefault().post(
                UpdateBottomBarUnreadNumEvent(
                    chatListUnreadNum + interactListUnreadNum + noticeListUnreadNum
                )
            )
konghaorui committed
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        } catch (e: Exception) {
        }
    }

    /**
     * 私聊,互动,通知列表下拉刷新触发
     */
    fun onEvent(event: MessageListRefreshEvent) {
        requestTopUnReadNumber()
    }

    /**
     * 云信登出
     */
    fun onEvent(event: ImLogoutEvent) {
        if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
            (mFragmentsList[0] as ChatFragment).clearData()
        }
        if (mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
            (mFragmentsList[1] as InteractFragment).clearData()
        }
        if (mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
            (mFragmentsList[2] as NoticeFragment).clearData()
        }
    }
}