ConfideBottomSheetDialogFragment.kt 29.4 KB
Newer Older
1 2 3 4
package com.ydl.confide.home

import android.annotation.SuppressLint
import android.app.Dialog
万齐军 committed
5
import android.content.Intent
万齐军 committed
6 7
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
8
import android.net.Uri
万齐军 committed
9
import android.os.Build
10
import android.os.Bundle
11
import android.text.TextUtils
12 13 14 15
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
16
import android.widget.FrameLayout
万齐军 committed
17
import android.widget.ImageView
霍志良 committed
18
import android.widget.TextView
19
import androidx.fragment.app.FragmentActivity
20
import com.alibaba.android.arouter.launcher.ARouter
21 22 23
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.drawee.view.SimpleDraweeView
24 25 26
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
27
import com.tencent.smtt.export.external.interfaces.JsResult
万齐军 committed
28
import com.tencent.smtt.sdk.*
29
import com.ydl.confide.R
刘鹏 committed
30 31
import com.ydl.confide.event.ConfideDialogEvent
import com.ydl.confide.event.ChangeAnotherExpertEvent
霍志良 committed
32
import com.ydl.confide.home.http.ConfideHomeApi
万齐军 committed
33
import com.ydl.confide.router.PhoneCallIn
34
import com.ydl.utils.WebUrlParamsUtils
35
import com.ydl.webview.IJavascriptHandler
36 37 38
import com.ydl.webview.ProgressWebView
import com.ydl.webview.TellData
import com.ydl.webview.WebModularServiceUtils
霍志良 committed
39
import com.ydl.ydlcommon.modular.findRouteService
万齐军 committed
40
import com.ydl.ydlcommon.utils.ScreenUtil
霍志良 committed
41
import com.ydl.ydlcommon.utils.TimeUtil
万齐军 committed
42 43
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
霍志良 committed
44
import com.ydl.ydlnet.YDLHttpUtils
45
import com.yidianling.common.tools.LogUtil
46
import com.yidianling.common.tools.RxImageTool
霍志良 committed
47
import com.yidianling.common.tools.ToastUtil
48
import com.yidianling.im.api.service.IImService
49
import com.yidianling.user.api.event.UserBindPhoneEvent
50
import com.yidianling.user.api.event.UserLoginEvent
霍志良 committed
51
import com.yidianling.user.api.service.IUserService
万齐军 committed
52
import de.greenrobot.event.EventBus
霍志良 committed
53 54
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
55 56
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
万齐军 committed
57
import kotlin.math.roundToInt
58

59 60 61
class ConfideBottomSheetDialogFragment : BottomSheetDialogFragment() {
    companion object {
        private const val KEY_JUMP_URL = "jumpUrl"
霍志良 committed
62 63
        private const val KEY_DOCTOR_ID = "doctor_id"
        private const val KEY_SHOULD_SHOW = "should_show"
64
        private const val KEY_LISTEN_FREE = "listen_free"
万齐军 committed
65
        private const val KEY_UID = "uid"
66
        private const val EXPERT_URL = "expert_url"
67
    }
霍志良 committed
68

万齐军 committed
69 70
    private var firstVisitWXH5PayUrl = true

霍志良 committed
71
    lateinit var wv_content: ProgressWebView
72
    lateinit var text_title: TextView
霍志良 committed
73 74 75 76 77 78
    lateinit var line: View
    lateinit var rl_title: View
    lateinit var close_webview_Icon: View
    lateinit var layoutCall: View
    lateinit var layoutChange: View
    lateinit var tvCall: TextView
万齐军 committed
79
    lateinit var ivCall: ImageView
霍志良 committed
80
    lateinit var tvTime: TextView
81
    lateinit var first_order: SimpleDraweeView
82
    lateinit var free: SimpleDraweeView
83 84
    lateinit var confideProgress: View
    lateinit var layout_change_text: View
万齐军 committed
85
    lateinit var layoutBottom: View
万齐军 committed
86
    lateinit var itemView: View
87 88 89
    var lineStatus: Int = 0
    var bottomSheet: FrameLayout? = null
    var mJtoJHandle: IJavascriptHandler? = null
霍志良 committed
90

万齐军 committed
91
    private var behavior: BottomSheetBehavior<*>? = null
92
    var isLogin: Boolean = false
霍志良 committed
93 94
    lateinit var jumpUrl: String
    lateinit var doctorId: String
95
    lateinit var expertUrl: String
霍志良 committed
96
    var shouldShow: Boolean? = false
万齐军 committed
97
    var uid: String? = null
98
    var listen_free: Boolean = false
万齐军 committed
99
    private var hasOnResume = false
霍志良 committed
100 101 102 103
    fun showBottomSheetDialog(
        activity: FragmentActivity,
        jumpUrl: String,
        doctorId: String,
万齐军 committed
104
        shouldShow: Boolean = false,
105
        uid: String? = null,
106
        listenFree: Boolean = false,
107
        expertUrl: String = ""
霍志良 committed
108
    ) {
109 110
        arguments = Bundle().apply {
            putString(KEY_JUMP_URL, jumpUrl)
霍志良 committed
111
            putString(KEY_DOCTOR_ID, doctorId)
万齐军 committed
112
            putBoolean(KEY_SHOULD_SHOW, shouldShow)
113
            putBoolean(KEY_LISTEN_FREE, listenFree)
万齐军 committed
114
            uid?.let { putString(KEY_UID, it) }
115
            putString(EXPERT_URL, expertUrl)
116
        }
117 118 119 120 121 122
        show(activity.supportFragmentManager, "confide_bottom_showdialog")
    }

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
霍志良 committed
123
        setStyle(STYLE_NORMAL, R.style.AppBottomSheet)
万齐军 committed
124
        EventBus.getDefault().register(this)
125

126 127 128 129 130 131 132 133 134
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.confide_webview, container, false)
    }
霍志良 committed
135

136 137
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
138 139 140 141
        ActionCountUtils.record(
            "ydl_experts_detail_popupwindows_page",
            "ydl_experts_detail_popupwindows_page_visit"
        )
142
        jumpUrl = arguments?.getString(KEY_JUMP_URL) ?: ""
霍志良 committed
143
        doctorId = arguments?.getString(KEY_DOCTOR_ID) ?: ""
144
        expertUrl = arguments?.getString(EXPERT_URL) ?: ""
霍志良 committed
145
        shouldShow = arguments?.getBoolean(KEY_SHOULD_SHOW) ?: false
万齐军 committed
146
        uid = arguments?.getString(KEY_UID)
147
        listen_free = arguments?.getBoolean(KEY_LISTEN_FREE) ?: false
148
        onLoadDialStatus(doctorId)
149
        wv_content = view.findViewById<ProgressWebView>(com.ydl.webview.R.id.wv_content)
万齐军 committed
150
        wv_content.progressbar.visibility = View.GONE
霍志良 committed
151
        close_webview_Icon = view.findViewById<View>(R.id.close_webview_Icon)
152
        text_title = view.findViewById<TextView>(R.id.text_title)
霍志良 committed
153 154
        line = view.findViewById<View>(R.id.line)
        rl_title = view.findViewById<View>(R.id.rl_title)
155 156 157 158 159 160 161

        close_webview_Icon?.setOnClickListener {
            this.dismiss()
        }
        webViewInit(wv_content)

    }
霍志良 committed
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    override fun setCancelable(cancelable: Boolean) {
        val dialog = dialog
        val touchOutsideView =
            dialog?.window?.decorView?.findViewById<View>(com.google.android.material.R.id.touch_outside)
        val bottomSheetView =
            dialog?.window?.decorView?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)

        if (cancelable) {
            touchOutsideView?.setOnClickListener(View.OnClickListener {
                if (dialog.isShowing) {
                    dialog.cancel()
                }
            })
            BottomSheetBehavior.from<View>(bottomSheetView!!).setHideable(true)
        } else {
            touchOutsideView?.setOnClickListener(null)
            // if false 按返回键也无法取消
//      dialog.setCancelable(false)
            BottomSheetBehavior.from<View>(bottomSheetView!!).setHideable(false)
        }

    }
185

万齐军 committed
186
    private fun onShowReady() {
万齐军 committed
187 188 189 190 191
        itemView = LayoutInflater.from(context).inflate(R.layout.confide_bottom_two, null, false)
        layoutCall = itemView.findViewById<View>(R.id.layoutCall)
        layoutChange = itemView.findViewById<View>(R.id.layoutChange)
        confideProgress = itemView.findViewById<View>(R.id.confide_progress)
        layout_change_text = itemView.findViewById<View>(R.id.layout_change_text)
万齐军 committed
192
        layoutBottom = itemView.findViewById<View>(R.id.layoutBottom)
万齐军 committed
193
        tvCall = itemView.findViewById<TextView>(R.id.tvCall)
万齐军 committed
194
        ivCall = itemView.findViewById<ImageView>(R.id.ivCall)
万齐军 committed
195
        tvTime = itemView.findViewById<TextView>(R.id.tvTime)
196
        first_order = itemView.findViewById<SimpleDraweeView>(R.id.first_order)
197
        free = itemView.findViewById<SimpleDraweeView>(R.id.free)
万齐军 committed
198
        val userService = findRouteService(IUserService::class.java)
199

200 201
        isLogin = userService.isLogin()
        first_order.visibility = if (isLogin) View.GONE else View.VISIBLE
202 203

        val controller: DraweeController = Fresco.newDraweeControllerBuilder()
204
            .setUri(Uri.parse("res://drawable/" + R.drawable.confide_first_order))
205 206 207 208 209
            .setOldController(first_order.controller)
            .setAutoPlayAnimations(true) // 是否自动播放Gif动画
            .build()
        first_order.controller = controller

万齐军 committed
210
        layoutCall.setOnClickListener {
万齐军 committed
211 212 213 214
            ActionCountUtils.record(
                "ydl_experts_detail_popupwindows_page",
                "ydl_experts_detail_popupwindows_page_visit"
            )
万齐军 committed
215 216 217
            if (!PhoneCallIn.loginByOneKeyLogin(requireContext(), true)) {
                return@setOnClickListener
            }
万齐军 committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231
            //判断是否绑定手机号
            if (!userService.isBindPhone()) {
                CommonDialog(requireContext())
                    .setMessage("为了您的账号安全,请绑定手机号")
                    .setLeftOnclick("取消") {
                    }
                    .setRightClick("确定") {
                        //跳转绑定手机号页面
                        userService.wxBindToInputhonePage(requireActivity())
                    }
                    .setCancelAble(false)
                    .show()
                return@setOnClickListener
            }
232

233 234
            when (lineStatus) {
                1, 4 -> {
235 236 237
                    callJsFun(wv_content, "listenCallClick()")
                }

238
                3, 6 -> {
239 240 241 242 243 244 245 246
                    if (!uid.isNullOrBlank()) {
                        activity?.let { it1 ->
                            ARouter.getInstance().navigation(IImService::class.java)
                                ?.startChatBySessionId(it1, uid!!)
                        }
                    }
                }

247 248
                5 -> {
                    if (!TextUtils.isEmpty(expertUrl)) {
249 250 251 252 253 254
                        val linkUri = Uri.parse(expertUrl)
                        if (linkUri != null) {
                            val host = linkUri.host
                            if (!TextUtils.isEmpty(host) && host == "h5") {
                                //如果是h5,跳转至NewH5Activity
                                try {
255 256 257 258 259 260 261
                                    var params = URLDecoder.decode(
                                        linkUri.getQueryParameter("params"),
                                        "UTF-8"
                                    )
                                    ARouter.getInstance().build("/new_h5/h5")
                                        .withSerializable("routerParam", params).navigation()
                                } catch (e: NullPointerException) {
262
                                    LogUtil.e("params参数为空")
263
                                } catch (e: UnsupportedEncodingException) {
264
                                    LogUtil.e("解码错误")
265
                                } catch (e: UnsupportedOperationException) {
266 267 268 269 270 271 272 273
                                    LogUtil.e("这不是一个uri格式的地址")
                                }
                            }
                        }
                    }
                }
            }

万齐军 committed
274 275 276 277 278 279 280 281
        }
        layoutChange.setOnClickListener {
            layout_change_text.visibility = View.GONE
            confideProgress.visibility = View.VISIBLE
            callJsFun(wv_content, "handleNext()")
        }

    }
282

霍志良 committed
283 284
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
万齐军 committed
285
        onShowReady()
霍志良 committed
286
        dialog.setOnShowListener {
万齐军 committed
287 288 289 290 291
            if (shouldShow == true) {
                layoutChange.visibility = View.VISIBLE
            } else {
                layoutChange.visibility = View.GONE
            }
霍志良 committed
292 293 294
            val layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
万齐军 committed
295 296 297 298
            ).apply {
                gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                bottomMargin = ScreenUtil.getNavBarHeight(context)
            }
霍志良 committed
299
            dialog?.window?.addContentView(itemView, layoutParams)
300
            bottomSheet =
霍志良 committed
301
                (it as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
万齐军 committed
302 303
            behavior = BottomSheetBehavior.from(bottomSheet!!)
            behavior?.peekHeight = (resources.displayMetrics.heightPixels * 0.7F).roundToInt()
304

305
            if (jumpUrl?.contains("payPage=1")) {
306 307 308 309
                //支付高度
                setMaxHeight(RxImageTool.dp2px(450f))
                behavior?.isHideable = false
                rl_title.visibility = View.GONE
310
            } else {
311 312
                setMaxHeight(resources.displayMetrics.heightPixels)
            }
霍志良 committed
313
            //true是跳过peekHeight,直接滑下去,false是可以滑动到顶部还可以保持peekHeight在滑下去
314
//        behavior?.skipCollapsed=true
万齐军 committed
315
            behavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
霍志良 committed
316 317
                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    when (newState) {
万齐军 committed
318 319
                        BottomSheetBehavior.STATE_EXPANDED -> {
                            bottomSheet.background = ColorDrawable(Color.WHITE)
320

321
                            if (!jumpUrl?.contains("payPage=1")) {
322 323 324 325 326
                                rl_title.visibility = View.VISIBLE
                                text_title.visibility = View.VISIBLE
                                close_webview_Icon.visibility = View.VISIBLE
                                line.visibility = View.GONE
                            }
霍志良 committed
327
                        }
万齐军 committed
328 329
                        BottomSheetBehavior.STATE_DRAGGING -> {
                            bottomSheet.setBackgroundResource(R.drawable.confide_bottom_webview)
330 331 332
                            if (!jumpUrl?.contains("payPage=1")) {
                                rl_title.visibility = View.VISIBLE
                            }
霍志良 committed
333 334 335 336
                            close_webview_Icon.visibility = View.GONE
                            text_title.visibility = View.GONE
                            line.visibility = View.VISIBLE
                        }
万齐军 committed
337
                        BottomSheetBehavior.STATE_COLLAPSED -> {
338 339 340
                            if (!jumpUrl?.contains("payPage=1")) {
                                rl_title.visibility = View.VISIBLE
                            }
霍志良 committed
341 342 343
                            line.visibility = View.VISIBLE
                        }
                    }
344 345
                }

霍志良 committed
346 347 348 349
                override fun onSlide(bottomSheet: View, slideOffset: Float) {}
            })
        }
        return dialog
350
    }
351 352

    private fun setMaxHeight(height: Int) {
353 354 355
        bottomSheet?.layoutParams?.height = height
        bottomSheet?.requestLayout()
    }
356

霍志良 committed
357
    private fun callJsFun(wv_content: ProgressWebView, funcName: String) {
358 359 360 361 362 363 364 365 366 367
        val sb = StringBuffer("javascript:")
        sb.append(funcName)
        wv_content.post {
            try {
                wv_content.loadUrl(sb.toString())
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
万齐军 committed
368 369

    fun onEventMainThread(event: ConfideDialogEvent) {
万齐军 committed
370
        if(!hasOnResume) return
万齐军 committed
371 372
//        第一位表示拨打按钮,第二位代表再换一位按钮
        val show = event.show
373 374 375 376
//        if (show == 0) {
//            behavior?.state = BottomSheetBehavior.STATE_EXPANDED
//        }

377 378 379
        setMaxHeight(RxImageTool.dp2px(450f))
        rl_title.visibility = View.GONE
        behavior?.isHideable = false
万齐军 committed
380 381 382 383 384
        layoutCall.visibility = if (show and 0x01 == 0x01) View.VISIBLE else View.GONE
        layoutChange.visibility = if (show and 0x02 == 0x01) View.VISIBLE else View.GONE
    }

    fun onEventMainThread(event: ChangeAnotherExpertEvent) {
385
        updateChange(event.doctorID, event.title, event.uid, event.linkUrl)
万齐军 committed
386 387
    }

388
    private fun updateChange(doctorId: String, title: String, uid: String, linkUrl: String) {
万齐军 committed
389 390 391 392
        if (doctorId == "0") {//没有下一位了
            layoutChange.visibility = View.GONE
            return
        }
万齐军 committed
393 394 395 396
        this.uid = uid
        text_title.text = title
        confideProgress.visibility = View.GONE
        layout_change_text.visibility = View.VISIBLE
万齐军 committed
397
        this.doctorId = doctorId
398
        onLoadDialStatus(doctorId)
万齐军 committed
399
        callJsFun(wv_content, "setUnRead(${getUnReadByUid(uid = uid)})")
400
    }
万齐军 committed
401

402 403
    @SuppressLint("ClickableViewAccessibility")
    private fun webViewInit(wv_content: ProgressWebView) {
404 405 406
        val userService = findRouteService(IUserService::class.java)
        val isLogin = userService.isLogin()
        first_order.visibility = if (isLogin) View.GONE else View.VISIBLE
407 408 409 410 411 412
        val setting: WebSettings = wv_content?.settings!!
        //支持js
        setting.setJavaScriptEnabled(true)
        //设置字符编码
        setting.setDefaultTextEncodingName("GBK")
        setting.setDomStorageEnabled(true)
413
        val appCachePath: String = context?.getCacheDir()?.getAbsolutePath().toString()
414 415 416 417 418 419
        setting.setAppCachePath(appCachePath)
        setting.setAllowFileAccessFromFileURLs(true)
        setting.setAppCacheEnabled(true)
        setting.setAllowFileAccess(true)
        setting.setBlockNetworkImage(false)

420 421
        wv_content?.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY //滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上
        mJtoJHandle = WebModularServiceUtils.getWebService()
422
            .getJavascripHandler(requireActivity(), wv_content, tellData = TellData())
423

424
        wv_content?.addJavascriptInterface(mJtoJHandle, "javascriptHandler")
425
//        var jumpurl = "http://192.168.210.152/jy/listenMask?listenerId=257&isFromApp=1"
426
        loadUrl()
427

428
//        wv_content.loadUrl(jumpUrl)
429 430 431 432 433 434
        wv_content.setOnTouchListener { p0, p1 -> //canScrollVertically(-1)的值表示是否能向下滚动,false表示已经滚动到顶部
            if (!wv_content.canScrollVertically(-1)) {
                wv_content.requestDisallowInterceptTouchEvent(false);
            } else {
                wv_content.requestDisallowInterceptTouchEvent(true);
            }
万齐军 committed
435 436 437 438 439 440 441
            false
        }
        wv_content.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(webview: WebView, url: String?): Boolean {
                if (url.isNullOrBlank()) return false
                return shouldOverridePayUrl(webview, url)
            }
442
        }
443 444 445 446 447 448 449 450 451 452 453
        wv_content.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(
                webView: WebView,
                s: String,
                s1: String,
                jsResult: JsResult
            ): Boolean {
                return super.onJsAlert(webView, s, s1, jsResult)
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
454 455 456 457 458 459 460 461
                if (newProgress == 100) {
                    wv_content.progressbar.visibility = View.GONE
                } else {
                    if (wv_content.progressbar.visibility == View.GONE) {
                        wv_content.progressbar.visibility = View.VISIBLE
                    }
                    wv_content.progressbar.progress = newProgress
                }
462
                if (newProgress == 100) {
万齐军 committed
463
                    callJsFun(wv_content, "setUnRead(${uid?.let { getUnReadByUid(uid = it) }})")
464 465 466 467 468 469
                }
                super.onProgressChanged(view, newProgress)
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
万齐军 committed
470
                text_title.text = title
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
            }

            // For Android < 3.0
            fun openFileChooser(valueCallback: ValueCallback<Uri?>) {
            }

            // For Android  >= 3.0
            fun openFileChooser(valueCallback: ValueCallback<*>, acceptType: String?) {
            }

            //For Android  >= 4.1
            override fun openFileChooser(
                valueCallback: ValueCallback<Uri>,
                acceptType: String,
                capture: String
            ) {
            }

            // For Android >= 5.0
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                return true
            }
        }
498
    }
万齐军 committed
499

500 501 502 503 504
    private fun loadUrl() {
        val url = WebUrlParamsUtils.getSuffix(jumpUrl, mJtoJHandle?.getUriAppendSuffix())
        wv_content?.loadUrl(url)
    }

万齐军 committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    private fun shouldOverridePayUrl(view: WebView, url: String): Boolean {
        if (url.startsWith("weixin://")) {
            return try {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                true
            } catch (e: java.lang.Exception) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                ToastUtil.toastShort("该手机没有安装微信")
                true
            }
        } else if (url.startsWith("alipays://") || url.startsWith("alipay")) {
            return try {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                true
            } catch (e: java.lang.Exception) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                // 启动支付宝 App 失败,会自行跳转支付宝网页支付
                true
            }
        }

        // 处理普通 http 请求跳转
//        if (!(url.startsWith("http") || url.startsWith("https"))) {
//            return true;
//        }

        // 处理微信 H5 支付跳转时验证请求头 referer 失效
        // 验证不通过会出现“商家参数格式有误,请联系商家解决”
        if (url.contains("wx.tenpay.com")) {

            // 申请微信 H5 支付时填写的域名
            // 比如经常用来测试网络连通性的 http://www.baidu.com
            val parse = Uri.parse(url)
            //从url 中获取 域名信息
            val redirectUrlStr = parse.getQueryParameter("redirect_url")
            val redirectUrl = Uri.parse(redirectUrlStr)
            // 申请微信 H5 支付时填写的域名
            val referer = redirectUrl.scheme + "://" + redirectUrl.host

            // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
            return if ("4.4.3" == Build.VERSION.RELEASE
                || "4.4.4" == Build.VERSION.RELEASE
            ) {
                if (firstVisitWXH5PayUrl) {
                    view.loadDataWithBaseURL(
                        referer, "<script>window.location.href=\"$url\";</script>",
                        "text/html", "utf-8", null
                    )
                    // 修改标记位状态,避免循环调用
                    // 再次进入微信H5支付流程时记得重置状态 firstVisitWXH5PayUrl = true
                    firstVisitWXH5PayUrl = false
                }
                // 返回 false 由系统 WebView 自己处理该 url
                false
            } else {
                // HashMap 指定容量初始化,避免不必要的内存消耗
                val map = HashMap<String, String>(1)
                map["Referer"] = referer
                view.loadUrl(url, map)
                true
            }
        } else if (url.contains("alipay")) {
            return false
        }
        return false
    }

572 573
    override fun onPause() {
        super.onPause()
万齐军 committed
574 575 576
        hasOnResume = false
    }

万齐军 committed
577 578
    override fun onResume() {
        super.onResume()
万齐军 committed
579
        hasOnResume = true
刘鹏 committed
580
        if (doctorId.isNotBlank() && layoutCall.visibility == View.VISIBLE) {
万齐军 committed
581 582 583 584
            onLoadDialStatus(doctorId)
        }
    }

万齐军 committed
585
    fun getUnReadByUid(uid: String): Int {
万齐军 committed
586
        if (uid.isBlank()) return 0
587 588
        return ARouter.getInstance().navigation(IImService::class.java).getUnReadByUid(uid)
    }
万齐军 committed
589

霍志良 committed
590
    @SuppressLint("CheckResult")
万齐军 committed
591
    private fun onLoadDialStatus(doctorId: String, showTip: Boolean = false) {
万齐军 committed
592 593
        if (doctorId.isBlank()) return
        if (doctorId == "0") return
霍志良 committed
594 595 596 597 598 599 600
        val confideApi = YDLHttpUtils.obtainApi(ConfideHomeApi::class.java)
        confideApi.getDialStatus(doctorId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.code == "200") {
                    layoutCall.visibility = View.VISIBLE
601
                    lineStatus = resp.data?.confideLine ?: 2
602
                    expertUrl = resp.data?.linkUrl ?: ""
603
                    if (isLogin && listen_free) {
604 605
                        free.visibility = View.VISIBLE
                        val controller: DraweeController = Fresco.newDraweeControllerBuilder()
606
                            .setUri(Uri.parse("res://drawable/" + R.drawable.confide_free))
607 608 609 610
                            .setOldController(free.controller)
                            .setAutoPlayAnimations(true) // 是否自动播放Gif动画
                            .build()
                        free.controller = controller
611
                    } else {
612 613
                        free.visibility = View.GONE
                    }
霍志良 committed
614 615 616 617 618 619
                    /*
                    * 1在线 2离线 3通话中 4 继续倾诉
                    * */
                    when (lineStatus) {
                        1 -> {
                            tvCall.text = "立即拨打"
万齐军 committed
620
                            tvTime.visibility = View.GONE
万齐军 committed
621
                            ivCall.visibility = View.VISIBLE
霍志良 committed
622 623 624 625 626
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_1)
                        }
                        2 -> {
                            tvCall.text = "已离线"
万齐军 committed
627 628
                            tvTime.visibility = View.VISIBLE
                            ivCall.visibility = View.GONE
629
                            tvTime.text = "(点击邀请上线)"
霍志良 committed
630 631
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_2)
万齐军 committed
632 633
                            if (showTip) {
                                if (!uid.isNullOrBlank()) {
634 635 636 637 638 639
                                    findRouteService(IImService::class.java).startChat(
                                        requireActivity(),
                                        uid!!,
                                        0,
                                        0
                                    )
万齐军 committed
640 641
                                }
                            }
霍志良 committed
642 643 644
                        }
                        3 -> {
                            tvCall.text = "通话中"
万齐军 committed
645 646
                            tvTime.visibility = View.VISIBLE
                            ivCall.visibility = View.GONE
万齐军 committed
647
                            tvTime.text = "(点击留言)"
霍志良 committed
648 649
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_3)
万齐军 committed
650 651 652
                            if (showTip) {
                                ToastUtil.toastShort("对方正在通话中,请稍后拨打")
                                if (!uid.isNullOrBlank()) {
653 654 655 656 657 658
                                    findRouteService(IImService::class.java).startChat(
                                        requireActivity(),
                                        uid!!,
                                        0,
                                        0
                                    )
万齐军 committed
659 660
                                }
                            }
霍志良 committed
661 662 663
                        }
                        4 -> {
                            tvCall.text = "继续倾诉"
万齐军 committed
664
                            ivCall.visibility = View.VISIBLE
霍志良 committed
665 666 667 668 669 670 671 672 673 674
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_1)
                            val t = resp?.data?.remainingTime?.remainingTime
                            if (t != null) {
                                tvTime.visibility = View.VISIBLE
                                val remain = TimeUtil.getElapseTimeForShow(t * 1000)
                                tvTime.text = "(剩余" + remain + ")"
                            }

                        }
675 676 677 678 679 680 681 682 683 684 685 686 687 688
                        5 -> {
                            tvCall.text = "已离线,可预约"
                            tvTime.visibility = View.GONE
                            ivCall.visibility = View.GONE
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_offline_book_bg)
                        }
                        6 -> {
                            tvCall.text = "已离线,可留言"
                            tvTime.visibility = View.GONE
                            ivCall.visibility = View.GONE
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_offline_book_bg)
                        }
霍志良 committed
689 690 691 692 693 694 695 696
                    }
                } else {
                    if (!resp.msg.isNullOrEmpty()) {
                        ToastUtil.toastShort(resp.msg)
                    }
                }
            }, { throwable -> throwable.printStackTrace() })
    }
万齐军 committed
697 698 699 700 701 702

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

704
    //登录成功
705
    fun onEvent(event: UserLoginEvent) {
706 707
        webViewInit(wv_content)

708
    }
709

710 711
    //绑定成功
    fun onEvent(event: UserBindPhoneEvent) {
712
        webViewInit(wv_content)
713
    }
714
}