package com.ym.modulecommon.news.presenter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.webkit.WebView
import com.ym.modulecommon.AdConstant
import com.ym.modulecommon.net.BaseObserver
import com.ym.modulecommon.net.RxSchedulers
import com.ym.modulecommon.net.ZXNewsClient
import com.ym.modulecommon.news.contract.AdNewsWebContract
import com.ym.modulecommon.news.entity.AdNewsWebEntity
import com.ym.modulecommon.utils.*
import com.ym.modulecommon.weiget.ScrollWebView

class AdNewsWebPresenter : AdNewsWebContract.Presenter {

    private var mView: AdNewsWebContract.View
    private var mActivity: Activity
    private var intent: Intent
    private var webView: WebView

    private val TAG = "AdNewsWebPresenter"

    private var oldUrl = ""
    private var currentUrl = ""
    private var newsId = 0

    private var mResult: AdNewsWebEntity? = null
    private var homeData: AdNewsWebEntity? = null

    private var mCurrentResult: AdNewsWebEntity? = null


    //是否完成阅读
    private var isComplete = false

    //是否完成当前阅读
    private var isCurrentComplete = false

    //是否正在阅读中
    private var isReading = false

    //滑动的开始时间
    private var scrollStartTime: Long = 0L

    //倒计时时间
    private var mCurrentProgress = 0

    //总时间
    private var totalTime = 0

    private var mHandler:Handler? = null

    constructor(
        mView: AdNewsWebContract.View,
        mActivity: Activity,
        intent: Intent,
        webView: ScrollWebView,
        handler: Handler
    ) {
        this.mView = mView
        this.mActivity = mActivity
        this.intent = intent
        this.webView = webView

        init(intent)
        mHandler = handler

        mHandler = object : Handler(){
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when(msg.what){
                    0-> {//无限循环
                        sendEmptyMessageDelayed(0, 1000)//一秒钟循环一次
                        LogUtils.e(TAG,"   循环 执行逻辑  " +mCurrentProgress)
                        if(isReading && !isCurrentComplete && !oldUrl.equals(currentUrl)){
                            mCurrentProgress--
                            if (mCurrentProgress < 0) {
                                mCurrentProgress = totalTime
                                stopTimer()
                                LogUtils.e(TAG,"   循环 执行逻辑   type = 2" +mCurrentProgress)
                                getNewsUpdateProgress(
                                    newsId?: 0,
                                    2,
                                    Utils.md5(currentUrl)
                                )
                                updateBottomStatus(CHILD_COMPLETE)

                            } else {
                                updateBottomStatus(CHILD_START_TIME)
                            }
                        }
                    }

                    1->{
                        isReading = false
                        startBottomTitleAnimation()
                    }

                }

            }
        }
        mHandler?.sendEmptyMessage(0)
    }

    @SuppressLint("JavascriptInterface")
    private fun init(intent: Intent) {
        oldUrl = intent.getStringExtra("news_url") ?: ""
//        oldUrl = "https://www.baidu.com/"
        newsId = intent.getIntExtra("news_id", 0)

        updateNewsStatus(newsId, 1)

        if (!TextUtils.isEmpty(oldUrl) && !TextUtils.equals(oldUrl, "null")) {
            mView.loadUrl(oldUrl)
        } else {
            mActivity?.finish()
        }

        if (!TextUtils.isEmpty(AdConstant.WebTheme.textColor)) {
            mView.setTextColor(AdConstant.WebTheme.textColor)
        }

        if (!TextUtils.isEmpty(AdConstant.WebTheme.themeColor)) {
            mView.setThemeColor(AdConstant.WebTheme.themeColor)
        }

        webView?.webChromeClient = object : AdNewsWebChromeClient() {
            override fun onProgressChanged(webView: WebView, i: Int) {
                if (i != 100) {
                    mView?.updateLoadProgress(i, true)
                } else {
                    mView?.updateLoadProgress(i, false)
                }
            }
        }

        updateBottomStatus(HOME_START)




    }

    override fun updateNewsStatus(newsId: Int, type: Int) {
        ZXNewsClient.adApi.getNewsStatus(newsId, type).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AdNewsWebEntity?>() {
                override fun onSuccess(result: AdNewsWebEntity?) {
                    if (result != null) {
                        if (result?.currentNews != null) {
                            homeData = result?.currentNews
//                            updateBottomStatus(HOME_START)
                            if (result?.status == 2) {
                                isComplete = true
                                //完成时弹窗
                                RxBus.get().post("complete_dialog", true)
                            }
//                            updateBottomStatus(HOME_START)
                        }
                        mView?.getData(result)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView?.getData(null)
                }
            })
    }

    //点击资讯获取当前状态
    /**
     * type  1判断当前资讯url是否重复   2 完成当前连接阅读
     */
    override fun getNewsUpdateProgress(newsId: Int, type: Int, url: String) {
        ZXNewsClient.adApi.getNewsUpdateProgress(newsId, type, url)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AdNewsWebEntity?>() {
                override fun onSuccess(result: AdNewsWebEntity?) {
                    if(type!=2) {
                        if (result != null) {
                            mResult = result
                            mCurrentResult = result?.currentNews
                            totalTime = mCurrentResult?.countDown ?: 60
                            mCurrentProgress = totalTime
                            Log.d("huang", "getNewsUpdateProgress totalTime=" + totalTime)
                            if(mCurrentResult?.urlStatus==0){//重复链接
                                Log.d("huang", "重复链接 ")
                                isComplete = false
                                updateBottomStatus(HOME_RESTART)
                            }else{
                                if (mCurrentResult?.status == 2) {//完成了
                                    //完成时弹窗
                                    isComplete = true
                                    updateBottomStatus(CHILD_COMPLETE)
                                    Log.d("huang", "完成了   CHILD_COMPLETE ")
                                } else if (mCurrentResult?.status == 1){//进行中
                                    isComplete = false
                                    Log.d("huang", "进行中   CHILD_START_TIME ")
                                    updateBottomStatus(CHILD_START_TIME)
                                } else {
                                    Log.d("huang", "e;se   CHILD_START ")
                                    isComplete = false
                                    updateBottomStatus(CHILD_START)
                                }
                            }

                        } else {
                            isComplete = false
                            isReading = false
                            updateBottomStatus(CHILD_START)
                        }
                    }else{
                        if (result != null) {
                            mResult = result
                            mCurrentResult = result?.currentNews
                            totalTime = mCurrentResult?.countDown ?: 60
                        }

                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView?.getData(null)
                    isComplete = false
                    isReading = false
                    updateBottomStatus(CHILD_START)
                }
            })
    }

    override fun nextUrl() {
        if (isComplete) {
            mView.loadUrl(mResult?.nextNews?.newsUrl?:"")
            reset()
        }
    }

    //重制页面状态
    private fun reset() {
        isComplete = false
        isCurrentComplete = false
        isReading = false
    }

    override fun onPageStarted(newUrl: String) {

    }

    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 onPageFinished(url: String) {
        LogUtils.e("huang","1  oldurl"+oldUrl+"    currenUrl:"+currentUrl)
        if(TextUtils.isEmpty(currentUrl)){
            oldUrl = url
        }

        currentUrl = url

        LogUtils.e("huang","2  oldurl"+oldUrl+"    currenUrl:"+currentUrl)
        if (url.isNotEmpty() && !oldUrl.equals(url)) {
            LogUtils.e("huang","3  oldurl"+oldUrl+"    currenUrl:"+currentUrl)
            isCurrentComplete = false
            isReading = true
            updateBottomStatus(CHILD_START_TIME)
            getNewsUpdateProgress(newsId, 1, Utils.md5(currentUrl))
        } else {
            isReading = false
            isCurrentComplete = false
            updateBottomStatus(HOME_START)
//            if (isComplete) {
//                updateBottomStatus(CHILD_COMPLETE)
//            } else {
//                updateBottomStatus(HOME_START)
//            }
        }
    }

    override fun onScrollChanged() {
        LogUtils.e("huang","oldurl"+oldUrl+"    currenUrl:"+currentUrl)

        if(!oldUrl.equals(currentUrl)){
            LogUtils.e("huang","开始倒计时")
            isReading = true
            mHandler?.removeMessages(1)
            mHandler?.sendEmptyMessageDelayed(1,2000)
        }
    }

    fun dispatchTouchEvent() {
        if(!oldUrl.equals(currentUrl)){
            LogUtils.e("huang","开始倒计时")
            isReading = true
            mHandler?.removeMessages(1)
            mHandler?.sendEmptyMessageDelayed(1,2000)
        }
    }


    private val HOME_START = 0//首页
    private val HOME_RESTART = 5//返回到首页
    private val CHILD_START = 1//点击进入
    private val CHILD_START_TIME = 2//点击进入后开启计时器
    private val CHILD_STOP_TIME = 3//点击进入后暂停计时器（未完成）
    private val CHILD_COMPLETE = 4//点击进入后完成任务

    //页面状态
    private var PAGE_STATUS = HOME_START

    //更新底部状态
    private fun updateBottomStatus(status: Int) {
        var title = ""
        var info = ""

        if(mCurrentResult !=null&& mCurrentResult?.completeNum==mCurrentResult?.browseNum && mCurrentResult?.browseNum!=0){
            title = "此任务已完成，奖励已发放"
            info = "继续做下一条任务吧～"
            mHandler?.removeCallbacksAndMessages(null)
            mView?.updateBottomStatus(title, info)
            isComplete = true
            RxBus.get().post("complete_dialog", true)
            return
        }
        PAGE_STATUS = status
        when (status) {
            HOME_START -> {
                title = "点击任意一篇内容进入"
                if(mCurrentResult==null){
                    info = "已完成${homeData?.completeNum}/${homeData?.browseNum}篇"
                }else{
                    info = "已完成${mCurrentResult?.completeNum}/${mCurrentResult?.browseNum}篇"
                }
                stopTimer()
                isReading = false
            }
            HOME_RESTART -> {
                title = "点击任意一篇内容进入"
                info = "已完成${mCurrentResult?.completeNum?:0}/${mCurrentResult?.browseNum?:0}篇"
                stopTimer()
                isReading = false
            }
            CHILD_START -> {
                isReading = true
                title = "请滑动屏幕，并停留${mCurrentResult?.countDown?:10}秒"
                info = "已完成${mCurrentResult?.completeNum?:0}/${mCurrentResult?.browseNum?:0}篇"
            }
            CHILD_START_TIME -> {
                isReading = true
                title = "请滑动屏幕，并停留${mCurrentProgress}秒"
                info = "已完成${mCurrentResult?.completeNum?:0}/${mCurrentResult?.browseNum?:0}篇"
            }
            CHILD_STOP_TIME -> {
                isReading = true
                title = "请滑动屏幕，并停留${mCurrentProgress}秒"
                info = "已完成${mCurrentResult?.completeNum}/${mCurrentResult?.browseNum}篇"
            }
            CHILD_COMPLETE -> {
                isComplete = true
                isReading = false
                isCurrentComplete = true
                stopTimer()
                title = "此任务已完成，奖励已发放"
                info = "继续做下一条任务吧～"
            }
        }
        mView?.updateBottomStatus(title, info)
    }

    private fun stopTimer() {

    }

    fun startBottomTitleAnimation() {
        mView?.startBottomTitleAnimation()
    }

    fun getisComplete(): Boolean {
        return isComplete
    }

    fun getSignOutDataInfo(): AdNewsWebEntity? {
        return mResult
    }



}