package com.ym.modulecommon.news

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.http.SslError
import android.os.Build
import android.os.Handler
import android.text.TextUtils
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.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.ym.admodule.R
import com.ym.admodule.news.NewsListener
import com.ym.modulecommon.AdConstant
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.base.BaseActivity
import com.ym.modulecommon.news.contract.AdNewsContract
import com.ym.modulecommon.news.entity.AdNewsInfomationEntity
import com.ym.modulecommon.news.entity.AdNewsWebEntity
import com.ym.modulecommon.news.presenter.AdNewsPresenter
import com.ym.modulecommon.utils.*
import com.ym.modulecommon.weiget.ScrollWebView
import kotlinx.android.synthetic.main.activity_ad_news.*
import java.lang.Exception

/**
 * 加载新闻 (同激励视频)
 *
 *  //    app/v1/mon/news/getNews
 */
class AdNewsActivity : BaseActivity(), DownloadListener, AdNewsContract.View,
    ScrollWebView.OnScrollChangeListener {

    private var mPresenter: AdNewsPresenter? = null
    private val TAG = "AdNewsActivity"
    override fun layoutID(): Int {
        return R.layout.activity_ad_news
    }
    companion object{
        private var listener: NewsListener? = null

        fun create(
            activity: Activity,
            adNewsInfomationEntity:AdNewsInfomationEntity,
            listener: NewsListener
        ) {
            this.listener = listener
            var intent = Intent(activity, AdNewsActivity::class.java)
            intent.putExtra("adNewsInfomationEntity",adNewsInfomationEntity)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            activity.startActivity(intent)
        }
    }

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

    override fun init() {
        try {
            val serializableExtra = intent.getSerializableExtra("adNewsInfomationEntity") as AdNewsInfomationEntity
            mPresenter = AdNewsPresenter(this, this,serializableExtra,intent,Handler())
            setInfoMation(serializableExtra)
        }catch (e:Exception){

        }
        initListener()
    }

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

        id_ad_news_back?.setOnClickListener {
            if (news_webview?.canGoBack() == true) {
                news_webview?.goBack()
            }else{
                if(id_ad_news_close.visibility == View.VISIBLE){
                    listener?.onAdClose()
                    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) {

        }
    }

    /**
     * 设置url
     */
    fun setInfoMation(result: AdNewsInfomationEntity?) {
        if(result==null){
            id_ad_news_time?.visibility  = View.GONE
            id_ad_news_close.visibility = View.VISIBLE
        }else{
            if (!TextUtils.isEmpty(result.newsUrl) && !TextUtils.equals(result.newsUrl, "null")) {
                loadUrl(result.newsUrl?:"")
            } else {
                id_ad_news_time?.visibility  = View.GONE
                id_ad_news_close.visibility = View.VISIBLE
            }

            if (!TextUtils.isEmpty(AdConstant.WebTheme.textColor)) {
                setTextColor(AdConstant.WebTheme.textColor)
            }
            if (!TextUtils.isEmpty(AdConstant.WebTheme.themeColor)) {
                setThemeColor(AdConstant.WebTheme.themeColor)
            }
            news_webview?.webChromeClient = object : AdNewsWebChromeClient() {
                override fun onProgressChanged(webView: WebView, i: Int) {
                    if (i != 100) {
                        updateLoadProgress(i, true)
                    } else {
                        updateLoadProgress(i, false)
                    }
                }
            }
            id_ad_news_tile.text = result.title
            id_ad_news_bootom_tile.text = "点击任意一篇内容进入"
            id_ad_news_bootom_progress.text = "已完成"+result.completeNum+"/"+result.browseNum+"篇"
            setTimes(id_ad_news_time,id_ad_news_close,((result?.countDown?:30)*1000L))
            listener?.onAdShow()
        }

    }

    override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
        Log.d(TAG, "onPageTop: 偏移：" + (t - oldt))
    }
    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) {
        Log.d(TAG, "onPageEnd: 偏移：" + (t - oldt))

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

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

    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        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 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()
    }

    override fun onBackPressed() {
        if(id_ad_news_close.visibility == View.VISIBLE){
            listener?.onAdClose()
            finish()
        }
    }

    fun setTimes(tv: TextView, iv: ImageView,millisinfuture:Long){
        tv.visibility = View.VISIBLE
        iv.visibility = View.INVISIBLE
        tv.text = "3"
        LJButtonCountTimer(AppliContext.get(), millisinfuture, 1000, tv,iv).start()
    }
}