package com.ym.game.activity

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Handler
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.webkit.*
import android.widget.*
import com.airbnb.lottie.LottieAnimationView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.zxing.WriterException
import com.tencent.ep.commonbase.api.Log
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.ym.xynt.R
import com.ym.game.monopoly.LollipopFixedWebView
import com.ym.game.utils.ZxingUtils
import com.ym.library.activity.JavaInterface
import com.ym.library.module.ShareInfoEntity
import com.ym.library.net.BaseObserver
import com.ym.library.net.GameApiClient
import com.ym.library.net.MyBaseActivity
import com.ym.library.net.RxSchedulers
import com.ym.library.utils.Utils
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.utils.LogUtils
import com.ym.modulecommon.utils.StatusBarUtil

/**
 * @author (wangXuewei)
 * @datetime 2020-12-11 20:42 GMT+8
 * @detail :
 */
class MonopolyWebActivity : MyBaseActivity() {
    private var url: String? = null
    private var title: String? = null
    private var webView: LollipopFixedWebView? = null
    private var pg: ProgressBar? = null
    private var rl_anim: RelativeLayout? = null
    private var ll_web: LinearLayout? = null
    private var tvname: TextView? = null
    private var tvinvitecode: TextView? = null
    private var id_rl_share_image: RelativeLayout? = null
    private var imghead: ImageView? = null
    private var id_iv_qcode: ImageView? = null
    override fun layoutID(): Int {
        return R.layout.activity_monopoly_webview
    }

    override fun init() {
        StatusBarUtil.transportStatus(
            this,
            resources.getColor(com.ym.library.R.color.transparent)
        )
        title = intent.data!!.getQueryParameter("title")
        if (title == "分红") {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }
        url = intent.data!!.getQueryParameter("url")
        title = intent.data!!.getQueryParameter("title")
        LogUtils.e("huang   url:$url")
        val id_lottie_dreams_come_true =
            findViewById<LottieAnimationView>(R.id.id_lottie_dreams_come_true)
        ll_web = findViewById(R.id.ll_web)
        rl_anim = findViewById(R.id.rl_anim)
        rl_anim?.setVisibility(View.VISIBLE)
        id_lottie_dreams_come_true.setImageAssetsFolder("hloading/images/")
        id_lottie_dreams_come_true.setAnimation("hloading/data.json")
        id_lottie_dreams_come_true.repeatCount = -1
        id_lottie_dreams_come_true.playAnimation()
        initWebView()
        initTitle()
        if(title.equals("邀请赚钱")){
            initShare()
        }

    }

    private fun initShare() {
        GameApiClient.gameApi.initShare()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<ShareInfoEntity>() {
                override fun onSuccess(result: ShareInfoEntity?) {
                    if (result != null) {
                        setShareResult(result)
                    }

                }

                override fun onFailure(
                    e: Throwable?,
                    code: String?,
                    errorMsg: String?
                ) {

                }
            })


    }

    fun setShareResult(result: ShareInfoEntity?) {

    }

    private val shareListener: UMShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {}

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {
            Utils.showToast(AppliContext.get(), "分享成功")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {
            Utils.showToast(AppliContext.get(), "分享失败")
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {
            Utils.showToast(AppliContext.get(), "分享取消")
        }
    }

    private fun loadBitmapFromView(v: View): Bitmap {
        val bmp = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        c.drawColor(Color.WHITE)
//        * 如果不设置canvas画布为白色，则生成透明
        v.layout(0, 0, v.width, v.height)
        v.draw(c)
        return bmp
    }

    private fun initWebView() {
        pg = findViewById(R.id.progressBar)
        webView = findViewById(R.id.activity_webview)
        webView?.getSettings()?.useWideViewPort = true
        webView?.getSettings()?.loadWithOverviewMode = true
        webView?.setLayerType(View.LAYER_TYPE_HARDWARE, null) //开启硬件加速
        //        webView.getSettings().setDefaultFontSize(56);
        // webView.getSettings().setMinimumFontSize(40);//设置最小字体
        // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
        webView?.getSettings()?.cacheMode = WebSettings.LOAD_DEFAULT
        webView?.getSettings()?.setAppCacheEnabled(true)

        // 设置不使用默认浏览器，而直接使用WebView组件加载页面。


        // 设置WebView组件支持加载JavaScript。
        webView?.getSettings()?.javaScriptEnabled = true
        // 建立JavaScript调用Java接口的桥梁。
        webView?.getSettings()?.javaScriptCanOpenWindowsAutomatically = true
        WebView.setWebContentsDebuggingEnabled(true)

        // 解决对某些标签的不支持出现白屏
        webView?.getSettings()?.domStorageEnabled = true
        webView?.addJavascriptInterface(
            WebJavaInterface(
                this,
                webView!!
            ), "android"
        )
        webView?.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView,
                url: String
            ): Boolean {
                view.loadUrl(url)
                return true
            }
        })
        webView?.setWebChromeClient(object : WebChromeClient() {
            override fun onProgressChanged(
                view: WebView,
                newProgress: Int
            ) {
                if (newProgress == 100) {
                    pg?.setVisibility(View.GONE) //加载完网页进度条消失
                    ll_web!!.visibility = View.VISIBLE
                    rl_anim!!.visibility = View.GONE
                } else {
                    pg?.setVisibility(View.VISIBLE) //开始加载网页时显示进度条
                    pg?.setProgress(newProgress) //设置进度值
                }
            }
        })
        webView?.loadUrl(url)
        //        webView.loadDataWithBaseURL(null, url, "text/html", "utf-8", null);//解决乱码问题
    }

    var bp: Bitmap? = null
    fun initcreatImg() {
        id_rl_share_image?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                bp = loadBitmapFromView(id_rl_share_image!!)
               // webView!!.loadUrl("javascript:obtainPoster('$img')")
//                    if (bp != null) {
//                        ShareAction(this@MonopolyWebActivity)
//                            .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
//                            //.withText("hello")//分享内容
//                            .withMedia(UMImage(this@MonopolyWebActivity, bp))
//                            .setCallback(shareListener)//回调监听器
//                            .share()
//                    }

                id_rl_share_image?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
            }
        })

        //  mWebView.loadUrl("javascript:closeWindows('$type','$shutdownType')")

    }

    private fun initTitle() {
        val id_rl_toolbar =
            findViewById<RelativeLayout>(com.ym.library.R.id.id_rl_toolbar)
        if (intent.data!!.getBooleanQueryParameter("showToolbar", true)) {
            id_rl_toolbar.visibility = View.VISIBLE
        } else {
            id_rl_toolbar.visibility = View.GONE
        }
        findViewById<View>(com.ym.library.R.id.id_iv_back).setOnClickListener { finish() }
        val tv_title =
            findViewById<TextView>(com.ym.library.R.id.tv_user_toolbar_title)
        tv_title.text = title
    }

    override fun onResume() {
        super.onResume()
        if (webView != null) {
            webView!!.loadUrl("javascript:onResume()")
        }
    }

    override fun onPause() {
        super.onPause()
        if (webView != null) {
            webView!!.loadUrl("javascript:onPause()")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (webView != null) {
            val parent = webView!!.parent
            if (parent != null) {
                (parent as ViewGroup).removeView(webView)
            }
            webView!!.removeAllViews()
            webView!!.destroy()
            webView = null
        }
    }

    inner class WebJavaInterface(act: Activity, web: WebView) : JavaInterface(act, web) {

        @JavascriptInterface
        fun InviteFriend() {
            Log.d("chromium", "!!!!")
            //   val bp: Bitmap = loadBitmapFromView(id_rl_share_image!!)
            if (bp != null) {
                ShareAction(this@MonopolyWebActivity)
                    .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                    //.withText("hello")//分享内容
                    .withMedia(UMImage(this@MonopolyWebActivity, bp))
                    .setCallback(shareListener)//回调监听器
                    .share()
            }

        }
    }
}