package com.swago.room.game

import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import com.google.gson.Gson
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.dialog.PayDialog
import com.swago.baseswago.model.live.game.GameInfoModel
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.SwagoInfo
import com.swago.baseswago.util.UserInfo
import com.swago.room.bean.UserRoomModel
import com.swago.room.databinding.DialogGamePlayBinding

/**
 *@date 2022/1/19 20:41
 *description:
 */
class GamePlayDialog : BaseXDFragment<DialogGamePlayBinding>(),IRoomActiveListener {

    private var url = ""

    private var webView: WebView? = null
    private val jsLoad by lazy {
        JSLoad()
    }
    private val gson by lazy {
        Gson()
    }

    companion object {
        private const val URL = "url"
        fun newInstance(url: String): GamePlayDialog {
            val dialog = GamePlayDialog()
            val bundle = Bundle()
            bundle.putString(URL, url)
            dialog.arguments = bundle
            return dialog
        }
    }

    init {
        setCanCancel(false)
        setGravity(Gravity.BOTTOM)
        setDimAmount(0f)
    }


    override fun initOther() {
        SwagoRoomManager.addListener(this)
        arguments?.let {
            url = it.getString(URL, "")
            activity?.let { activity ->
                webView = WebView(activity)
                webView?.apply {
                    settings.javaScriptEnabled = true
                    addJavascriptInterface(jsLoad, "jsLoad")
                    settings.allowUniversalAccessFromFileURLs = true
                    settings.allowFileAccess = true
                    settings.allowFileAccessFromFileURLs = true
                    settings.useWideViewPort = true
                    settings.loadWithOverviewMode = true
                    settings.javaScriptCanOpenWindowsAutomatically = true//设置允许JS弹窗
                    settings.domStorageEnabled = true
                    isHorizontalScrollBarEnabled = true
                    isVerticalScrollBarEnabled = true
                    clearCache(true)
                    webViewClient = object : WebViewClient() {
                        override fun shouldOverrideUrlLoading(
                            view: WebView?,
                            request: WebResourceRequest?
                        ): Boolean {
                            return super.shouldOverrideUrlLoading(view, request)
                        }
                    }

                    //设置大小
                    val params = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    params.width = DpPxUtil.getScreenWidth()
                    params.height = (params.width * 276 / 360f).toInt()
                    this.layoutParams = params
                    binding.cl.addView(this)
                }

                webView?.loadUrl(url)
            }
        }
    }

    override fun initLiveData() {}


    inner class JSLoad {

        @JavascriptInterface
        fun getGameNeedInfo(): String {
            SwagoRoomManager.iRoomInfo?.let {
                UserInfo.getUserInfo()?.let { userInfoModel ->
                    UserInfo.getLoginModel()?.let { loginModel ->
                        val gameInfoModel = GameInfoModel(
                            (it as UserRoomModel).roomModel?.broadcast_id?:"",
                            userInfoModel.id,
                            it.getAnchorId(),
                            it.getAnchorType(),
                            SwagoInfo.getLanguageCode(),
                            SwagoInfo.getVersionCode(),
                            SwagoInfo.getAppClient(),
                            SwagoInfo.getDeviceInfo(),
                            SwagoInfo.getChannel(),
                            it.getGameApiBaseUrl(),
                            it.getGameType(),
                            loginModel.token
                        )
                        return gson.toJson(gameInfoModel)
                    }
                }
            }
            return ""
        }

        @JavascriptInterface
        fun recharge() {
            PayDialog.newInstance().show(childFragmentManager,"PayDialog")
        }

        @JavascriptInterface
        fun closeGame(){
            dismissAllowingStateLoss()
        }

    }

    override fun onDestroyView() {
        try {
            webView?.apply {
                webChromeClient = null
                parent?.let {
                    val parent = it as ViewGroup
                    parent.removeView(this)
                }
                stopLoading()
                clearHistory()
                removeAllViews()
                clearCache(true)
                destroy()
                webView = null
                binding.cl.removeAllViews()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.onDestroyView()
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun closeRoomed() {
        SwagoRoomManager.removeListener(this)
        dismissAllowingStateLoss()
    }
}