package com.quansu.heifengwuliu.fragment

import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.webkit.*
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.quansu.heifengwuliu.R
import com.quansu.heifengwuliu.base.MBFragment
import com.quansu.heifengwuliu.databinding.FragmentWebBinding
import com.quansu.heifengwuliu.view.FuncShopView
import com.ysnows.base.base.BRepository
import com.ysnows.base.base.BViewModel
import com.ysnows.base.view.ProgressView
import java.io.UnsupportedEncodingException
import java.net.URLEncoder

class WebFragment : MBFragment<BViewModel<BRepository>, FragmentWebBinding>(), ProgressView {
    protected var refresh_layout: SwipeRefreshLayout? = null
    protected var webview: WebView? = null
    protected var url = "https://www.baidu.com"
    protected var rootView: View? = null
    protected var layWebview: LinearLayout? = null
    protected var imgAvatar: ImageView? = null
    protected var edtName: EditText? = null
    protected var imgScan: ImageView? = null
    protected var recyclerView: RecyclerView? = null
    protected var layNormal: LinearLayout? = null
    private var progress: ProgressBar? = null
    override fun __before(savedInstanceState: Bundle?) {
        super.__before(savedInstanceState)
        val extras = arguments
        if (extras != null) {
            url = extras.getString("url", "https://www.baidu.com")
        }
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

//        P().Q(NetEngine.getService().getFuncs(2, 1), new OnRes<ArrayList<Func>>() {
//            @Override
//            public void onCall(IResponse<ArrayList<Func>> res) {
//                if (res.ok()) {
//                    webAppAdapter.setNewData(res.data());
//                }
//            }
//        });
    }

    override fun listeners() {
        super.listeners()
        imgScan!!.setOnClickListener { v: View? -> toast(resources.getString(R.string.jingqingqidai)) }
        edtName!!.setOnEditorActionListener { v: TextView?, actionId: Int, event: KeyEvent? ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val kw = edtName!!.text.toString()
                if (kw.startsWith("http://") || kw.startsWith("https://")) {
                    url = kw
                } else {
                    var encodeStr: String? = null
                    try {
                        encodeStr = URLEncoder.encode(kw, "UTF-8")
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
                    url = String.format("https://m.baidu.com/s?wd=%s", encodeStr)
                }
                loadUrl(url)
            }
            false
        }
    }

    override fun binding(inflater: LayoutInflater, container: ViewGroup?): FragmentWebBinding {
        return FragmentWebBinding.inflate(layoutInflater)
    }

    override fun initView(rootView: View?) {
        super.initView(rootView)
        webview = rootView!!.findViewById(R.id.webview)
        progress = rootView.findViewById(R.id.progress)
        refresh_layout = rootView.findViewById(R.id.refresh_layout)
        layWebview = rootView.findViewById(R.id.lay_webview)
        imgAvatar = rootView.findViewById(R.id.img_avatar)
        edtName = rootView.findViewById(R.id.edt_name)
        imgScan = rootView.findViewById(R.id.img_scan)
        recyclerView = rootView.findViewById(R.id.recycler_view)
        layNormal = rootView.findViewById(R.id.lay_normal)

//        webAppAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Func item = (Func) adapter.getItem(position);
//                loadUrl(item.url);
//
//            }
//        });

        /*下拉刷新设置*/if (refresh_layout != null) {
            refresh_layout!!.setColorSchemeResources(R.color.refresh_colorPrimary, R.color.refresh_colorAccent, R.color.refresh_colorPrimaryDark)
            refresh_layout!!.setOnRefreshListener { onRefresh() }
            refresh_layout!!.isEnabled = isNeedRefresh
        }
        val webSettings = webview?.getSettings()
        webSettings?.javaScriptEnabled = true
        webSettings?.domStorageEnabled = true
        webSettings?.setAppCacheEnabled(true)
        webSettings?.pluginState = WebSettings.PluginState.ON
        webSettings?.useWideViewPort = true // 关键点
        webSettings?.allowFileAccess = true // 允许访问文件
        webSettings?.cacheMode = WebSettings.LOAD_NO_CACHE //没有缓存LOAD_NO_CACHE
        webSettings?.databaseEnabled = true
        webSettings?.builtInZoomControls = true
        webSettings?.displayZoomControls = false
        webSettings?.loadWithOverviewMode = true
        // 支持通过js打开新的窗口
        webSettings?.javaScriptCanOpenWindowsAutomatically = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webSettings?.setSupportZoom(false)
        webview?.setWebViewClient(object : WebViewClient() {
            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
                super.onPageStarted(view, url, favicon)
                val activity = activity
                if (activity != null) {
                    (activity as FuncShopView).setWebUrl(url)
                }
            }

            override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
                view.loadUrl(request.url.toString())
                return true
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                refreshing(false)
                onProgressFinished()
            }
        })
        webview?.setWebChromeClient(object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                if (titleBar != null) {
                    titleBar!!.setTitle(title)
                }
                val activity = activity
                if (activity != null) {
                    (activity as FuncShopView).setWebName(title)
                }
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                onProgress(newProgress)
            }
        })
    }

    private fun loadUrl(url: String) {
        webview!!.loadUrl(url)
        layNormal!!.visibility = View.GONE
        (activity as FuncShopView?)!!.setNormalVisibility(View.GONE)
    }

    @Subscribe(tags = [Tag("WebViewBack")])
    fun back(msg: String?) {
        if (webview!!.canGoBack()) {
            webview!!.goBack()
        } else {
            layNormal!!.visibility = View.VISIBLE
            (activity as FuncShopView?)!!.setNormalVisibility(View.VISIBLE)
        }
    }

    override val isNeedRefresh: Boolean
        get() = true

    override fun onRefresh() {
        webview!!.reload()
    }

    override fun refreshing(refreshing: Boolean) {
        refresh_layout!!.isRefreshing = refreshing
    }

    override fun onProgress(progress: Int) {
        this.progress!!.visibility = View.VISIBLE
        this.progress!!.progress = progress
    }

    override fun onProgressFinished() {
        progress!!.visibility = View.GONE
    }

    override fun title(): String? {
        return null
    }

    override val isRxbus: Boolean
        get() = true
}