package com.ym.modulecommon.news

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.graphics.Bitmap
import android.graphics.Color
import android.net.http.SslError
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.webkit.DownloadListener
import android.webkit.SslErrorHandler
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import com.ym.admodule.R
import com.ym.modulecommon.base.BaseActivity
import com.ym.modulecommon.news.contract.AdNewsWebContract
import com.ym.modulecommon.news.entity.AdNewsWebEntity
import com.ym.modulecommon.news.presenter.AdNewsWebPresenter
import com.ym.modulecommon.utils.*
import com.ym.modulecommon.weiget.ScrollWebView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_ad_news_web.*
import kotlinx.android.synthetic.main.activity_ad_news_web.id_activity_web_progress
import kotlinx.android.synthetic.main.activity_ad_news_web.id_ad_news_back
import kotlinx.android.synthetic.main.activity_ad_news_web.id_ad_news_bootom_progress
import kotlinx.android.synthetic.main.activity_ad_news_web.id_ad_news_bootom_tile
import kotlinx.android.synthetic.main.activity_ad_news_web.id_ad_news_close
import kotlinx.android.synthetic.main.activity_ad_news_web.id_ad_news_tile
import kotlinx.android.synthetic.main.activity_ad_news_web.id_layout_ad_news_bottom
import kotlinx.android.synthetic.main.activity_ad_news_web.id_layout_ad_news_title

class AdNewsWebActivity : BaseActivity(), DownloadListener, AdNewsWebContract.View,
    ScrollWebView.OnScrollChangeListener, View.OnClickListener {

    private var mPresenter: AdNewsWebPresenter? = null

    private val TAG = "AdNewsWebActivity"
    private val COMPLETE_DIALOG = "complete_dialog"

    private var mCompleteDialogObservable: Observable<Boolean>? = null

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

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun before() {
        super.before()
        StatusBarUtil.setLightMode(this)
    }

    override fun init() {
        val lp = id_layout_ad_news_toolbar.getLayoutParams() as RelativeLayout.LayoutParams
        lp.height = Utils.getStatusBarHeight()
        id_layout_ad_news_toolbar.layoutParams = lp

        mCompleteDialogObservable = RxBus.get().register(COMPLETE_DIALOG, Boolean::class.java)
        mCompleteDialogObservable?.observeOn(AndroidSchedulers.mainThread())?.subscribe({
            showSignOutDialog()
        }, { })

        mPresenter = AdNewsWebPresenter(this, this, intent, news_webview,Handler())
        initListener()

    }

    private fun initListener() {
        id_ad_news_close?.setOnClickListener { finish() }

        id_ad_news_back?.setOnClickListener {
            if (news_webview?.canGoBack() == true) {
                news_webview?.goBack()
            } else {
                finish()
            }
        }

        news_webview?.setDownloadListener(this)
        news_webview?.setOnScrollChangeListener(this)

        news_webview?.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView, urls: String, favicon: Bitmap?) {
                Log.d(TAG, "onPageStarted: urls=" + urls)
                mPresenter?.onPageStarted(urls)
                super.onPageStarted(view, urls, favicon)
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                Log.d(TAG, "shouldOverrideUrlLoading: url=" + url)
                return mPresenter?.shouldOverrideUrlLoading(url) ?: false
            }

            @RequiresApi(Build.VERSION_CODES.M)
            override fun onPageFinished(view: WebView, urls: String) {
                super.onPageFinished(view, urls)
                Log.d(TAG, "onPageFinished: url=" + urls)
                mPresenter?.onPageFinished(urls)
            }

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

    override fun loadUrl(url: String) {
        news_webview?.loadUrl(url)
    }

    override fun setTextColor(color: String) {
        id_ad_news_tile?.setTextColor(Color.parseColor(color))
        id_ad_news_bootom_tile?.setTextColor(Color.parseColor(color))
        id_ad_news_bootom_progress?.setTextColor(Color.parseColor(color))
    }

    override fun setThemeColor(color: String) {
        id_layout_ad_news_title?.setBackgroundColor(Color.parseColor(color))
        id_layout_ad_news_bottom?.setBackgroundColor(Color.parseColor(color))
    }

    override fun updateLoadProgress(progress: Int?, isShow: Boolean) {
        if (isShow) {
            id_activity_web_progress.progress = progress ?: 0
        } else {
            id_activity_web_progress.visibility = View.GONE
        }
    }

    override fun updateBottomStatus(title: String, progressText: String) {
        id_ad_news_bootom_tile?.text = title
        id_ad_news_bootom_progress?.text = progressText
    }

    override fun startBottomTitleAnimation() {
        startAnimator()
    }

    override fun getData(result: AdNewsWebEntity?) {
        if (result != null) {

        }
    }

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

    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        Log.d(TAG, "onScrollChanged: 偏移：" + (t - oldt))
        mPresenter?.onScrollChanged()
        clearAnimation()


    }

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

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        Log.d(TAG, "dispatchTouchEvent: ")
        mPresenter?.dispatchTouchEvent()
        clearAnimation()
        return super.dispatchTouchEvent(ev)
    }

    override fun onDownloadStart(
        url: String?,
        userAgent: String?,
        contentDisposition: String?,
        mimetype: String?,
        contentLength: Long
    ) {

    }

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

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

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        println("id_webview?.canGoBack():" + news_webview?.canGoBack())
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (news_webview?.canGoBack() == true) {
                news_webview?.goBack()
                return true
            } else {
                return super.onKeyDown(keyCode, event)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private var signOutDataInfo: AdNewsWebEntity? = null

    //未完成任务退出提示弹窗
    override fun finish() {
        showSignOutDialog()
    }

    private fun showSignOutDialog() {
        signOutDataInfo = mPresenter?.getSignOutDataInfo()
        AdWebDialog.showSignOutDialog(
            this,
            mPresenter?.getisComplete() ?: false,
            signOutDataInfo?.needNum ?: 0,
            this, this
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        news_webview?.visibility = View.GONE
        RxBus.get().unregister(COMPLETE_DIALOG, mCompleteDialogObservable!!)//页面销毁的时候要执行 反注册
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.dialog_scratch_dialog_bg -> {
                if (signOutDataInfo != null) {
                    if (signOutDataInfo?.haveNext == 1) {
                        mPresenter?.nextUrl()
                    } else {
                        if (mPresenter?.getisComplete()!!) {
                            super.finish()
                        }
                    }
                }
            }
            R.id.dialog_scratch_dialog_cancel -> {
                super.finish()
            }
        }
    }

    private var mObjectAnimator: ObjectAnimator? = null
    private fun startAnimator() {
        mObjectAnimator = ObjectAnimator.ofFloat(
            id_ad_news_bootom_tile,
            View.ROTATION,
            0F, 5F, -5F, 0F, 0F, 0F, 0F, 0F, 0F
        )
        mObjectAnimator?.repeatCount = ValueAnimator.INFINITE
        mObjectAnimator?.setDuration(2000)?.start()
    }

    private fun clearAnimation() {
        val objectAnimator = ObjectAnimator.ofFloat(
            id_ad_news_bootom_tile,
            View.ROTATION,
            0F, 0F)
        objectAnimator?.repeatCount = ValueAnimator.INFINITE
        objectAnimator?.setDuration(2000)?.start()

        mObjectAnimator?.cancel()
        id_ad_news_bootom_tile?.clearAnimation()
    }
}