package com.swago.baseswago.activity

import android.annotation.SuppressLint
import android.net.Uri
import android.os.Build
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.*
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.swago.baseswago.R
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.databinding.ActivityWebBinding
import com.swago.baseswago.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**
 *@date 2021/8/30 10:19
 *description:
 */
@Route(path = ARouteConstant.Base.webView)
class WebViewActivity : BaseXActivity<ActivityWebBinding>() {

    @Autowired
    @JvmField
    var url = ""

    private var webView: WebView? = null

    private val jsLoad by lazy {
        JSLoad()
    }

    override fun loadData() {
    }

    override fun initOther() {
        ARouter.getInstance().inject(this)
        setBackView(binding.toolbar.ivBack)

        webView = WebView(this)
        webView?.apply {
            try {
                val jsonObject = JSONObject()
                jsonObject.put("TokenParam", UserInfo.getLoginModel()?.token?:"")
                jsonObject.put("UserIdParam", UserInfo.getUserInfo()?.id?:"")
                jsonObject.put("LocaleParam", SwagoInfo.getLanguageCode())
                jsonObject.put("AppVersionParam", SwagoInfo.getVersionCode())
                jsonObject.put("ClientParam", SwagoInfo.getAppClient())
                jsonObject.put("ChannelParam", SwagoInfo.getChannel())
                jsonObject.put("DeviceParam", SwagoInfo.getDeviceInfo())
                settings.userAgentString = settings.userAgentString + jsonObject.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            if (Build.VERSION.SDK_INT >= 21) {
                settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }

            settings.javaScriptEnabled = true
            addJavascriptInterface(jsLoad, "jsLoad")
            settings.allowUniversalAccessFromFileURLs = true
            settings.allowFileAccess = true
            settings.allowFileAccessFromFileURLs = true
            settings.useWideViewPort = true
            settings.loadWithOverviewMode = true
            settings.javaScriptCanOpenWindowsAutomatically = true//设置允许JS弹窗
            settings.domStorageEnabled = true
            isHorizontalScrollBarEnabled = true
            isVerticalScrollBarEnabled = true
            clearCache(true)
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest?
                ): Boolean {
                    return super.shouldOverrideUrlLoading(view, request)
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    view?.title?.let {
                        binding.toolbar.tvTitle.text = it
                    }
                }
            }

            webChromeClient = object:WebChromeClient(){
                override fun onShowFileChooser(
                    webView: WebView?,
                    filePathCallback: ValueCallback<Array<Uri>>?,
                    fileChooserParams: FileChooserParams?
                ): Boolean {
                    var compressPicPath = ""
                    EasyPhotos.createAlbum(
                        this@WebViewActivity,
                        true,
                        false,
                        GlideEngine.getInstance()
                    )
                        .setFileProviderAuthority(AppContext.getContext().packageName + "/fileprovider")
                        .setCount(1)//参数说明：最大可选数，默认1
                        .start(object : SelectCallback() {
                            override fun onResult(
                                p0: java.util.ArrayList<Photo>?,
                                isOriginal: Boolean
                            ) {
                                if (p0 != null && p0.size > 0) {
                                    //上传前压缩
                                    Luban.with(this@WebViewActivity)
                                        .load(p0[0].path)
                                        .ignoreBy(100)
                                        .setCompressListener(object : OnCompressListener {
                                            override fun onStart() {
                                            }

                                            override fun onSuccess(file: File?) {
                                               if (file == null){
                                                   filePathCallback?.onReceiveValue(null)
                                               }else{
                                                   compressPicPath = file.toString()
                                                   val array = Array<Uri>(1) {Uri.fromFile(File(compressPicPath))}
                                                   filePathCallback?.onReceiveValue(array)
                                               }
                                            }

                                            override fun onError(e: Throwable?) {
                                                filePathCallback?.onReceiveValue(null)
                                            }

                                        }).launch()
                                }
                            }

                            override fun onCancel() {
                                filePathCallback?.onReceiveValue(null)
                            }
                        })
                    return true
                }
            }

            //设置大小
            val params = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                0
            ).apply {
                startToStart = R.id.root
                endToEnd = R.id.root
                topToBottom = R.id.toolbar
                bottomToBottom =R.id.root
            }
            this.layoutParams = params
            binding.root.addView(this)
        }
        webView?.loadUrl(url)
    }

    inner class JSLoad {
        @JavascriptInterface
        fun closeGame(){
        }
    }

    override fun initLiveData() {}


    override fun onBackPressed() {
        goBack()
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack()
            return true
        }
        return false
    }

    private fun goBack() {
        webView?.let { webView->
            if (webView.canGoBack()) {
                webView.url?.let {
                    if (it.contains(url)  || it.contains("withdrawal")) {
                        webView.goBack()
                    } else {
                        finish()
                    }
                }
            } else {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            webView?.apply {
                webChromeClient = null
                stopLoading()
                clearHistory()
                removeAllViews()
                clearCache(true)
                destroy()
                binding.root.removeAllViews()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}