package cn.yyxx.eyuangame.core.impl.center

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.widget.FrameLayout
import android.widget.ImageView
import cn.yyxx.eyuangame.base.utils.Logger
import cn.yyxx.eyuangame.core.entity.ClickType
import cn.yyxx.eyuangame.core.entity.SdkBackLoginInfo
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl
import cn.yyxx.eyuangame.core.impl.SdkDrive
import cn.yyxx.eyuangame.core.impl.SdkJsImpl
import cn.yyxx.eyuangame.core.impl.share.ShareImpl
import cn.yyxx.eyuangame.core.internal.IImplCallback
import cn.yyxx.eyuangame.core.internal.IJsCallback
import cn.yyxx.eyuangame.core.network.Host
import cn.yyxx.eyuangame.core.ui.dialog.ScaleLoadingDialog
import cn.yyxx.support.AndroidBug5497Workaround
import cn.yyxx.support.JsonUtils
import cn.yyxx.support.ResUtils
import cn.yyxx.support.device.DeviceInfoUtils
import org.json.JSONObject

/**
 * @author #Suyghur.
 * Created on 2021/07/02
 */
class HybridActivity : Activity(), View.OnClickListener {

    private var uploadMessageForAndroid5: ValueCallback<Array<Uri>>? = null
    private lateinit var container: FrameLayout
    private lateinit var webView: WebView
    private lateinit var ivClose: ImageView
    private var loadingDialog: ScaleLoadingDialog? = null


    private val callback = object : IJsCallback {

        override fun onCallback(method: String, data: String): String {
            when (method) {
                "getCommon" -> return SdkDrive.instance.getComm(this@HybridActivity)
                "getToken" -> return SdkBackLoginInfo.instance.token
                "close" -> {
                    runOnUiThread {
                        this@HybridActivity.finish()
                    }
                }
                "back" -> {
                    runOnUiThread {
                        onBackPressed()
                    }
                }
                "facebookShare" -> {
                    kotlin.runCatching {
                        val jsonObject = JSONObject(data)
                        val line = if (JsonUtils.hasJsonKey(jsonObject, "line")) {
                            jsonObject.getString("line")
                        } else {
                            ""
                        }
                        val tag = if (JsonUtils.hasJsonKey(jsonObject, "tag")) {
                            jsonObject.getString("tag")
                        } else {
                            ""
                        }
                        val quote = if (JsonUtils.hasJsonKey(jsonObject, "quote")) {
                            jsonObject.getString("quote")
                        } else {
                            ""
                        }
                        ShareImpl.instance.invokeShare2Fb(this@HybridActivity, line, tag, quote, object : IImplCallback {
                            override fun onResult(code: Int, result: String) {
                                Logger.d("invokeShare2Fb onResult")
                                if (code == 0) {
                                    webView.loadUrl("javascript:wk.FBShareCallback(1)")
                                } else {
                                    webView.loadUrl("javascript:wk.FBShareCallback(-1)")
                                }
                            }
                        })

                    }
                }
                "getRoleInfo" -> {
                    val jsonObject = JSONObject()
                    kotlin.runCatching {
                        jsonObject.put("login_type", SdkBackLoginInfo.instance.loginType)
                        jsonObject.put("uid", SdkBackLoginInfo.instance.userId)
                        jsonObject.put("role_id", SdkBackLoginInfo.instance.currentRoleId)
                        jsonObject.put("role_name", SdkBackLoginInfo.instance.currentRoleName)
                        jsonObject.put("role_level", SdkBackLoginInfo.instance.currentRoleLevel)
                        jsonObject.put("server_id", SdkBackLoginInfo.instance.currentServerId)
                        jsonObject.put("server_name", SdkBackLoginInfo.instance.currentServerName)
                    }
                    return jsonObject.toString()
                }
            }
            return ""
        }

    }

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

    private fun initView() {
        if (SdkBridgeImpl.isLand) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        }
        setContentView(ResUtils.getResId(this, "yyxx_hybrid", "layout"))

        if (!SdkBridgeImpl.isLand) {
            AndroidBug5497Workaround.assistActivity(this)
        }

//        tvTitle = findViewById(ResUtils.getResId(this, "yyxx_tv_title", "id"))
//        ivReturn = findViewById(ResUtils.getResId(this, "yyxx_iv_return", "id"))
//        ivReturn.apply {
//            tag = ClickType.ACTION_RETURN
//            setOnClickListener(this@HybridActivity)
//        }

        showDialog(this)
    }


    private fun initWebView() {
        container = findViewById(ResUtils.getResId(this, "yyxx_webview_container", "id"))

        webView = findViewById(ResUtils.getResId(this, "yyxx_webview", "id"))
        webView.isVerticalScrollBarEnabled = true
        webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        webView.addJavascriptInterface(SdkJsImpl(callback), "eyuangame")
        webView.setBackgroundColor(Color.TRANSPARENT)

        ivClose = findViewById(ResUtils.getResId(this, "yyxx_iv_close", "id"))
        ivClose.visibility = View.GONE
        ivClose.setOnClickListener {
            this.finish()
        }

//        webView.viewTreeObserver.addOnGlobalLayoutListener {
//            if (isSoftShowing()) {
//                view.visibility = View.GONE
//            } else {
//                view.visibility = View.VISIBLE
//            }
//        }

        val webSetting = webView.settings
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.saveFormData = true
        webSetting.savePassword = true
        webSetting.builtInZoomControls = false
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(false)
        webSetting.setAppCacheEnabled(false)
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        webSetting.setAppCachePath(getDir("appcache", 0).path)
        webSetting.databasePath = getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(getDir("geolocation", 0).path)
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()

        if (DeviceInfoUtils.isNetworkConnected(this)) {
            webView.loadUrl(url)
//            webView.loadUrl("file:///android_asset/test.html");
        } else {
            //这种写法可以正确解码
            webView.loadData("网络异常,请检查重试", "text/html; charset=UTF-8", null)
        }

        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
//                if (view.canGoBack() && Uri.parse(url).path != "/index.html") {
//                    ivReturn.visibility = View.VISIBLE
//                } else {
//                    ivReturn.visibility = View.GONE
//                }
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                val hitTestResult = view.hitTestResult
                if (Host.originHost(url)) {
                    container.setBackgroundColor(Color.parseColor("#00FFFFFF"))
                    ivClose.visibility = View.GONE
                } else {
                    container.setBackgroundColor(Color.parseColor("#FFFFFF"))
                    ivClose.visibility = View.VISIBLE
                }

                if (url.startsWith("http:") || url.startsWith("https:")) {
                    //解决重定向加载的问题 return false
                    if (!view.canGoBack()) {
                        return false
                    }
                    //解决重定向加载的问题 return false
                    if (hitTestResult.type == WebView.HitTestResult.UNKNOWN_TYPE) {
                        return false
                    }
                    view.loadUrl(url)
                } else {
                    jump2MyCardClient(url)
                    return true
                }

                return false
            }

            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                //部分手机浏览器不支持https，所以此处需要接受证书
//                handler.proceed()
//                showSslErrorDialog(handler)

            }
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                //progressWebView.setProgressBarProgress(newProgress);
                if (newProgress == 100 && loadingDialog != null && loadingDialog!!.isShowing) {
                    //加载完成,关闭loading
                    dismissDialog()
                }
            }

            //For Android > 5.0
            override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
                openFileChooserImplForAndroid5(filePathCallback)
//                uploadMessageForAndroid5 = filePathCallback
//                mFileChooseParams = fileChooserParams
//                val intent = Intent(Intent.ACTION_GET_CONTENT)
//                intent.addCategory(Intent.CATEGORY_OPENABLE)
//                intent.putExtra("return-data", true)
//                intent.type = "image/*"
//                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
//                startActivityForResult(Intent.createChooser(intent, "选择相册"), FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5)
                return true
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
//                if (!DeviceInfoUtils.isNetworkConnected(view.context)) {
//                    tvTitle.text = "网络异常"
//                    return
//                }
//                if (!TextUtils.isEmpty(view.title)) {
//                    var viewtitle = view.title
//                    if (viewtitle!!.length > 10) {
//                        viewtitle = viewtitle.substring(0, 10)
//                        viewtitle = "$viewtitle..."
//                    }
//                    tvTitle.text = viewtitle
//                }
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }

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

        if (requestCode == FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5) {
            Logger.d("onActivityResult FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5")
            if (uploadMessageForAndroid5 == null) {
                Logger.d("mUploadMessageForAndroid5 == null")
                return
            }
            if (intent == null) {
                uploadMessageForAndroid5!!.onReceiveValue(arrayOf())
                return
            }
            val result = if (resultCode != RESULT_OK) null else intent.data
            if (result == null) {
                uploadMessageForAndroid5!!.onReceiveValue(arrayOf())
            } else {
                uploadMessageForAndroid5!!.onReceiveValue(arrayOf(result))
            }
            uploadMessageForAndroid5 = null
        } else {
            ShareImpl.instance.onShareResult(requestCode, resultCode, intent)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private fun showDialog(context: Context) {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }

        loadingDialog = ScaleLoadingDialog(context, "")
        loadingDialog?.show()
    }

    private fun dismissDialog() {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
    }

    private fun jump2MyCardClient(url: String) {
        try {
            val intent = if (url.startsWith("intent://")
                || url.startsWith("line://")
                || url.startsWith("shopeepay://")
            ) {
                Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
            } else {
                Intent(Intent.ACTION_VIEW, Uri.parse(url))
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Logger.e("${e.message}")
        }
    }

    private fun openFileChooserImplForAndroid5(uploadMsg: ValueCallback<Array<Uri>>) {
        Logger.i("Open ImageChooser For Higher than Android5")
        uploadMessageForAndroid5 = uploadMsg
        val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
        contentSelectionIntent.type = "image/*"

        val chooserIntent = Intent(Intent.ACTION_CHOOSER)
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")

        startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5)
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            finish()
        }
    }

    override fun onClick(v: View?) {
        v?.apply {
            when (tag as Int) {
                ClickType.ACTION_RETURN -> this@HybridActivity.finish()
            }
        }
    }

    companion object {

        private const val FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2

        private var url = ""

        fun start(activity: Activity, url: String) {
            Companion.url = url
            activity.startActivity(Intent(activity, HybridActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }

}