package com.ym.library.activity.presenter


import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.WebView
import com.ym.library.activity.JavaInterface
import com.ym.library.module.AdStatusEntity
import com.ym.library.module.CoinEntity
import com.ym.library.module.NewsEntity
import com.ym.library.net.ApiClient
import com.ym.library.net.BaseObserver
import com.ym.library.net.RxSchedulers
import com.ym.library.net.ZXADClient
import com.ym.library.utils.EventUtils
import com.ym.library.utils.MainLooper
import com.ym.library.utils.RxTimerUtil
import com.ym.library.utils.Utils
import com.ym.library.widget.ScrollWebView
import com.ym.library.activity.contract.NewWebContract
import com.ym.modulecommon.AppliContext

/**
 * Created by gaoleichao on 2019/4/22
 */
class NewWebPresenter : NewWebContract.Presenter {

    private val mView: NewWebContract.View
    private val mActivity: Activity
    private val intent: Intent
    private val mJavaInterFace: NewWebJavaScriptInterface

    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 mPageUrl: String = ""

    constructor(mView: NewWebContract.View, mActivity: Activity, intent: Intent, webview: ScrollWebView) {
        this.mView = mView
        this.mActivity = mActivity
        this.intent = intent
        mJavaInterFace = NewWebJavaScriptInterface(mActivity, webview)
        initData(intent)
    }

    private var title: String? = ""
    private var oldUrl: String = ""
    private var slot_id: String = ""
    private var sid: Int = 0
    private var session_id: String = ""

    private fun initData(intent: Intent) {
//        val uri = intent.data
        if (intent != null) {
            // 完整的url信息
            title = intent?.data?.getQueryParameter("title") ?: ""
            oldUrl = intent?.data?.getQueryParameter("url") ?: ""
            slot_id = intent?.data?.getQueryParameter("slot_id") ?: ""
            val s = intent?.data?.getQueryParameter("sid") ?: ""
            if (!TextUtils.isEmpty(s) && !TextUtils.equals(s, "null")) {
                sid = Integer.valueOf(s)
            }
            session_id = Utils.md5(oldUrl)
        }

        if (TextUtils.isEmpty(oldUrl)) {
            Utils.showToast(AppliContext.get(), "url is null")
            mView.closePage()
        } else {
            mView.loadUrl(oldUrl)
        }

        if (TextUtils.isEmpty(title) || TextUtils.equals(title, "null")) {
            mView.setTitle("")
        } else {
            mView.setTitle(title)
        }

        if (sid == 1919) {
            mView.addJavascriptInterface(mJavaInterFace, "android")
        } else {
            mView.addJavascriptInterface(mJavaInterFace, "novel")
        }
    }

    override fun savePic(path: String) {
//        mJavaInterFace?.savePic(path)
    }

    override fun onScrollChanged() {
        if (!isKeyDown() && (alertRenderType == 1 || alertRenderType == 2 || alertRenderType == 3) && STATUS == INIT) {
            //开启计时器
            startTimer(mPageUrl)
        }
    }

    override fun onDownloadStart(url: String?) {
        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) {
        }
    }

    override fun onPageStarted(newUrl: String) {
        if (!TextUtils.equals(newUrl, oldUrl)) {
            mView.setCloseVisibility(View.VISIBLE)
        } else {
            mView.setCloseVisibility(View.GONE)
        }
        if ((alertRenderType == 1 || alertRenderType == 2 || alertRenderType == 3) && STATUS == ING && redirect_reset == 1) {
            stopTimer()
        } else {
            RxTimerUtil.cancel()
            STATUS = OVER
        }
    }

    override fun onPageFinished(url: String) {
        mPageUrl = url
        getAdStatus(mPageUrl/*, Base64.encodeToString(url.toByteArray(), Base64.URL_SAFE)*/)
    }


    override fun shouldOverrideUrlLoading(url: String): Boolean {
        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 (Utils.isInstall(intent)) {
                    mActivity.startActivity(intent)
                    return true
                }
            }
        } catch (e: Exception) {
            return false
        }
        return false
    }

    override fun dispatchTouchEvent() {
        if (isKeyDown() && (alertRenderType == 1 || alertRenderType == 2 || alertRenderType == 3) && STATUS == INIT) {
            //开启计时器
            EventUtils.onEvent("kkz_page_slide")

            startTimer(mPageUrl)
        }
    }


    private var redirect_reset: Int = 0
    private var time_trigger: Int = 0
    private var delay = 0
    private var alertRenderType = 0
    private var adSign: String = ""
    private var status: Int = 0
    private var progressStatus: Int = 0

    private fun getAdStatus(sUrl: String/*, url: String*/) {
        Log.d("glc", "sUrl" + sUrl)
        ApiClient.adApi.getAdStatus(slot_id, sid, sUrl, Utils.md5(sUrl)).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AdStatusEntity>() {
                override fun onSuccess(result: AdStatusEntity?) {
                    if (result != null) {
                        status = result.status ?: 0
                        delay = result.delay ?: 0
                        adSign = result.adSign ?: ""
                        progressStatus = result.progressStatus ?: 0
                        if (result.alertRenderType == 1) {
                            setTimerViewMode(result.alert ?: "")
                        } else if (result.alertRenderType == 2) {
                            setTopViewMode(result.alert ?: "")
                        } else if (result.alertRenderType == 3) {
//                        setBottomViewMode(result.alert ?: "")
                            if (delay > 0 && status == 1 && progressStatus == 0) {
//                            mView.setBottomMaxProgress(delay)
//                            mView.setBottomProgressVisibity(View.VISIBLE)
                                STATUS = INIT
                            }
                            mView.setCurrentNum(result?.award_limit?:0,result.current_nums ?: 0,result?.alert?:"")
                        }
                        if (result.delay == 0) {
                            //加金币
                            addCoins(sUrl)
                        }
                        alertRenderType = result.alertRenderType ?: 0
                        redirect_reset = result.redirect_reset ?: 0//1是 0否

                        time_trigger = result.time_trigger ?: 0//1按下 其他滑动 2代表直接计时

                    }
                }

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

    private fun setTopViewMode(alert: String) {
        mView.setTimerLayoutVisibility(View.GONE)
        mView.setBottomVisibity(View.GONE)
        STATUS = INIT
        mView.setTimerDesc("")
        mView.setTopDescVisibity(View.VISIBLE)
        mView.setTopDesc(alert)
    }

    private fun setBottomViewMode(alert: String) {
        mView.setTimerLayoutVisibility(View.GONE)
        mView.setTopDescVisibity(View.GONE)
        mView.setBottomVisibity(View.VISIBLE)
        mView.setBottomDesc(alert)
        if (delay > 0 && status == 1 && progressStatus == 0) {
            mView.setBottomMaxProgress(delay)
            mView.setBottomProgressVisibity(View.VISIBLE)
            STATUS = INIT
        } else {
            mView.setBottomProgressVisibity(View.GONE)
        }
    }

    private fun setTimerViewMode(alert: String) {
        mView.setTimerDesc(alert)
        mView.setTopDesc("")
        mView.setBottomVisibity(View.GONE)
        mView.setTopDescVisibity(View.GONE)
        if (delay > 0 && status == 1) {
            //计时器初始化
            mView.setTimerMaxProgress(delay)
            mView.setTimerLayoutVisibility(View.VISIBLE)
            STATUS = INIT
        } else {
            mView.setTimerLayoutVisibility(View.GONE)
        }
    }

    private fun updateProgress() {
        if (alertRenderType == 1) {
            mView.updateTimerProgress(mCurrentProgress)
        } else if (alertRenderType == 3) {
            mView.updateBottomProgress(mCurrentProgress)
        }
    }

    private var mCurrentProgress: Int = 0

    private fun startTimer(url: String) {
        Log.d("NewWebPresenter", "startTimer")
        STATUS = START
        RxTimerUtil.interval(1000) {
            if (STATUS == START) {
                STATUS = ING
            }
            mCurrentProgress++
            updateProgress()
            Log.d("NewWebPresenter", "progress:" + mCurrentProgress)
            if (mCurrentProgress >= delay) {
                if (STATUS == ING) {
                    stopTimer()
                    addCoins(url)
                }
            }
        }
    }

    private fun stopTimer() {
        RxTimerUtil.cancel()
        STATUS = OVER
        mCurrentProgress = 0
        updateProgress()
    }

    private fun isKeyDown(): Boolean {
        return time_trigger == 1
    }

    private fun isResetTimer(): Boolean {
        return redirect_reset == 1
    }

    private fun addCoins(url: String) {
        ApiClient.userApi.readAddCoins(
            Utils.md5(url),
            201,
            sid.toString(),
            slot_id,
            adSign
        ).compose(RxSchedulers.observableIO2Main()).subscribe(object : BaseObserver<CoinEntity>() {
            override fun onSuccess(result: CoinEntity?) {
                println("onFailure$url")
                if (result != null && result.coins > 0) {
                    mView.showCoinsDialog(result.coins, result.leftAward ?: "")
                }

                getAdStatus(url)
            }

            override fun onFailure(e: Throwable, code: String, errorMsg: String) {
                println("onFailure$errorMsg")
                if (TextUtils.equals("105", code)) {
                    Utils.showToast(AppliContext.get(), errorMsg)
                }
            }
        })
    }

    private var keyEnabled: Boolean? = true

    private var videoSrc: String = ""

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

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

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

        @android.webkit.JavascriptInterface
        fun setKeyEnabled(isEnabled: Boolean) {
            keyEnabled = isEnabled
            MainLooper.get()?.post(Runnable {
                mView.setTitleEnabled(if (isEnabled) View.GONE else View.VISIBLE)
            })
        }

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

        @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())
//        }
        }
    }

    override fun getHomeUrl(): String {
        return oldUrl
    }

    override fun nextUrl() {
        ZXADClient.adApi.getAd("kkz").compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>?) {
                    var data: NewsEntity? = null
                    result?.forEach {
                        if (it.status == 0) {
                            data = it
                            return@forEach
                        }
                    }
                    if (data != null) {
                        oldUrl = data?.url ?: ""
                        slot_id = data?.slot_id ?: ""
                        title = data?.title ?: ""
                        sid = data?.sid ?: 0
                        session_id = Utils.md5(oldUrl)
                        mView.loadUrl(oldUrl)
                        onPageFinished(oldUrl)
                    } else {
                        Utils.showToast(AppliContext.get(), "您已经完成全部任务了")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    Utils.showToast(AppliContext.get(), errorMsg)
                    Utils.getStatusBarHeight()
                }
            })
    }
}