package com.ym.library.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.http.SslError
import android.os.Build
import android.text.TextUtils
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 androidx.annotation.RequiresApi
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.bumptech.glide.Glide
import com.umeng.analytics.MobclickAgent
import com.ym.library.MyConstant
import com.ym.library.R
import com.ym.library.activity.contract.NewWebContract
import com.ym.library.activity.presenter.NewWebPresenter
import com.ym.library.net.MyBaseActivity
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusConstant.RX_MAIN_WATER_DROP_UPDATE
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_new_web.*

/**
 * Created by gaoleichao on 2019/4/22
 */
class NewWebActivity : MyBaseActivity(), NewWebContract.View, ScrollWebView.OnScrollChangeListener,
    DownloadListener,
    View.OnClickListener {

    override fun layoutID(): Int = R.layout.activity_new_web

    private var mPresenter: NewWebContract.Presenter? = null

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun before() {
        super.before()
//        StatusBarUtil.setTranslucent(this, resources.getColor(R.color.transparent))
//        getWindow().setStatusBarColor(Color.parseColor("#ffffff"));
        StatusBarUtil.setLightMode(this)
    }

    override fun init() {

        val lp = app_bar_layout.getLayoutParams() as CoordinatorLayout.LayoutParams
        lp.topMargin = getStatusBarHeight(this)
        app_bar_layout.layoutParams = lp

        mPresenter = NewWebPresenter(
            this,
            this,
            intent,
            webview
        )
        initListener()

        if (TextUtils.isEmpty(SettingPreference.getH5Data("guide"))) {
            SettingPreference.setH5Data("guide", "1")
            id_activity_new_web_guide_layout?.visibility = View.VISIBLE
            Glide.with(AppliContext.get()).asGif().load(R.drawable.slide_head)
                .into(id_activity_new_web_guide_img)
        }
    }

    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    fun getStatusBarHeight(context: Context): Int {
        return context.getResources().getDimensionPixelSize(
            context.getResources().getIdentifier("status_bar_height", "dimen", "android")
        )
    }

    override fun closePage() {
        finish()
    }

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

    override fun setTitle(title: String?) {
//        id_activity_web_title?.text = title
    }

    override fun setTitleEnabled(visibility: Int) {
        id_activity_web_titlebar?.visibility = visibility
    }

    override fun addJavascriptInterface(
        javaScriptInterface: NewWebPresenter.NewWebJavaScriptInterface,
        name: String
    ) {
        webview?.addJavascriptInterface(javaScriptInterface, name)
    }

    override fun setCloseVisibility(visibility: Int) {
        id_activity_web_close?.visibility = View.VISIBLE
    }

    override fun setTimerDesc(desc: String) {
        id_activity_web_timer_desc?.text = desc
    }

    override fun setTopDesc(desc: String) {
        id_activity_web_top_tips?.text = desc
    }

    override fun setTopDescVisibity(visibility: Int) {
        id_activity_web_top_tips?.visibility = visibility
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (id_activity_new_web_guide_layout?.visibility == View.VISIBLE) {
            id_activity_new_web_guide_layout?.visibility = View.GONE
        }
        mPresenter?.dispatchTouchEvent()
        return super.dispatchTouchEvent(ev)
    }

    override fun setTimerLayoutVisibility(visibility: Int) {
        id_activity_web_timer_layout?.visibility = visibility
    }

    private var isAdds = false

    private var isOpen = true

    private var showNewCoinsDialog: Dialog? = null
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    override fun showCoinsDialog(coins: Int, value: String) {
//        showCoins(coins)
        isAdds = true
        var text = "阅读奖励  金币+" + coins
        if (MyConstant.kkz_award_render_type == 1) {
            CenterDialog.showDialogReadCoins(this, coins, value, object : View.OnClickListener {
                override fun onClick(v: View?) {
                    isAdds = false
                    mPresenter?.nextUrl()
                }
            })
        } else {
            showNewCoinsDialog = CenterDialog.showNewCoinsDialog(this@NewWebActivity, coins)
        }
    }

    override fun setTimerMaxProgress(max: Int) {
//        id_activity_web_timer_progress?.maxProgress = max
    }

    override fun updateTimerProgress(progress: Int) {
//        id_activity_web_timer_progress?.progress = progress
    }

    override fun setBottomDesc(desc: String) {
        id_activity_web_bottom_tips?.text = desc
    }

    override fun setBottomVisibity(visibility: Int) {
        id_activity_web_bottom_progress_layout?.visibility = visibility
    }

    override fun setBottomMaxProgress(progress: Int) {
        id_activity_web_bottom_progress?.max = progress
    }

    override fun updateBottomProgress(progress: Int) {
        id_activity_web_bottom_progress?.progress = progress
    }

    override fun setBottomProgressVisibity(visibility: Int) {
        id_activity_web_bottom_progress?.visibility = View.VISIBLE
    }

    override fun setCurrentNum(award: Int,num: Int,title: String) {
        if (award > 0 && num >= award) {//奖励目标数大于0 且 已看数量大于目标数量，不展示退出挽留弹窗
            isAdds = true
        }
        if (!title.equals("")) {
            tv_newweb_title.text = "${title.split(" ")[0]}"
        } else {
            tv_newweb_title.text = "看4篇可得2钻石"
        }
        if (num == 0) {
            id_read_round_1.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_1.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_2.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_2.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_3.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_3.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_4.setBackgroundResource(R.drawable.shape_c9c9c9_r)
        } else if (num == 1) {
            id_read_round_1.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_1.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_2.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_2.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_3.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_3.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_4.setBackgroundResource(R.drawable.shape_c9c9c9_r)
        } else if (num == 2) {
            id_read_round_1.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_1.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_2.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_2.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_3.setBackgroundResource(R.drawable.shape_c9c9c9_r)
            id_read_line_3.setBackgroundColor(Color.parseColor("#c9c9c9"))
            id_read_round_4.setBackgroundResource(R.drawable.shape_c9c9c9_r)
        } else if (num == 3) {
            id_read_round_1.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_1.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_2.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_2.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_3.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_3.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_4.setBackgroundResource(R.drawable.shape_c9c9c9_r)
        } else if (num == 4) {
            id_read_round_1.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_1.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_2.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_2.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_3.setBackgroundResource(R.drawable.shape_0090ff_r)
            id_read_line_3.setBackgroundColor(Color.parseColor("#0090ff"))
            id_read_round_4.setBackgroundResource(R.drawable.shape_0090ff_r)
        }
    }

    private fun initListener() {
/*        id_activity_web_go_home?.setOnClickListener {
            webview?.loadUrl(mPresenter?.getHomeUrl())
        }*/
        webview?.setOnLongClickListener {
            val result = webview?.hitTestResult
                ?: return@setOnLongClickListener false
            if (result.type == WebView.HitTestResult.IMAGE_TYPE) {
                // 检查权限。Manifest.permission.WRITE_EXTERNAL_STORAGE
//                CenterDialog.showDialogSavePic(this, object : View.OnClickListener {
//                    override fun onClick(v: View?) {
//                        mPresenter?.savePic(result.extra)
//                    }
//                })
//                return@setOnLongClickListener true
            }
            return@setOnLongClickListener false
        }

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

        id_activity_web_close?.setOnClickListener { finish() }

        webview?.setOnScrollChangeListener(this)

        webview?.setDownloadListener(this)

        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
                }
            }
        }

        webview?.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView, urls: String, favicon: Bitmap?) {
                mPresenter?.onPageStarted(urls)
                super.onPageStarted(view, urls, favicon)
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                return mPresenter?.shouldOverrideUrlLoading(url) ?: false
            }

            override fun onPageFinished(view: WebView, urls: String) {
                super.onPageFinished(view, urls)
                mPresenter?.onPageFinished(urls)
            }

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

    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) {
        mPresenter?.onScrollChanged()
    }

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

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

    override fun finish() {
        if (isAdds == true) {
            super.finish()
        } else {
            CenterDialog.showSignOutDialog(this, this)
        }

    }

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

    override fun onDestroy() {
        super.onDestroy()

        if (showNewCoinsDialog != null) {
            showNewCoinsDialog?.dismiss()
        }
        webview?.visibility = View.GONE
    }

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

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }
}