package com.xty.base.act

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.annotation.Route
import com.tamsiree.rxkit.RxNetTool
import com.tamsiree.rxkit.RxTool
import com.xty.base.databinding.ActAgreementReadWebBinding
import com.xty.base.databinding.ActWebBinding
import com.xty.common.LogUtils
import com.xty.common.R
import com.xty.common.arouter.ARouterUrl
import java.util.*


/**
 * webview  协议阅读
 */
@Route(path = ARouterUrl.AGREEMNT_READ_WEB_ACT)
class AgreementReadWebAct : IBaseAct() {
    var maxInt=4
    lateinit var timer: Timer
    private var isAgree=true
    val timerLive by lazy { MutableLiveData<String>() }

    val binding by lazy { ActAgreementReadWebBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root
    private var url = ""
    private var titleName = ""
    override fun initData() {
        super.initData()
        isDarkBar = true
        intent.extras?.let {
            url = it.getString("url", "")
            titleName = it.getString("title", "")
            isAgree = it.getBoolean("isAgree",true)

        }
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvTitle.text = titleName
        initWebSettings()
        timer=Timer()
        binding.mAgree.isSelected=false
        binding.mAgree.isEnabled=false
        if(isAgree){
            binding.mAgree.visibility=View.VISIBLE
        }else{
            binding.mAgree.visibility=View.GONE
        }

        timer.schedule(object :TimerTask(){
            override fun run() {
                timerLive.postValue("")
            }
        },0,1000)

        timerLive.observe(this){
            --maxInt
            if(maxInt==0){
                timer.cancel()
                maxInt=10
                binding.mAgree.text=getString(com.xty.base.R.string.agree)
                binding.mAgree.isSelected=true
                binding.mAgree.isEnabled=true
            }else{
                binding.mAgree.text = "${getString(com.xty.base.R.string.agree)}($maxInt)"
                binding.mAgree.isSelected=false
                binding.mAgree.isEnabled=false
            }

        }

        binding.mAgree.setOnClickListener {
            setResult(RESULT_OK)
            finish()
        }
        binding.mWeb.loadUrl(url)

    }


    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebSettings() {
        binding.mWeb.isHorizontalScrollBarEnabled = false //水平不显示
        binding.mWeb.isVerticalScrollBarEnabled = false //垂直不显示
        var webViewClient = MyClient()

        binding.mWeb.apply {
                isHorizontalScrollBarEnabled = false //水平不显示
                isVerticalScrollBarEnabled = false //垂直不显示

                val webSetting: WebSettings =  settings
                webSetting.apply {
                    setRenderPriority(WebSettings.RenderPriority.HIGH)
                    cacheMode = if (RxNetTool.isConnected(RxTool.getContext())) {
                        WebSettings.LOAD_DEFAULT // 设置缓存模式
                    } else {
                        WebSettings.LOAD_CACHE_ELSE_NETWORK // 设置缓存模式
                    }
                    loadWithOverviewMode = true
                    domStorageEnabled = true//不添加可能加载H5的页面时候出现一片空白
                    databaseEnabled = true
                    setAppCacheEnabled(true)
                    allowFileAccess = true
                    javaScriptEnabled = true
                    textZoom=110
                    useWideViewPort = false//设置此属性，可任意比例缩放
                    setLayerType(View.LAYER_TYPE_HARDWARE, null) // 启用硬件加速
                    layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
                    builtInZoomControls = false //设置内置的缩放控件。若为false，则该WebView不可缩放
                    displayZoomControls = false //隐藏原生的缩放控件
                    defaultTextEncodingName = "utf-8" //设置编码格式
                    blockNetworkImage = false //解决图片不显示
                    loadsImagesAutomatically = true //支持自动加载图片
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        setAllowFileAccessFromFileURLs(true)
                        setAllowUniversalAccessFromFileURLs(true)
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//解决视频加载不出来的问题
                        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
                    }
                }
                webViewClient = webViewClient
                webChromeClient = object : WebChromeClient() {
                    override fun getDefaultVideoPoster(): Bitmap? {

                        try{
                            //这个地方是加载h5的视频列表 默认图   点击前的视频图
                            LogUtils.d("WebView---------加载视频默认图片");
                            return BitmapFactory.decodeResource( context.getResources(),
                                R.mipmap.ic_chat_picture);

                        }catch( e:Exception){
                            LogUtils.e("WebView---------默认图片加载失败");

                        }

                        return  null
                    }

                }
        }
    }

    override fun onPause() {
        super.onPause()
        //暂停WebView在后台的所有活动
        binding.mWeb.onPause()
        //暂停WebView在后台的JS活动
        binding.mWeb.pauseTimers()
    }

    override fun onResume() {
        super.onResume()
        binding.mWeb.onResume();
        binding.mWeb.resumeTimers();
    }

    override fun onDestroy() {
        super.onDestroy()
        if(timer!=null){
            timer.cancel()
        }
        binding.root.removeView(binding.mWeb)
        binding.mWeb.destroy()
    }

    inner  class MyClient : WebViewClient(){
        override fun shouldOverrideUrlLoading(p0: WebView?, p1: String): Boolean {
            p0?.loadUrl(p1)
            return true
        }
    }
}


