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.im.IMGroupNewMsgListener
import com.swago.baseswago.im.ImConstant
import com.swago.baseswago.model.im.CusNewMsgBean
import com.swago.baseswago.model.im.FollowSuccessMsgBean
import com.swago.baseswago.model.im.GameData
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
import org.json.JSONObject

/**
 *@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()
    }

    private val imGroupNewMsgListener = IMGroupNewMsgListener()

    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)
            }
        }


        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<GameData>>(
            ImConstant.fruit_game
        ) {
            it.data?.let { gameData ->
                convertToJson(gameData,ImConstant.fruit_game)
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<GameData>>(
            ImConstant.beauty_game
        ) {
            it.data?.let { gameData ->
                convertToJson(gameData,ImConstant.beauty_game)
            }
        }


    }

    override fun initLiveData() {}


    inner class JSLoad {

        @JavascriptInterface
        fun getGameNeedInfo(): String {
            imGroupNewMsgListener.attach()
            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().apply {
                this.noticeGameDialog = {
                    val jsonObject = JSONObject()
                    jsonObject.put("type", 1000)
                    val dataJsonObject = JSONObject()
                    dataJsonObject.put("userAmount", it)
                    jsonObject.put("data", dataJsonObject)
                    webView?.loadUrl("javascript:onMessage(${jsonObject.toString()})")
                }
            }.show(childFragmentManager, "PayDialog")
        }

        @JavascriptInterface
        fun closeGame() {
            dismissAllowingStateLoss()
        }

    }


    private fun convertToJson(gameData: GameData,type:Int){
        val jsonObject = JSONObject()
        jsonObject.put("type", type)
        val dataJsonObject = JSONObject()
        dataJsonObject.put("userId", gameData.userId)
        dataJsonObject.put("betsCamp", gameData.betsCamp)
        dataJsonObject.put("betsAmount", gameData.betsAmount)
        dataJsonObject.put("campTotalAmount", gameData.campTotalAmount)
        jsonObject.put("data", dataJsonObject)
        webView?.loadUrl("javascript:onMessage(${jsonObject.toString()})")
    }


    override fun onDestroyView() {
        try {
            imGroupNewMsgListener.detach()
            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()
    }
}