package com.ccwangluo.accelerator.ui.web

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import com.ccwangluo.accelerator.databinding.FragmentWebviewBinding
import com.ccwangluo.accelerator.manager.LoginUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.github.shadowsocks.http.HttpConfig
import com.just.agentweb.core.AgentWeb
import com.just.agentweb.core.client.DefaultWebClient
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar


@Page(name = "webview")
class CommonWebViewFragment : XPageFragment() {

    override fun initTitleBar(): TitleBar? {
        return null
    }

    var agentWeb: AgentWeb? = null
    lateinit var binding: FragmentWebviewBinding
    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        binding = FragmentWebviewBinding.inflate(inflater!!, container, false)
        return binding.root
    }

    private var show_title = false

    override fun initViews() {
        val url = arguments?.getString(WEBVIEW_URL_KEY)
        val gameId = arguments?.getInt(GAME_ID)
        show_title = arguments?.getBoolean(SHOW_TITLE) ?: false
        if (show_title) {
            binding.webBar.visibility = View.VISIBLE
        }
        binding.webBack.setOnClickListener {
            if (agentWeb?.back() == false || binding.webTitle.text.contains("订单")) {
                popToBack()
            }
        }
        binding.webClose.setOnClickListener {
            popToBack()
        }
        agentWeb =
            url?.let {
                var weburl = it
                if (weburl.contains("?")) {
                    weburl =
                        weburl + "&channel=${SysUtils.getChannel()}&gameId=${gameId}"
                } else {
                    weburl =
                        weburl + "?channel=${SysUtils.getChannel()}&gameId=${gameId}"
                }
                LoginUtils.token?.let {
                    weburl = weburl + "&token=${it}"
                }
                createAgentWeb(this, binding.commonWebview, weburl)
            }
        agentWeb?.getJsInterfaceHolder()
            ?.addJavaObject("android", gameId?.let { AndroidInterface(this, agentWeb!!, it) })
        agentWeb?.webCreator?.webView?.requestFocus(View.FOCUS_DOWN);
    }

    fun createAgentWeb(fragment: Fragment?, viewGroup: ViewGroup, url: String): AgentWeb {
        return AgentWeb.with(fragment!!)
            .setAgentWebParent(
                viewGroup!!,
                -1,
                FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .useDefaultIndicator(Color.parseColor("#3CA4FD"), 3)
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
            .createAgentWeb()
            .ready()
            .go(url)
    }

    val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            println("webview    " + url)
            url?.let {
                if (it.contains("cc-tt-front") || it.contains("ttaccelerator")) {
                    binding.webBar.visibility = View.GONE
                } else {
                    binding.webBar.visibility = View.VISIBLE
                }
            }
        }

    }

    val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            //do you work
            println("webview    process" + newProgress)
        }

        override fun onReceivedTitle(view: WebView?, title: String) {
            var title = title
            super.onReceivedTitle(view, title)
            if (show_title && !TextUtils.isEmpty(title)) {
                if (title.length > 10) {
                    title = title.substring(0, 10) + "..."
                }
            }
            binding.webTitle.setText(title)
            if (agentWeb?.webCreator?.webView?.canGoBack() == true) {
                binding.webClose.visibility = View.VISIBLE
            } else {
                binding.webClose.visibility = View.GONE
            }
        }

    }

    override fun initListeners() {

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
    }

    override fun getUserVisibleHint(): Boolean {
        return super.getUserVisibleHint()
    }

    override fun onPause() {
        agentWeb?.getWebLifeCycle()?.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb?.getWebLifeCycle()?.onResume()
        super.onResume()

        refreshLogin()
        agentWeb?.jsAccessEntrace
            ?.quickCallJs("onResume")
    }

    private fun refreshLogin() {
        LoginUtils.token?.let {
            agentWeb?.getJsAccessEntrace()
                ?.quickCallJs("userToken", it)
        } ?: let {
            agentWeb?.getJsAccessEntrace()
                ?.quickCallJs("clearToken")
        }
    }

    override fun onDestroyView() {
        agentWeb?.getWebLifeCycle()?.onDestroy()
        super.onDestroyView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            agentWeb?.let {
                it.webCreator.webView.url?.let { url ->
                    if (url.contains(HttpConfig.MEMBER_CENTER)) {
                        it.getJsAccessEntrace()
                            .quickCallJs("goback")
                        return true
                    } else {
                        if (it.back()) {
                            return true
                        }
                    }
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    companion object {
        val WEBVIEW_URL_KEY = "WEBVIEW_URL_KEY"
        val SHOW_TITLE = "SHOW_TITLE"
        val GAME_ID = "GAME_ID"
    }
}