package com.yzx.escreen.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.widget.ContentLoadingProgressBar
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tencent.smtt.export.external.interfaces.*
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.yzx.escreen.MainActivity
import com.yzx.escreen.R
import com.yzx.escreen.activity.base.BaseActivity
import com.yzx.escreen.config.Config
import com.yzx.escreen.model.BaseBean
import com.yzx.escreen.model.User
import com.yzx.escreen.model.UserLoginEvent
import com.yzx.escreen.model.Version
import com.yzx.escreen.presenter.base.BasePresenter
import com.yzx.escreen.utils.hideNavigationBar
import com.yzx.escreen.widget.BaseDialog
import kotlinx.android.synthetic.main.activity_web.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.ctx
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*

/**
 * 类名：WebActivity
 * 作者：Yun.Lei
 * 功能：
 * 创建日期：2020年5月6日14:42:16
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class WebActivity : BaseActivity<BasePresenter<*>>(), NetworkUtils.OnNetworkStatusChangedListener {


    companion object {
        fun active(act: Activity, link: String) {
            act.startActivity<WebActivity>("link" to link)
        }
    }

    private val webView: WebView by lazy { WebView(this) }
    private var url: String = ""
    private var count = 0
    private val run = Runnable {
        count = 0
    }
    var netErrorDialog: QMUIDialog? = null

    override val inflateId: Int
        get() = R.layout.activity_web

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        url = intent?.getStringExtra("link") ?: "https://m.qbjjyyun.net/"
        this.initData()
    }

    fun checkVersion(userCheck: Boolean = false): Unit {
        val BASE_URL = Config.BASE_URL
        OkGo.post<String>("$BASE_URL/parent/common/getInkBottleMaxVersion")
            .tag(this)
            .execute(object : StringCallback() {

                override fun onSuccess(response: Response<String>) {
                    val json = response.body()
                    Log.d("checkVersion", "onSuccess: ${json}")
                    val resultType = object : TypeToken<BaseBean<Version>>() {}.type
                    val gson = Gson()
                    val res = gson.fromJson<BaseBean<Version>>(json, resultType)
                    if (res.code == 0) {
                        val appVersion = AppUtils.getAppVersionName()
                        val appVersionCode = AppUtils.getAppVersionCode()
                        val versionCode = res?.data?.version_code ?: 0
                        val curr = Date().time
                        val lastTipTime = SPUtils.getInstance()
                            .getLong("last_tip_time${res.data.version_code}", 0)
                        if (versionCode > appVersionCode) {     //有新版本
                            when {
                                res.data.type == 1 -> {   //强制升级
                                    updateApp(res.data)
                                }
                                curr - lastTipTime > 24 * 60 * 60 * 1000 -> {     //非强制一天以内提示一次
                                    updateApp(res.data)
                                }
                                userCheck -> {      //
                                    updateApp(res.data)
                                }
                            }

                        } else {
                            if (userCheck) {
                                toast("已经是最新版本了！")
                            }
                        }
                    }
                }

            })


    }

    private fun updateApp(version: Version) {
        AllenVersionChecker
            .getInstance()
            .downloadOnly(
                UIData.create()
                    .setTitle("检测到新版本")
                    .setContent(version.explain)
                    .setDownloadUrl(version.app_src)
            )
            .setCustomVersionDialogListener { context, versionBundle ->
                val dialog = BaseDialog(context, R.style.BaseDialog, R.layout.version_dialog)
                val title = dialog.find<TextView>(R.id.tv_title)
                title.text = "检测到新版本"
                val content = dialog.find<TextView>(R.id.tv_msg)
                content.text = version.explain
                dialog.window?.setDimAmount(0.5f)
                val cancelBtn = dialog.find<View>(R.id.cancel_btn)
                if (version.type == 1) {
                    cancelBtn.visibility = View.GONE
                }

                return@setCustomVersionDialogListener dialog
            }
            .setOnCancelListener {
                SPUtils.getInstance().put("last_tip_time${version.version_code}", Date().time)
            }
            .setCustomDownloadingDialogListener(object : CustomDownloadingDialogListener {
                @SuppressLint("SetTextI18n")
                override fun updateUI(dialog: Dialog?, progress: Int, versionBundle: UIData?) {
                    val tvProgress: TextView = dialog!!.findViewById(R.id.tv_progress)
                    val progressBar: ContentLoadingProgressBar = dialog.findViewById(R.id.pb)
                    progressBar.progress = progress
                    tvProgress.text = "$progress%"

                    Log.d("checkVersion", "onSuccess: ${progress}")
                }

                override fun getCustomDownloadingDialog(
                    context: Context?,
                    progress: Int,
                    versionBundle: UIData?
                ): Dialog {
                    return BaseDialog(
                        context!!,
                        R.style.BaseDialog,
                        R.layout.download_dialog
                    )
                }

            })
            .executeMission(this)
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {
        url = intent?.getStringExtra("link") ?: "https://m.qbjjyyun.net/"
//        titleTv.setOnClickListener {
//            count++
//            titleTv.removeCallbacks(run)
//            titleTv.postDelayed(run, 1000)
//            if (count >= 5) {
//                startActivity<MainActivity>()
//            }
//        }
        btnBack.setOnClickListener { onBackPressed() }
        btnClose.setOnClickListener {
//            webView.loadUrl(url)
            finish()
        }
        btnRefresh.setOnClickListener {
            webView.reload()
        }
        btnSetting.setOnClickListener {
            NetworkUtils.openWirelessSettings()
        }
        webView.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        webLayout.addView(webView)
        webView.addJavascriptInterface(YzxJavascriptInterface(this), "YZX_SCREEN")
        val userAgent = webView.settings.userAgentString
        webView.settings.apply {
            allowFileAccess = true
            javaScriptEnabled = true
            loadWithOverviewMode = true
            useWideViewPort = true
            defaultTextEncodingName = "gb2312"
            setAppCacheEnabled(true)
            mediaPlaybackRequiresUserGesture = false
            javaScriptCanOpenWindowsAutomatically = true
            cacheMode = WebSettings.LOAD_DEFAULT
            databaseEnabled = true
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            blockNetworkImage = false
            domStorageEnabled = true
            setAppCacheMaxSize(1024 * 1024 * 8)
            setAppCachePath(ctx.cacheDir.absolutePath)
            mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
            userAgentString = "$userAgent app/escreen"
        }
        webView.webViewClient = object : WebViewClient() {
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                view?.loadUrl(request?.url.toString())
                return super.shouldOverrideUrlLoading(view, request)
            }

            // 即使加载失败后，webview执行完onReceivedError()方法也会执行这个方法
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                webView.settings.blockNetworkImage = false
                if (!TextUtils.isEmpty(view.title)) {
//                    titleTv.text = view.title//webView获取到网页title
                }
            }

            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                handler.proceed()
            }

            override fun onReceivedError(
                p0: WebView?,
                p1: WebResourceRequest?,
                p2: WebResourceError?
            ) {
                super.onReceivedError(p0, p1, p2)
                LogUtils.e("weberror-onReceivedError")
//                showNetworkError("网络环境异常或服务器数据加载异常，请检查！", force = true)
            }

            override fun onReceivedError(p0: WebView?, p1: Int, p2: String?, p3: String?) {
                super.onReceivedError(p0, p1, p2, p3)
                LogUtils.e("weberror-onReceivedError2")
            }
        }
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                progressbar.progress = newProgress
                if (newProgress >= 100) {
                    view?.post {
                        progressbar.visibility = View.GONE
                        if (view.canGoBack()) {
//                            btnBack.visibility = View.VISIBLE
//                            btnClose.visibility = View.VISIBLE
                        } else {
//                            btnBack.visibility = View.GONE
//                            btnClose.visibility = View.GONE
                        }
                    }
                } else {
                    if (progressbar.visibility == View.GONE) {
                        view?.post { progressbar.visibility = View.VISIBLE }
                    }
                }
            }

            override fun onJsAlert(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean {
                val b = AlertDialog.Builder(this@WebActivity)
                b.setTitle(message)
                b.setPositiveButton("确定") { _, _ ->
                    result?.confirm()
                }
                return true
            }
        }
        WebView.setWebContentsDebuggingEnabled(true)        //将 WebViews 配置为可调试状态
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
    }

    override fun initData() {
        webView.loadUrl(url)
        showNetworkError()

    }

    override fun initPresenter(): BasePresenter<*>? {
        return null
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
//        checkVersion()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
    }

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

    override fun onDestroy() {
        super.onDestroy()
        webView.apply {
//            webViewClient = null
            webChromeClient = null
            (parent as ViewGroup).removeView(webView)
            removeAllViews()
            destroy()
        }
        AllenVersionChecker.getInstance().cancelAllMission()
    }

    /**
     * 调用js方法
     */
    private fun evaluateJavascript(funName: String, data: String) {
        webView.post {
            webView.evaluateJavascript("javascript:$funName('$data')") {
                Log.d("javascriptCallBack:", it)
                //toast(it)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

    }

    override fun onDisconnected() {

    }

    override fun onConnected(networkType: NetworkUtils.NetworkType?) {

    }

    private fun showNetworkError(msg: String = "你还没有连接网络，请先连接网络！", force: Boolean = false) {
        if (!NetworkUtils.isConnected() || force) {        //无网提示
            val builder = QMUIDialog.MessageDialogBuilder(this)

            builder.setMessage(msg)
                .setTitle("温馨提示")

                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
            if (force) {
                builder.addAction("关闭") { dialog, index ->
                    finish()
                }
            }
            builder.addAction(
                "去设置"
            ) { dialog, index ->
                NetworkUtils.openWirelessSettings()
            }
            netErrorDialog = builder.show()
            netErrorDialog?.hideNavigationBar()
        }
    }

}


class YzxJavascriptInterface(var ctx: Activity) {

    /**
     * 获取电子书的clientId
     */
    @JavascriptInterface
    fun getClientId(): Int = 602

    /**
     * 提示
     */
    @JavascriptInterface
    fun toast(msg: String) {
        ctx.toast("android:$msg")
    }

    /**
     * 检查版本升级
     */
    @JavascriptInterface
    fun mCheckVersion() {
        Log.d("mCheckVersion", "mCheckVersion: -------------------->")
        val act = ctx as WebActivity
        act.checkVersion(true)
    }

    /**
     * 保存用户信息
     */
    @JavascriptInterface
    fun saveUserInfo(json: String) {
        val resultType = object : TypeToken<User>() {}.type
        val gson = Gson()
        val user = gson.fromJson<User>(json, resultType)
        EventBus.getDefault().post(UserLoginEvent())
        user?.save()
    }

    @JavascriptInterface
    fun saveUnitCount(count: Int) {
        User.saveUnitCount(count)
    }

    @JavascriptInterface
    fun toHome() {
        ctx.startActivity<MainActivity>()
        ctx.finish()
    }

    @JavascriptInterface
    fun logout() {
        val sp = SPUtils.getInstance()
        sp.remove("user_name")
        sp.remove("user_id")
        sp.remove("type")
        sp.remove("token")
        sp.remove("school_id")
        sp.remove("school_name")
        sp.remove("phone")
        sp.remove("grade_name")
        sp.remove("grade_id")
        sp.remove("class_name")
        sp.remove("class_id")
        sp.remove("ticket")
        sp.remove("login_start")
        sp.remove("unit_count")
        ctx.startActivity<HomeActivity>()
    }

}




















