package com.ym.library.activity


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.webkit.*
import androidx.annotation.RequiresApi
import com.badoo.mobile.util.WeakHandler
import com.umeng.analytics.MobclickAgent
import com.umeng.socialize.UMShareAPI
import com.ym.library.R
import com.ym.library.module.CoinEntity
import com.ym.library.module.NewsEntity
import com.ym.library.module.TaskEntity
import com.ym.library.net.ApiClient
import com.ym.library.net.MyBaseActivity
import com.ym.library.net.BaseObserver
import com.ym.library.net.RxSchedulers
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusUtil
import com.ym.library.utils.*
import com.ym.library.widget.ScrollWebView
import com.ym.modulecommon.AppliContext
import kotlinx.android.synthetic.main.activity_web.*
import java.util.regex.Pattern


/**
 * Created by gaoleichao on 2018/5/8.
 */

class WebActivity : MyBaseActivity(), View.OnClickListener {

    private val TAG = "WebActivity"

    private val INIT: Int = 1
    private val ING: Int = 2
    private val PAUSE: Int = 3
    private val STOP: Int = 4
    private val START: Int = 5
    private val OVER: Int = 6
    private var status: Int = INIT

    private var videoSrc: String? = null
    private var mUrlList: MutableList<String>? = null
    private var title: String? = null
    private var url: String = ""
    private var slot_id: String? = null
    private var alert: String? = null
    private var deep_url_re: String? = null
    private var timeTrigger: String? = null
    private var incentive_level: Int = 0
    private var sid: Int = 0
    private var delay: Int = 0

    private var mJavaInterFace: WebJavaScriptInterface? = null

    private var mWeakHandler: WeakHandler? = null


    private var isAdd = false
    private var isReward = false


    private var pkg: String? = null
    private var session_id: String = ""
    private var alertRenderType: String? = ""

    private var isKeyEnabled: Boolean = false

    private var mCurrentTime: Int = 0

    private var isSuc = false
    private var mPageUrl = ""

    private var mUploadMessage: ValueCallback<Uri>? = null
    private var mUploadCallbackAboveL: ValueCallback<Array<Uri>>? = null
    private val PERMISSION_CAMERA = 101
    private var imageUri: Uri? = null
    private var isPhotoCannle: Boolean = false

    override fun layoutID(): Int {
        return R.layout.activity_web
    }

    override fun before() {
        super.before()
        StatusBarUtil.setLightMode(this)
    }

    override fun init() {
        initData()
        initView()
//        initPhotoDialog)
        initWebView()
        setOnListener()
    }

    private fun initData() {
        // 完整的url信息
        title = intent.getStringExtra("title") ?: ""
        url = intent.getStringExtra("url") ?: ""
        alert = intent.getStringExtra("alert") ?: ""
        slot_id = intent.getStringExtra("slot_id") ?: ""
        deep_url_re = intent.getStringExtra("deep_url_re") ?: ""
        timeTrigger = intent.getStringExtra("timeTrigger") ?: ""
        alertRenderType = intent.getStringExtra("alertRenderType") ?: ""
        val incentive = intent.getStringExtra("incentive_level") ?: ""
        if (!TextUtils.isEmpty(incentive) && !TextUtils.equals(incentive, "null")) {
            incentive_level = Integer.valueOf(incentive)
        }
        val de = intent.getStringExtra("delay") ?: ""
        if (!TextUtils.isEmpty(de) && !TextUtils.equals(de, "null")) {
            delay = Integer.valueOf(de)
        }
        val s = intent.getStringExtra("sid") ?: ""
        if (!TextUtils.isEmpty(s) && !TextUtils.equals(s, "null")) {
            sid = Integer.valueOf(s)
        }

        if (TextUtils.isEmpty(url)) {
            finish()
        }
        session_id = Utils.md5(url)


        mWeakHandler = WeakHandler()
    }

    private fun initView() {
        window.setFormat(PixelFormat.TRANSLUCENT)
        if (TextUtils.isEmpty(title) || TextUtils.equals(title, "null")) {
            id_activity_web_title?.text = ""
        } else {
            id_activity_web_title?.text = title
        }

        if (incentive_level == 3 || incentive_level == 7 || incentive_level == 8) {
            mUrlList = arrayListOf()
            queryTask()
        }

        webview?.setDelay(delay)
    }

    private fun setOnListener() {
        id_activity_web_back_layout?.setOnClickListener {
            if (webview?.canGoBack() == true) {
                webview?.goBack()
            } else {
                finish()
            }
        }

        id_activity_web_close?.setOnClickListener { finish() }

        webview?.setOnScrollChangeListener(object : ScrollWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {

            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {

            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                if (!TextUtils.equals(
                        Utils.replaceAll(url),
                        Utils.replaceAll(mPageUrl)
                    ) && (incentive_level == 3 || incentive_level == 8)
                ) {
                    if (TextUtils.isEmpty(mPageUrl)) {
                        return
                    }
                    if (mUrlList?.contains(mPageUrl) != true) {
                        if (status == INIT) {
                            mCurrentTime = 0
                            startTimer()
                        }
                    }
                }
                if (incentive_level == 7) {
                    if (status == INIT) {
                        mCurrentTime = 0
                        startTimer()
                    }
                }
            }
        })
        webview?.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            if (!TextUtils.isEmpty(videoSrc) && !TextUtils.equals(videoSrc, "null")) {

            } else {
                try {
                    val uri = Uri.parse(url)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    AppliContext.get().startActivity(intent)
                } catch (e: Exception) {
                }

            }
        })
        webview?.webChromeClient = object : MyWebChromeClient() {
            override fun onProgressChanged(webView: WebView, i: Int) {
                if (i != 100) {
                    id_activity_web_progress?.progress = i
                } else {
                    id_activity_web_progress?.visibility = View.GONE
                }
                if (i == 100) {
                    if (isAdd) {
                        return
                    }
                    if (incentive_level == 1) {
                        if (delay > 0) {
                            if (!TextUtils.isEmpty(alert) && !TextUtils.equals(alert, "null")) {
                                setTimerLayoutView(alert ?: "")
                            } else {
                                setTimerLayoutView("")
                            }
                            startTimer()
                        } else {
                            mJavaInterFace?.addCoin(
                                url
                                    ?: return, CoinEntity.EXTERNAL_SDK_AD_TYPE
                            )
                        }
                    } else if (incentive_level == 2) {
                        if (!TextUtils.isEmpty(alert) && !TextUtils.equals(alert, "null")) {
                            setTimerLayoutView(alert ?: "")
                        } else {
                            setTimerLayoutView("")
                        }
                    }
                }
            }

        }
        webview?.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView, urls: String, favicon: Bitmap?) {
                if (!TextUtils.equals(urls, url)) {
                    id_activity_web_close?.visibility = View.VISIBLE
                } else {
                    id_activity_web_close?.visibility = View.GONE
                }
                super.onPageStarted(view, url, favicon)
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                Log.d("glc", url)
                if (TextUtils.isEmpty(url)) return false
                try {
                    if (!url.startsWith("http") && !url.startsWith("https") && !url.startsWith("ftp")) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        if (isInstall(intent)) {
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            AppliContext.get().startActivity(intent)
                        }
                        return true
                    }
                } catch (e: Exception) {
                    return false
                }

                return false
            }

            override fun onPageFinished(view: WebView, urls: String) {
                super.onPageFinished(view, urls)
                mPageUrl = urls
                if (incentive_level == 2) {
                    if (isAdd) {
                        return
                    }
                    if (TextUtils.isEmpty(deep_url_re) || TextUtils.equals(deep_url_re, "null")) {
                        return
                    }

                    val url = view.url
                    if (TextUtils.isEmpty(url)) {
                        return
                    }
                    try {
                        val pattern = Pattern.compile(deep_url_re)
                        if (!isReward && null != pattern && pattern.matcher(url).matches()) {
                            isReward = true
                            val entity = NewsEntity()
                            entity.sid = sid
                            entity.slot_id = slot_id
//                            AdUpload.onDeepClick(entity)
                            if (delay > 0) {
                                startTimer()
                            } else {
                                mJavaInterFace?.addCoin(
                                    mPageUrl
                                        ?: return, CoinEntity.EXTERNAL_SDK_AD_TYPE
                                )
                            }
                        }
                    } catch (e: Exception) {

                    }

                }
                if (!TextUtils.isEmpty(videoSrc) && !TextUtils.equals(videoSrc, "null")) {
                    webview?.loadUrl("javascript:videoPlay()")
                }
                if (incentive_level == 8) {
                    mCurrentTime = 0
                    id_activity_web_timer_progress?.progress = mCurrentTime
                    RxTimerUtil.cancel()
                    status = INIT
                }
                if (!TextUtils.equals(url, mPageUrl)) {
//                    EventUtils.onH5AdClick(session_id, mPageUrl)
                }
            }

            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                handler.proceed() // 接受所有网站的证书
            }
        }

    }

    @SuppressLint("JavascriptInterface")
    private fun initWebView() {
        webview?.loadUrl(url)
        mJavaInterFace = WebJavaScriptInterface(this, webview)
//        if (sid == 1919) {
        webview?.addJavascriptInterface(mJavaInterFace, "android")
//        } else {
//            webview?.addJavascriptInterface(mJavaInterFace, "novel")
//        }
    }

    private fun coins(url: String, type: Int) {
        Log.d("WebActivity", " in:" + incentive_level)
        ApiClient.userApi.addCoins(Utils.md5(url), 201, sid.toString(), slot_id?:"")
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<CoinEntity>() {
                @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
                override fun onSuccess(result: CoinEntity?) {
                    if (result != null && result.coins > 0) {
                        var text = "阅读奖励  金币+" + result.coins
                        CenterDialog.showNewCoinsDialog(this@WebActivity, result.coins)
                        isSuc = true
                        status = OVER
                        setTimerLayoutGone()
                        id_activity_web_top_tips?.visibility = View.GONE
                        id_activity_web_top_tips?.text = ""
                    } else {
                        isAdd = false
                        if (sid == 347) {
                            Utils.showToast(applicationContext, "搜索完成次数+1")
                        }
                        if (incentive_level == 3 || incentive_level == 7 || incentive_level == 8) {
                            mUrlList?.add(url)
                            queryTask()
                        }
                    }
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
                    isAdd = false
                    if ((incentive_level == 3 || incentive_level == 8) && TextUtils.equals("155", code)) {
                        mUrlList?.add(url)
                    }
                    if (incentive_level == 3 || incentive_level == 7 || incentive_level == 8) {
                        queryTask()
                    }

                    if (TextUtils.equals("105", code)) {
                        Utils.showToast(AppliContext.get(), errorMsg)
                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        webview?.visibility = View.GONE
        RxTimerUtil.cancel()
        if (null != webview) {
            webview?.loadUrl("javascript:onDestroy()")
            webview?.destroy()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (null != webview && webview?.canGoBack() == true) {
            webview?.goBack()
        }
    }

    override fun onResume() {
        super.onResume()
        if (webview != null) {
            webview?.loadUrl("javascript:onResume()")
        }
//        EventUtils.onEvent("page_status", Utils.obj2Str(
//            ReportEntity(
//                Constant.ReportSessionId,
//                "WebActivity",
//                "onResume"
//            )
//        ))
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        if (webview != null) {
            webview?.loadUrl("javascript:onPause()")
        }
        RxTimerUtil.cancel()
        status = INIT
//        EventUtils.onEvent("page_status", Utils.obj2Str(
//            ReportEntity(
//                Constant.ReportSessionId,
//                "WebActivity",
//                "onPause"
//            )
//        ))
        MobclickAgent.onPause(this)
        RxBusUtil.getDefault()
            .send(RxBusConstant.RX_SPEED_WATER_TASK_LIST)
        RxBusUtil.getDefault()
            .send(RxBusConstant.RX_MAIN_WATER_DROP_UPDATE)
    }

    private fun queryTask() {
        if (sid == 0) {
            return
        }
        ApiClient.taskApi.queryTaskStatus(sid.toString(), slot_id?:"").compose(RxSchedulers.observableIO2Main(this))
            .subscribe(object : BaseObserver<TaskEntity>() {
                override fun onSuccess(entity: TaskEntity?) {
                    if (entity == null || TextUtils.isEmpty(entity.coins) || TextUtils.equals(entity.coins, "null")) {
                        return
                    }
                    if (entity.delay > 0) {
                        delay = entity.delay
                        status = INIT
                    }
                    if (incentive_level == 3 || incentive_level == 8) {
                        if (TextUtils.equals("1", alertRenderType)) {
                            id_activity_web_top_tips?.visibility = View.GONE
                            if (!TextUtils.isEmpty(entity.alert) && !TextUtils.equals(entity.alert, "null")) {
                                setTimerLayoutView(entity.alert)
                            } else {
                                setTimerLayoutView("")
                            }
                        } else {
                            id_activity_web_top_tips?.visibility = View.VISIBLE
                            id_activity_web_top_tips?.text = entity.alert?.replace("\n", "")
                            setTimerLayoutGone()
                        }

                    }

                    if (incentive_level == 7) {
                        if (TextUtils.equals("1", alertRenderType)) {
                            id_activity_web_top_tips?.visibility = View.GONE
                            if (!TextUtils.isEmpty(entity.alert) && !TextUtils.equals(entity.alert, "null")) {
                                setTimerLayoutView(entity.alert)
                            } else {
                                setTimerLayoutView("")
                            }
                        } else {
                            id_activity_web_top_tips?.visibility = View.VISIBLE
                            id_activity_web_top_tips?.text = entity.alert?.replace("\n", "")
                            setTimerLayoutGone()
                        }
                    }

                }

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

                }
            })
    }

    private fun setTimerLayoutView(alert: String) {
        id_activity_web_timer_layout?.visibility = View.VISIBLE
        id_activity_web_timer_desc?.text = alert
        id_activity_web_timer_progress?.maxProgress = delay
        id_activity_web_timer_progress?.progress = 0
    }

    private fun setTimerLayoutGone() {
        id_activity_web_timer_layout?.visibility = View.GONE
        id_activity_web_timer_progress?.progress = 0
    }

    //判断app是否安装
    private fun isInstall(intent: Intent): Boolean {
        return AppliContext.get().packageManager.queryIntentActivities(
            intent,
            PackageManager.MATCH_DEFAULT_ONLY
        ).size > 0
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isKeyEnabled) {
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    internal inner class WebJavaScriptInterface(context: Activity, mWebView: WebView) :
        JavaInterface(context, mWebView) {

        @android.webkit.JavascriptInterface
        fun getIncentiveLevel(): Int = incentive_level

        @android.webkit.JavascriptInterface
        fun getVideoSrc(): String {
            return videoSrc ?: ""
        }

        @android.webkit.JavascriptInterface
        fun setVideoSrc(video: String) {
            videoSrc = video
        }

        @android.webkit.JavascriptInterface
        fun setKeyEnabled(isEnabled: Boolean) {
            isKeyEnabled = isEnabled
            runOnUiThread {
                id_activity_web_titlebar?.visibility = if (isEnabled) View.GONE else View.VISIBLE
            }
        }

        @android.webkit.JavascriptInterface
        fun hideTitleBar() {
            runOnUiThread {
                StatusBarUtil.setTranslucent(this@WebActivity, resources.getColor(R.color.transparent))
                id_activity_web_parent?.fitsSystemWindows = false
                id_activity_web_titlebar?.visibility = View.GONE
            }
        }

        @android.webkit.JavascriptInterface
        fun setPkg(pg: String) {
            pkg = pg
        }

//        onApiPost()
//        onApiGet()
//        onLoadFullVideo()
//        onShowFullVideo()






        @android.webkit.JavascriptInterface
        fun addCoin(url: String, type: Int) {
            if (isAdd) {
                return
            }
            isAdd = true
            if (sid == 0) {
                return
            }
            mWeakHandler?.postDelayed(
                { coins(url, type) },
                (if (incentive_level == 1 || incentive_level == 2 || incentive_level == 3 || incentive_level == 7 || incentive_level == 8) 0 else delay * 1000).toLong()
            )
        }




    }

    private fun startTimer() {
        if (status == OVER || status == ING || status == STOP) {
            return
        }
        RxTimerUtil.cancel()
        if (status == INIT) {
            beginTimer()
        }
    }

    private fun beginTimer() {
        status = ING
        RxTimerUtil.interval(1000) {
            mCurrentTime++
            if (TextUtils.equals(alertRenderType, "1")) {
                id_activity_web_timer_progress?.progress = mCurrentTime
            }
            if (mCurrentTime >= delay) {
                RxTimerUtil.cancel()
                status = STOP
                if (incentive_level == 1) {
                    mJavaInterFace?.addCoin(
                        mPageUrl
                            ?: return@interval, CoinEntity.EXTERNAL_SDK_AD_TYPE
                    )
                } else if (incentive_level == 2) {
                    mJavaInterFace?.addCoin(
                        mPageUrl
                            ?: return@interval, CoinEntity.EXTERNAL_SDK_AD_TYPE
                    )
                } else {
                    mJavaInterFace?.addCoin(mPageUrl ?: return@interval, 201)
                }
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (TextUtils.equals(timeTrigger, "1")) {
            if (incentive_level == 7 || incentive_level == 8 || incentive_level == 3) {
                if (status == INIT) {
                    startTimer()
                }
            }
        }

        return super.dispatchTouchEvent(ev)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        } catch (ex: java.lang.Exception) {
        }
    }

    override fun finish() {
        if (incentive_level == 2 || incentive_level == 8 || incentive_level == 9 || incentive_level == 11) {
            if (!isAdd) {
                CenterDialog.showSignOutDialog(this, this)
            } else {
                super.finish()
            }
        } else {
            super.finish()
        }
    }

    override fun onClick(v: View?) {
        super.finish()
    }

}

