package com.mints.goodmoney.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.webkit.WebChromeClient
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.github.lzyzsd.jsbridge.DefaultHandler
import com.mints.goodmoney.BuildConfig
import com.mints.goodmoney.R
import com.mints.goodmoney.common.AppConfig
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.TurntableBean
import com.mints.goodmoney.mvp.presenters.PanPresenter
import com.mints.goodmoney.mvp.views.PanView
import com.mints.goodmoney.ui.activitys.AwardActivity
import com.mints.goodmoney.ui.fragment.base.BaseFragment
import com.mints.library.net.netstatus.NetUtils
import com.mints.library.utils.json.JsonUtil
import kotlinx.android.synthetic.main.fragment_main_pan.*


/**
 * 描述：大转盘
 * 作者：孟崔广
 * 时间：2020/9/20 17:30
 */
class PanFragment : BaseFragment(), PanView {

    private val panPresenter by lazy { PanPresenter() }
    private val userManager by lazy { UserManager.getInstance() }
    private var isLoadPanSuc = false // 是否加载大转盘成功
    private val carrierType = Constant.CARRIER_CHALLENGE_TURN

    override fun getContentViewLayoutID() = R.layout.fragment_main_pan

    override fun initViewsAndEvents() {
        panPresenter.attachView(this)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) { // 不在最前端界面显示
            onPause()
        } else { // 重新显示到最前端中
            onResume()
        }
        super.onHiddenChanged(hidden)
    }

    override fun onResume() {
        super.onResume()
        if (AppConfig.fragmentClickFlag === Constant.FRAGMENT_CLICK_PAN) {
            if (TextUtils.isEmpty(userManager?.userID)) {
                // 游客登录
                panPresenter.userLogin()
            } else {
                if (!isLoadPanSuc && NetUtils.isNetworkConnected(getContext())) {
                    loadTurnUrl()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        panPresenter.detachView()
    }

    override fun loginSuc() {
        if (!isLoadPanSuc && NetUtils.isNetworkConnected(getContext())) {
            loadTurnUrl()
        }
    }

    /**
     * 加载转盘url
     */
    private fun loadTurnUrl() {
        getTurnUrl()
        blTurntableWebview.setOnTouchListener(object : View.OnTouchListener {
           override fun onTouch(v: View?, event: MotionEvent): Boolean {
                return event.action == MotionEvent.ACTION_MOVE
            }
        })
        blTurntableWebview.setDefaultHandler(DefaultHandler())
        blTurntableWebview.webChromeClient = WebChromeClient()
        blTurntableWebview.setOnLongClickListener { true }
        //注册监听方法当js中调用callHandler方法时会调用此方法（handlerName必须和js中相同）
        blTurntableWebview.registerHandler("getTurnResult") { data, function ->
            val turntableBean: TurntableBean = JsonUtil.parseJson(data, TurntableBean::class.java)
            if (turntableBean != null) {
                val bundle = Bundle()
                bundle.putInt(Constant.MAIN_CUR_COIN, turntableBean.coin)
                bundle.putString(Constant.MAIN_CARRIER_TYPE, carrierType)
                bundle.putString(Constant.MAIN_EXTRA_ID, turntableBean.key)
                readyGo(AwardActivity::class.java, bundle)

                androidCallJsReferse()
            }
        }
        blTurntableWebview.setDefaultHandler(object : DefaultHandler() {
            override fun handler(data: String, function: CallBackFunction) {
                showToast(data)
            }
        })
    }

    /**
     * 获取转盘url
     */
    private fun getTurnUrl() {
        val tokenID = userManager.tokenID
        val url: String = BuildConfig.MainIp + "turn/turn.html?carrierType=" + carrierType + "&token=" + tokenID
        blTurntableWebview.loadUrl(url)

        isLoadPanSuc = true
    }

    /**
     * 奖励成功刷新js界面
     */
    private fun androidCallJsReferse() {
        // 调用js中的方法（必须和js中的handlerName想同）
        blTurntableWebview.callHandler("refreshTurnTable", "") {
        }
    }

    /**
     * 用户主动取消js调用
     */
    private fun androidCallJsCancel() {
        // 调用js中的方法（必须和js中的handlerName想同）
        blTurntableWebview.callHandler("cancelTurnTable", "") {}
    }


}