package com.ym.modulecommon.news.presenter

import android.app.Activity
import android.content.Intent
import android.icu.number.CurrencyPrecision
import android.net.Uri
import android.nfc.Tag
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import com.ym.modulecommon.net.BaseObserver
import com.ym.modulecommon.net.RxSchedulers
import com.ym.modulecommon.net.ZXNewsClient
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.utils.LogUtils
import com.ym.modulecommon.utils.RxBus
import com.ym.modulecommon.utils.Utils


/**
 * 新闻赚
 *
 * 1,开启循环，监听
 * 2,isScrooll 是否在滑动
 * 3,homeUrl   currentUrl  判断是否在首页
 * 4,complication  此篇文章是否看完
 * 5,
 */
class AdNewsPresenter : AdNewsContract.Presenter {

    private var adNewsInfomationEntity: AdNewsInfomationEntity? = null
    private var mView: AdNewsContract.View
    private var mActivity: Activity
    private var intent: Intent
    private val TAG = "huang"
    private var mCurrentProgress = 10
    private var isScrooll = false
    private var homeUrl = ""
    private var currentUrl = ""
    private var complication = false
    private var isTaskComplication = false
    private var mCurrentResult: AdNewsWebEntity? = null
    private var totalTime:Int = 60
    private var mHandler:Handler? = null
    constructor(
        mView: AdNewsContract.View,
        mActivity: Activity,
        adNewsInfomationEntity: AdNewsInfomationEntity,
        intent: Intent,
        handler: Handler
    ) {
        this.mView = mView
        this.mActivity = mActivity
        this.intent = intent
        this.adNewsInfomationEntity = adNewsInfomationEntity
        mHandler = handler

        LogUtils.e(TAG,"homeUrl:"+homeUrl)

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

                            } else {
                                updateBottomStatus(CHILD_START_TIME)
                            }
                        }
                    }

                    1->{
                        isScrooll = false
                        startBottomTitleAnimation()
                    }

                }

            }
        }
        mHandler?.sendEmptyMessage(0)
    }
    //点击资讯获取当前状态
    /**
     * type  1判断当前资讯url是否重复   2 完成当前连接阅读
     */
    override fun getNewsUpdateProgress(newsId: Int, type: Int, url: String) {
        ZXNewsClient.adApi.getNewsUpdateProgress(newsId, type, url,1)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AdNewsWebEntity?>() {
                override fun onSuccess(result: AdNewsWebEntity?) {
                    if(type!=2){
                        if (result != null) {
                            mCurrentResult = result?.currentNews
                            totalTime = mCurrentResult?.countDown ?: 60
                            mCurrentProgress = totalTime
                            setHomeInfo()
                        }else{
                            updateBottomStatus(CHILD_COMPLETE)
                        }
                    }else{
                        if (result != null) {
                            mCurrentResult = result?.currentNews
                            totalTime = mCurrentResult?.countDown ?: 60
                            mCurrentProgress = totalTime
                        }
                    }
                }

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

    /**
     * 设置信息
     */
    private fun setHomeInfo() {
        if(mCurrentResult?.urlStatus==0){//重复链接
            updateBottomStatus(CHILD_COMPLETE)
        }else{
            if (mCurrentResult?.status == 2) {//完成了
                //完成时弹窗
                updateBottomStatus(CHILD_COMPLETE)
            } else if (mCurrentResult?.status == 1){//进行中
                updateBottomStatus(CHILD_START_TIME)
            } else {
                updateBottomStatus(CHILD_START_TIME)
            }
        }
    }


    /**
     * 开始的时候
     */
    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(newUrl: String) {
        LogUtils.e(TAG,"newUrl:"+newUrl +"   homeUrl:"+homeUrl)
        mCurrentProgress = totalTime
        currentUrl = newUrl

        if(TextUtils.isEmpty(homeUrl)){
             homeUrl = newUrl
        }
        if(homeUrl.equals(currentUrl)){
            LogUtils.e(TAG,"newUrl:== homeUrl:")
            complication = true
            isScrooll = false
            if(mCurrentResult!=null){
                updateBottomStatus(HOME_START)
            }
        }else{
            LogUtils.e(TAG,"newUrl: != homeUrl:")
            complication = false
            isScrooll = true
            updateBottomStatus(CHILD_START_TIME)
            LogUtils.e(TAG,"   循环 执行逻辑   type = 1  " +newUrl)
            getNewsUpdateProgress(adNewsInfomationEntity?.id?:0,1,newUrl)
        }
    }

    override fun onScrollChanged() {
        if(!currentUrl.equals(homeUrl)){
            isScrooll = true
            mHandler?.removeMessages(1)
            mHandler?.sendEmptyMessageDelayed(1,2000)
        }

    }

    fun dispatchTouchEvent() {
        if(!currentUrl.equals(homeUrl)){
            isScrooll = true
            mHandler?.removeMessages(1)
            mHandler?.sendEmptyMessageDelayed(1,2000)
        }
    }

    private val HOME_START = 0//首页
    private val CHILD_START_TIME = 2//点击进入后开启计时器
    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)
            isTaskComplication = true
            return
        }
        PAGE_STATUS = status
        when (status) {
            HOME_START -> {
                title = "点击任意一篇内容进入"
                info = "已完成${mCurrentResult?.completeNum}/${mCurrentResult?.browseNum}篇"
            }
            CHILD_START_TIME -> {
                title = "请滑动屏幕，并停留${mCurrentProgress}秒"
                info = "已完成${mCurrentResult?.completeNum?:0}/${mCurrentResult?.browseNum?:0}篇"
            }
            CHILD_COMPLETE -> {
                title = "此任务已完成，奖励已发放"
                info = "继续做下一条任务吧～"
            }
        }
        mView?.updateBottomStatus(title, info)
    }

    private fun stopTimer() {
        complication = true
        isScrooll = false
    }

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


}