package com.lanyun.wanglaotou.composable

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.google.accompanist.insets.navigationBarsPadding
import com.lanyun.common.baseDate.updateMainEvent
import com.lanyun.common.model.MainEvent
import com.lanyun.wanglaotou.App
import com.lanyun.wanglaotou.public.AppBar
import com.lanyun.wanglaotou.public.BaseScreen
import com.lanyun.wanglaotou.public.LcePage
import com.lanyun.wanglaotou.public.WebViewCtrl
import com.lanyun.wanglaotou.viewModel.MainViewModel
import com.lanyun.wanglaotou.viewModel.WebViewAction
import com.lanyun.wanglaotou.viewModel.WebViewModel


@SuppressLint("SetJavaScriptEnabled", "UseCompatLoadingForDrawables")
@Composable
fun WebViewCompose(
    navHostController: NavHostController,
    url: String,
    title:String,
    mainViewModel: MainViewModel,
    webViewModel: WebViewModel = viewModel()
){
    val context = LocalContext.current
    var ctrl: WebViewCtrl? by remember { mutableStateOf(null) }
    val viewStates = webViewModel.viewStates
    val css = """
          #page-header {
            display: none;
          }
          #main-container {
            padding-top: 0 !important;
          }
    """.trimIndent()
    val webView = rememberWebViewWIthLifecycle(webViewModel,url)
    LcePage(pageState = viewStates.pageState, onRetry = {
        webViewModel.dispatch(WebViewAction.FetchData(url))
    }) {

        var isRefreshing: Boolean by remember { mutableStateOf(false) }
        BaseScreen{

            Column(modifier = Modifier
                .fillMaxSize()
                .navigationBarsPadding()) {
                AppBar(title, leftIcon = Icons.Default.ArrowBack, onLeftClick = {
                    updateMainEvent(MainEvent.UserSubData)
                    navHostController.navigateUp()
                })

                AndroidView(factory = {
                    webView
                }, modifier = Modifier.fillMaxSize(),
                    update = { webview ->
                        //设置支持JavaScript
                        // webView.addJavascriptInterface(JSKit())
                        val webSettings = webView.settings
                        webSettings.javaScriptEnabled = true
                        webSettings.domStorageEnabled = true
//                        //        //设置自适应屏幕，两者合用
//                        webSettings.useWideViewPort = true //将图片调整到适合webview的大小
//                        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
//                        webSettings.setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。
//                        webSettings.builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
//                        webSettings.displayZoomControls = false //隐藏原生的缩放控件
//                        //        //其他细节操作
//                        webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存
//                        webSettings.allowFileAccess = true //设置可以访问文件
//                        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
//                        webSettings.loadsImagesAutomatically = true //支持自动加载图片
//                        webSettings.defaultTextEncodingName = "UTF-8"//设置编码格式

                        webview.webViewClient = object : WebViewClient() {
                            override fun shouldOverrideUrlLoading(
                                view: WebView?,
                                request: WebResourceRequest?
                            ): Boolean {
                                val ll = request?.url.toString()
                                if (ll.startsWith("weixin://")
                                    || ll.startsWith("alipays://")
                                    || ll.startsWith("mqqapi://")
                                ) {

                                    mainViewModel.toBuyUrl.value = ll
                                    //打开本地App进行支付

                                }

                                return super.shouldOverrideUrlLoading(view, request)
                            }
                            override fun onPageFinished(view: WebView?, url: String?) {

//                                view.loadUrl("javascript:(function() {" +
//                                        "var parent = document.getElementsByTagName('head').item(0);" +
//                                        "var style = document.createElement('style');" +
//                                        "style.type = 'text/css';" +
//                                        "style.innerHTML = window.atob('" + authcss + "');" +
//                                        "parent.appendChild(style);" +
//                                        "})()");

                                val js = "javascript:(function() { " +
                                        "var parent = document.getElementsByTagName('head').item(0);" +
                                        "var style = document.createElement('style');" +
                                        "style.innerText = '" + css.trim().replace("\n","") + "';" +
                                        "parent.appendChild(style);})()";
                                Log.e("js----","js--- {$js}")
                                webview.loadUrl(js);

                                super.onPageFinished(view, url)


                            }


                        }

                        webView.loadUrl(viewStates.url)
//                        ctrl = WebViewCtrl(webView, viewStates.url, onWebCall = { isFinish ->
//                            isRefreshing = !isFinish
//                        })
//                        ctrl?.initSettings()

                    })

                //Spacer(modifier = Modifier.height(ToolBarHeight).background(Color.Red))

            }




        }
    }

}


@Composable
fun rememberWebViewWIthLifecycle(webViewModel: WebViewModel,url: String) : WebView{
    val context = LocalContext.current
    val webView = remember {
        WebView(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }
    val lifecycleObserver = rememberWebViewLifecycleObserver(webView)
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    DisposableEffect(lifecycle) {
        webViewModel.dispatch(WebViewAction.FetchData(url))
        lifecycle.addObserver(lifecycleObserver)
        onDispose {
        lifecycle.removeObserver(lifecycleObserver)
        }
    }

    return webView
}



@Composable
private fun rememberWebViewLifecycleObserver(webView: WebView): LifecycleEventObserver {
    return remember(webView) {
        LifecycleEventObserver { _, event ->
            run {
                when (event) {
                    Lifecycle.Event.ON_RESUME -> webView.onResume()
                    Lifecycle.Event.ON_PAUSE -> webView.onPause()
                    Lifecycle.Event.ON_DESTROY -> webView.destroy()
                    else -> Log.e("WebView", event.name)
                }
            }
        }
    }
}