package com.halo.assistant.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.webkit.*
import androidx.annotation.RequiresApi
import com.gh.common.DefaultJsApi
import com.gh.common.DefaultUrlHandler.interceptUrl
import com.gh.common.util.*
import com.gh.common.util.CollectionUtils.OnCollectionListener
import com.gh.gamecenter.MessageDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.adapter.viewholder.UnAvaliableWebviewViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.ToolBoxEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.eventbus.EBShare
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.PermissionHelper.checkStoragePermissionBeforeAction
import com.gh.gamecenter.common.view.dsbridge.DWebView
import com.gh.gamecenter.core.AppExecutor.uiExecutor
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.core.utils.ElapsedTimeCallback
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.core.utils.GsonUtils.fromJson
import com.gh.gamecenter.core.utils.MtaHelper.onEventWithTime
import com.gh.gamecenter.core.utils.TimeElapsedHelper
import com.gh.gamecenter.databinding.FragmentWebBinding
import com.gh.gamecenter.databinding.FragmentWebWarningBinding
import com.gh.gamecenter.entity.CommentnumEntity
import com.gh.gamecenter.entity.WebShareEntity
import com.gh.gamecenter.eventbus.EBTypeChange
import com.gh.gamecenter.gamedetail.GameDetailFragment
import com.gh.gamecenter.message.MessageDetailFragment
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.PicassoEngine
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import kotlin.math.abs

class WebFragment : LazyFragment(), IScrollable {

    private var mBinding: FragmentWebBinding? = null
    var mMenuShare: MenuItem? = null
    var mMenuCollect: MenuItem? = null

    private var mToolBoxEntity: ToolBoxEntity? = null

    private var newsId: String? = null
    private var mBbsId: String? = null // 论坛 id
    private var mNavigationTitle: String? = null //导航栏标题
    private var mBackConfirmationContent: String? = null //返回确认弹窗内容
    private var mGameName: String? = null
    private var mIsCloseButton: String? = null //h5游戏是否显示关闭按钮 hide(隐藏)、open(开启)
    private var mWebUrl: String = "" //网页url

    private var commentNum = 0

    private var mShowWebShare = false //是否显示分享按钮
    private var mAutoCompletionTitle = false //是否使用网页标题
    private var mIsTools = false //是否工具箱页面
    private var mQaType = -1 //0:QA内容详情 1:使用帮助内容详情
    private var mIsBindWechat = false //是否绑定微信页面
    private var mIsBackpressRequireConfirmation = false //返回是否需要确认弹窗
    private var mIsWebPageHandleBackPressed = false //是否由网页处理返回事件
    private var mIsOpenNativePage = false //网页打开新页面是否重新打开一个原生页面
    private var mIsHorizontalDispatcherEnabled = false //是否启用横向滚动
    private var mIsWebPageSuccessfullyLoaded = true // 页面是否成功加载
    private var mIsWebPageReceivedError = false // 页面是否加载错误
    private var mIsSecurityCertification = false //是否安全认证页面
    private var mLeaveWebpageToHandleTitle = false //是否由网页处理标题
    private var mClearHistoryOnLoaded = false // 是否加载完成以后清理掉旧的加载历史
    private var mIsWebViewInstalled = true // 当前设备是否存在可用的 WebView

    private var mTimeElapsedHelper: TimeElapsedHelper? = null
    private lateinit var mJsApi: DefaultJsApi
    private var mShareEntity: WebShareEntity? = null
    private var mSelectPicCallback: ValueCallback<Uri?>? = null
    private var mSelectPicCallbackAboveL: ValueCallback<Array<Uri>>? = null
    private val mShareResultCallback by lazy {
        object : ShareUtils.ShareCallBack {

            override fun onSuccess(label: String) {
                if ("短信" == label || "复制链接" == label) {
                    onShareSuccess()
                }
            }

            override fun onCancel() {
                // Do nothing
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        updateIsWebViewInstalled()
        super.onCreate(savedInstanceState)
    }

    override fun getRealLayoutId(): Int {
        return if (mIsWebViewInstalled) R.layout.fragment_web else R.layout.fragment_web_warning
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        if (mIsWebViewInstalled) {
            mBinding = FragmentWebBinding.bind(inflatedView)
        } else {
            UnAvaliableWebviewViewHolder(FragmentWebWarningBinding.bind(inflatedView)).bindView()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (!mIsWebViewInstalled) return

        if (requestCode == MessageDetailFragment.REQUEST_UPDATE_COMMENT) {
            if (data != null) {
                mBinding?.webComment?.text = getString(
                    R.string.web_newscomment_count, data.extras?.getInt("commentNum")
                )
            }
        } else if (requestCode == REQUEST_PICK_IMAGE) {
            if (mSelectPicCallback == null && mSelectPicCallbackAboveL == null) return
            if (resultCode == Activity.RESULT_OK) {
                val uriList = Matisse.obtainResult(data)
                if (uriList.size == 0) return
                if (mSelectPicCallbackAboveL != null) {
                    mSelectPicCallbackAboveL?.onReceiveValue(uriList.toTypedArray())
                    mSelectPicCallbackAboveL = null
                } else if (mSelectPicCallback != null) {
                    mSelectPicCallback?.onReceiveValue(uriList[0])
                    mSelectPicCallback = null
                }
            } else {
                if (mSelectPicCallback != null) {
                    mSelectPicCallback?.onReceiveValue(null)
                } else if (mSelectPicCallbackAboveL != null) {
                    mSelectPicCallbackAboveL?.onReceiveValue(null)
                }
            }
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (!TextUtils.isEmpty(mGameName) && mIsBackpressRequireConfirmation && mIsCloseButton == "open") {
            mBinding?.run {
                closeBtn.visibility = View.VISIBLE
                closeBtn.setOnClickListener { requireActivity().finish() }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mBinding?.fullscreenContainer?.elevation = 10F.dip2px().toFloat()
                mBinding?.closeBtn?.elevation = 11F.dip2px().toFloat()
            }
        } else {
            initMenu()
        }
    }

    private fun initMenu() {
        setNavigationTitle(mNavigationTitle)
        initMenu(R.menu.menu_web)
        mMenuShare = getItemMenu(R.id.menu_share)
        mMenuCollect = getItemMenu(R.id.menu_collect)
        mMenuShare?.isVisible = mIsTools
        mMenuCollect?.isVisible = mIsTools
        if (mIsTools) {
            mToolBoxEntity = requireArguments().getParcelable(ToolBoxEntity.TAG)
            if (mToolBoxEntity != null && mToolBoxEntity?.me != null && mToolBoxEntity?.me?.isToolkitFavorite == true) {
                mMenuCollect?.setIcon(R.drawable.community_content_detail_collect_select)
            } else {
                mMenuCollect?.setIcon(R.drawable.community_content_detail_collect_unselect)
            }
        }
    }

    override fun onMenuItemClick(menuItem: MenuItem) {
        when (menuItem.itemId) {
            R.id.menu_share -> if (activity is BaseActivity) {
                val curActivity = activity as BaseActivity
                if (mToolBoxEntity != null) {
                    curActivity.showShare(
                        mToolBoxEntity?.url,
                        mToolBoxEntity?.icon,
                        mToolBoxEntity?.name,
                        mToolBoxEntity?.des,
                        ShareUtils.ShareEntrance.tools, mToolBoxEntity?.id
                    )
                } else {
                    showShareWindow(curActivity)
                }
            }
            R.id.menu_collect -> CheckLoginUtils.checkLogin(
                activity, "工具详情-收藏"
            ) {
                mMenuCollect?.isEnabled = false
                if (mToolBoxEntity?.me != null && mToolBoxEntity?.me?.isToolkitFavorite == true) {
                    mToolBoxEntity?.id?.let {
                        CollectionUtils.deleteCollection(
                            it,
                            CollectionUtils.CollectionType.TOOLKIT,
                            object : OnCollectionListener {
                                override fun onSuccess() {
                                    mToolBoxEntity?.me?.isToolkitFavorite = false
                                    mMenuCollect?.isEnabled = true
                                    mMenuCollect?.setIcon(R.drawable.community_content_detail_collect_unselect)
                                    toast(R.string.collection_cancel)
                                }

                                override fun onError() {
                                    mMenuCollect?.isEnabled = true
                                    toast(R.string.collection_cancel_failure)
                                }
                            })
                    }
                } else {
                    mToolBoxEntity?.id?.let {
                        CollectionUtils.postCollection(
                            it,
                            CollectionUtils.CollectionType.TOOLKIT,
                            object : OnCollectionListener {
                                override fun onSuccess() {
                                    var userData = mToolBoxEntity?.me
                                    if (userData == null) {
                                        userData = ToolBoxEntity.ToolboxMeEntity()
                                        mToolBoxEntity?.me = userData
                                    }
                                    userData.isToolkitFavorite = true
                                    mMenuCollect?.isEnabled = true
                                    mMenuCollect?.setIcon(R.drawable.community_content_detail_collect_select)
                                    toast(R.string.collection_success)
                                }

                                override fun onError() {
                                    mMenuCollect?.isEnabled = true
                                    toast(R.string.collection_failure)
                                }
                            })
                    }
                }
            }
        }
    }

    private fun showShareWindow(curActivity: BaseActivity) {
        if (mShareEntity == null) {
            toast("分享实体为空")
            return
        }

        onShareClicked()

        curActivity.showShareWithCallback(
            if (TextUtils.isEmpty(mShareEntity?.url)) requireArguments().getString(
                EntranceConsts.KEY_URL
            ) else mShareEntity?.url,
            mShareEntity?.icon,
            mShareEntity?.title,
            mShareEntity?.description,
            if (mQaType >= 0) ShareUtils.ShareEntrance.qaDetail else ShareUtils.ShareEntrance.web,
            "",
            mShareResultCallback
        )
    }

    private fun initData() {
        val args = arguments
        if (args != null) {
            mShowWebShare = args.getBoolean(EntranceConsts.KEY_WEB_SHARE, false)
            mIsBindWechat = args.getBoolean(KEY_IS_BIND_WECHAT, false)
            mIsTools = args.getBoolean(KEY_ISTOOLS, false)
            mQaType = args.getInt(KEY_QA_TYPE, -1)
            mBbsId = args.getString(EntranceConsts.KEY_BBS_ID)
            mAutoCompletionTitle = args.getBoolean(KEY_COMPLETION_TITLE, true)
            mNavigationTitle = args.getString(EntranceConsts.KEY_GAMENAME)
            newsId = args.getString(EntranceConsts.KEY_NEWSID)
            mIsBackpressRequireConfirmation = args.getBoolean(KEY_REQUIRE_BACK_CONFIRMATION)
            mIsWebPageHandleBackPressed = args.getBoolean(KEY_LEAVE_WEB_PAGE_TO_HANDLE_BACK_PRESSED)
            mBackConfirmationContent = args.getString(KEY_BACK_CONFIRMATION_CONTENT)
            mIsOpenNativePage = args.getBoolean(KEY_OPEN_NATIVE_PAGE, false)
            mGameName = args.getString(KEY_GAME_NAME)
            mIsCloseButton = args.getString(KEY_CLOSE_BUTTON)
            mIsHorizontalDispatcherEnabled = args.getBoolean(KEY_ENABLE_HORIZONTAL_SCROLL_DISPATCH)
            mIsSecurityCertification = args.getBoolean(KEY_IS_SECURITY_CERTIFICATION, false)
            mLeaveWebpageToHandleTitle = args.getBoolean(KEY_LEAVE_WEB_PAGE_TO_HANDLE_TITLE, false)
            mWebUrl = dealWithUrl(args.getString(EntranceConsts.KEY_URL, ""))
        }
        mJsApi = DefaultJsApi(requireContext(), mEntrance, this, mBbsId)
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        mBinding?.run {
            val settings = webview.settings
            settings.javaScriptEnabled = true
            webview.enableForceDark(DarkModeUtils.isDarkModeOn(requireContext()))
            webview.setTransparentBackground()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
            // 避免提示网页有害信息不能访问
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try {
                    settings.safeBrowsingEnabled = false
                } catch (e: AbstractMethodError) {
                    e.printStackTrace()
                }
            }

            mTimeElapsedHelper = TimeElapsedHelper(this@WebFragment).apply {
                elapsedTimeCallback = ElapsedTimeCallback { elapsedTime ->
                    ActivityCountHelper.handleStayTime(mWebUrl, elapsedTime)
                }
            }

            DWebView.setWebContentsDebuggingEnabled(PackageFlavorHelper.IS_TEST_FLAVOR)

            // 适配大于屏幕宽度的页面
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.domStorageEnabled = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                settings.mediaPlaybackRequiresUserGesture = false
            }

            // 自适应屏幕
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    // 部分设备不支持 TEXT_AUTOSIZING
                    // 报 java.lang.IllegalArgumentException: WebViewClassic does not support TEXT_AUTOSIZING layout mode
                    settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
                } catch (throwable: Throwable) {
                    // do nothing
                }
            }

            // 用webview打开url
            webview.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return if (isAdded) {
                        val originalUrl = requireArguments().getString(EntranceConsts.KEY_URL, "")
                        val b = if (Uri.parse(originalUrl).path != Uri.parse(url).path) interceptUrl(
                            requireContext(),
                            url,
                            "$mEntrance+(光环浏览器)"
                        ) else false
                        if (mIsOpenNativePage && !b) {
                            startActivity(
                                WebActivity.getIntent(
                                    requireContext(),
                                    url,
                                    mNavigationTitle,
                                    true,
                                    true,
                                    mEntrance
                                )
                            )
                            return true
                        }
                        b
                    } else {
                        false
                    }
                }

                override fun onPageFinished(view: WebView, url: String) {
                    super.onPageFinished(view, url)
                    if (mClearHistoryOnLoaded) {
                        mBinding?.webview?.clearHistory()
                        mClearHistoryOnLoaded = false
                    }
                    if (mLeaveWebpageToHandleTitle) {
                        postDelayedRunnable({
                            if (isResumed) {
                                setNavigationTitle(view.title)
                            }
                        }, 100)
                    }
                    if ("Webpage not available" != webview.title && !mIsWebPageReceivedError) {
                        mIsWebPageSuccessfullyLoaded = true
                    }
                }

                // 只会在API 23及以上调用
                @RequiresApi(Build.VERSION_CODES.M)
                override fun onReceivedError(
                    view: WebView,
                    request: WebResourceRequest,
                    error: WebResourceError
                ) {
                    super.onReceivedError(view, request, error)
                    if (request.isForMainFrame) {
                        mIsWebPageSuccessfullyLoaded = false
                        mIsWebPageReceivedError = true
                    }
                }

                override fun onReceivedError(
                    view: WebView?,
                    errorCode: Int,
                    description: String?,
                    failingUrl: String?
                ) {
                    super.onReceivedError(view, errorCode, description, failingUrl)
                    // API 23及以上会调用上面的方法，防止重复调用
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) return
                    mIsWebPageSuccessfullyLoaded = false
                    mIsWebPageReceivedError = true
                }
            }

            // 页面里的下载跳转到自带浏览器
            webview.setDownloadListener { url: String?, _: String?, _: String?, _: String?, _: Long ->
                if (isAdded) {
                    val uri = Uri.parse(url)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    tryWithDefaultCatch { startActivity(intent) }
                }
            }

            //设置加载进度条
            webview.webChromeClient = object : WebChromeClient() {
                // For Android  >= 4.1
                fun openFileChooser(
                    valueCallback: ValueCallback<Uri?>?,
                    acceptType: String?,
                    capture: String?
                ) {
                    mSelectPicCallback = valueCallback
                    openImageChooserActivity()
                }

                override fun onShowFileChooser(
                    webView: WebView,
                    filePathCallback: ValueCallback<Array<Uri>>,
                    fileChooserParams: FileChooserParams
                ): Boolean {
                    mSelectPicCallbackAboveL = filePathCallback
                    openImageChooserActivity()
                    return true
                }

                override fun onShowCustomView(view: View, callback: CustomViewCallback) {
                    super.onShowCustomView(view, callback)
                    fullscreenContainer.removeAllViews()
                    fullscreenContainer.visibility = View.VISIBLE
                    fullscreenContainer.addView(view)
                }

                override fun onHideCustomView() {
                    super.onHideCustomView()
                    fullscreenContainer.visibility = View.GONE
                    fullscreenContainer.removeAllViews()
                }

                override fun onProgressChanged(view: WebView, newProgress: Int) {
                    webProgressbar.progress = newProgress
                    if (newProgress == 100) {
                        webProgressbar.visibility = View.GONE
                        if (newsBottom.visibility == View.GONE && newsId != null) {
                            newsBottom.visibility = View.VISIBLE
                        }
                    } else {
                        if (webProgressbar.visibility == View.GONE) {
                            webProgressbar.visibility = View.VISIBLE
                        }
                    }
                }

                override fun onReceivedTitle(view: WebView, title: String) {
                    super.onReceivedTitle(view, title)
                    // title 有可能超出边界
                    if (TextUtils.isEmpty(newsId)
                        && (TextUtils.isEmpty(mNavigationTitle) || mNavigationTitle?.contains("http") == true)
                        && !mIsTools
                        && mAutoCompletionTitle
                    ) {
                        mNavigationTitle = title
                        setNavigationTitle(mNavigationTitle)
                    }
                }
            }

            if (mWebUrl.isNotEmpty()) {
                if (mWebUrl.startsWith("http")) {
                    if (mIsSecurityCertification) {
                        val extraHeaders = HashMap<String, String>()
                        extraHeaders["Referer"] = "https://www.ghzs.com"
                        webview.loadUrl(mWebUrl, extraHeaders)
                    } else {
                        webview.loadUrl(mWebUrl)
                    }
                } else {
                    webview.loadDataWithBaseURL(null, mWebUrl, "text/html", "utf-8", null)
                }
            }
            if (mIsHorizontalDispatcherEnabled) {
                webview.enableHorizontalScrollDispatch()
            }
            webview.addJavascriptObject(mJsApi, null)
            webview.addJavascriptObject(ShareNativeCallback(), "share")
            webview.addJavascriptObject(InternalJsApi(), "internal")
            webview.setOnScrollChangedListener { _: Int, dy: Int ->
                if (abs(dy) > 0) {
                    EventBus.getDefault().post(EBTypeChange(GameDetailFragment.EB_SCROLLING, 0))
                }
            }
            webComment.setOnClickListener {
                val intent = MessageDetailActivity.getIntentById(
                    context, newsId, commentNum, null,
                    "$mEntrance+(光环浏览器)"
                )
                startActivityForResult(intent, MessageDetailFragment.REQUEST_UPDATE_COMMENT)
            }
        }
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        setHasOptionsMenu(true)
        if (activity != null && activity is WebActivity) {
            mBinding?.doNotDeleteThisEmptyLayout?.visibility = View.GONE
        }
        initData()
        initWebView()
        if (newsId != null) {
            getNewsCommentNum()
        }
        ActivityCountHelper.postActivityPageEnter(mWebUrl, mEntrance)
    }

    /**
     * 重新加载，供 argument 里的 URL 更新了的时候使用
     */
    fun reload() {
        if (arguments != null) {
            mClearHistoryOnLoaded = true
            requireArguments().getString(EntranceConsts.KEY_URL)?.let {
                mBinding?.webview?.loadUrl(
                    it
                )
            }
        }
    }

    private fun dealWithUrl(webUrl: String): String {
        return if (!webUrl.contains("from=ghzs")) {
            val uri = Uri.parse(webUrl).buildUpon().appendQueryParameter("from", "ghzs").build()
            uri.toString()
        } else {
            webUrl
        }
    }

    private fun openImageChooserActivity() {
        checkStoragePermissionBeforeAction(requireContext(), object : EmptyCallback {
            override fun onCallback() {
                Matisse.from(activity)
                    .choose(MimeType.ofImage())
                    .showSingleMediaType(true)
                    .countable(true)
                    .addFilter(GhMatisseFilter())
                    .maxSelectable(1)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(PicassoEngine())
                    .forResult(REQUEST_PICK_IMAGE)
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!TextUtils.isEmpty(mGameName)) {
            mTimeElapsedHelper?.let { onEventWithTime("H5页面", it.elapsedTime, "停留", mGameName) }
        }
        mBinding?.webview?.run {
            removeJavascriptObject(null)
            removeJavascriptObject("share")
            removeJavascriptObject("internal")
        }
    }

    private fun getNewsCommentNum() {
        RetrofitManager.getInstance()
            .api
            .getNewsCommentnum(newsId, Utils.getTime(context))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<CommentnumEntity>>() {
                @SuppressLint("SetTextI18n")
                override fun onNext(response: List<CommentnumEntity>) {
                    super.onNext(response)
                    if (response.isNotEmpty() && response[0].num > 0) {
                        commentNum = response[0].num
                        mBinding?.webComment?.text = "查看评论（" + response[0].num + "）"
                    }
                }
            })
    }

    override fun onBackPressed(): Boolean {
        mBinding?.run {
            if (mIsBackpressRequireConfirmation) {
                return false
            } else if (!TextUtils.isEmpty(mGameName)) {
                return false
            } else if (mIsWebPageHandleBackPressed && mIsWebPageSuccessfullyLoaded) {
                webview.callHandler("onBackPressed") { _: Any? -> }
                return true
            } else if (webview.canGoBack()) {
                webview.goBack()
                return true
            } else if (isDisplayingLogoutPage) {
                // 根据网页是否已注销来判断怎么处理返回逻辑
                webview.callHandler("onCancelCount") { retValue: Any? ->
                    if (retValue is Boolean) {
                        if (retValue) {
                            mJsApi.logoutExitWebViewAndRedirectToLogin()
                        } else {
                            if (webview.canGoBack()) {
                                webview.goBack()
                            } else {
                                requireActivity().finish()
                            }
                        }
                    }
                    Utils.log(retValue)
                }
                return true
            }
        }
        return false
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(bean: EBReuse) {
        mBinding?.run {
            if (bean.type == "feedbackRefresh") {
                webview.callHandler("setUselessTrue") { _: Any? -> }
            } else {
                // 是绑定微信页面时，登录后刷新页面
                if (mIsBindWechat) { // 登录
                    if (bean.type == Constants.LOGIN_TAG || (bean.type == Constants.EB_QUIT_LOGIN)) {
                        webview.reload()
                    }
                } else {
                    mJsApi.onLogin()
                }
            }
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        mBinding?.webview?.callHandler("videoPlay") { _: Any? -> }
    }

    override fun onFragmentPause() {
        super.onFragmentPause()
        mBinding?.webview?.callHandler("videoPause") { _: Any? -> }
    }

    override fun scrollToTop() {
        mBinding?.webview?.scrollTo(0, 0)
    }

    /**
     * 当前页面是否是注销页面
     */
    private val isDisplayingLogoutPage: Boolean =
        Constants.LOGOUT_ADDRESS_DEV == mBinding?.webview?.url || Constants.LOGOUT_ADDRESS == mBinding?.webview?.url

    private fun updateIsWebViewInstalled() {
        mIsWebViewInstalled = PackageUtils.checkWebViewIsAvailable(requireContext())
    }

    fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val am = requireActivity().getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val maxStreamVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        var currentVolume: Int
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP -> {
                currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC)
                if (currentVolume < maxStreamVolume) {
                    currentVolume++
                }
                am.setStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    currentVolume,
                    AudioManager.FLAG_PLAY_SOUND or AudioManager.FLAG_SHOW_UI
                )
                Utils.log("$maxStreamVolume+$currentVolume")
                mBinding?.webview?.callHandler<Any>(
                    "onHaloVolume",
                    arrayOf<Any>("+", maxStreamVolume, currentVolume),
                    null
                )
                return true
            }
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC)
                if (currentVolume > 0) {
                    currentVolume--
                }
                am.setStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    currentVolume,
                    AudioManager.FLAG_PLAY_SOUND or AudioManager.FLAG_SHOW_UI
                )
                Utils.log("$maxStreamVolume-$currentVolume")
                mBinding?.webview?.callHandler<Any>(
                    "onHaloVolume",
                    arrayOf<Any>("-", maxStreamVolume, currentVolume),
                    null
                )
                return true
            }
            KeyEvent.KEYCODE_VOLUME_MUTE -> {
            }
        }
        return false
    }

    internal inner class ShareNativeCallback {
        @JavascriptInterface
        fun setNativeShareContent(shareJson: Any) {
            uiExecutor.execute {
                try {
                    mShareEntity = fromJson(
                        shareJson.toString(),
                        WebShareEntity::class.java
                    )
                    mMenuShare?.isVisible = true
                } catch (ignore: Exception) {
                }
            }
        }

        @JavascriptInterface
        fun showShareWindow() {
            uiExecutor.execute {
                try {
                    showShareWindow(activity as BaseActivity)
                } catch (ignore: Exception) {
                }
            }
        }
    }

    internal inner class InternalJsApi {

        @JavascriptInterface
        fun setNestedScrollingEnabled(msg: Any) {
            mBinding?.webview?.isNestedScrollingEnabled = msg.toString() == "true"
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(share: EBShare?) {
        postDelayedRunnable({
            tryCatchInRelease {
                if (share != null && share.shareEntrance == ShareUtils.ShareEntrance.web && isSupportVisible) {
                    onShareSuccess()
                }
            }
        }, 1000)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mMenuShare?.setIcon(R.drawable.icon_share_black)
        mMenuCollect?.setIcon(R.drawable.community_content_detail_collect_unselect)
        mBinding?.webview?.enableForceDark(DarkModeUtils.isDarkModeOn(requireContext()))
    }

    private fun onShareClicked() {
        if (mShareEntity == null) return
        mBinding?.webview?.callHandler("onShareClicked", arrayOf(mShareEntity?.url)) { _: Any? -> }
    }

    private fun onShareSuccess() {
        if (mShareEntity == null) return
        mBinding?.webview?.callHandler("onShareSuccess", arrayOf(mShareEntity?.url)) { _: Any? -> }
    }

    companion object {
        const val KEY_ISTOOLS = "isTools"
        const val KEY_IS_BIND_WECHAT = "is_bind_wechat"
        const val KEY_ISCOLLECTIONTOOLS = "isCollectionTools"
        const val KEY_IS_SECURITY_CERTIFICATION = "is_security_certification"
        const val KEY_COMPLETION_TITLE = "completion_title"
        const val KEY_QA_TYPE = "qa_type"
        const val KEY_LEAVE_WEB_PAGE_TO_HANDLE_TITLE = "leave_web_page_to_handle_title"
        const val KEY_LEAVE_WEB_PAGE_TO_HANDLE_BACK_PRESSED = "leave_web_page_to_handel_back_pressed"
        const val KEY_REQUIRE_BACK_CONFIRMATION = "require_back_confirmation"
        const val KEY_BACK_CONFIRMATION_CONTENT = "back_confirmation_content"
        const val KEY_OPEN_NATIVE_PAGE = "open_native_page"
        const val KEY_GAME_NAME = "game_name"
        const val KEY_CLOSE_BUTTON = "close_button"
        const val KEY_ENABLE_HORIZONTAL_SCROLL_DISPATCH = "enable_horizontal_scroll_dispatch"
        private const val REQUEST_PICK_IMAGE = 101
    }
}