package com.jld.vod.base

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import com.jld.vod.R
import com.jld.vod.model.bean.BaseBean
import com.jld.vod.model.bean.ContextBean
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.WinCallback
import com.jld.vod.view.widget.CustomProgressDialog
import com.jld.vod.viewmodel.MainViewModel
import com.kaopiz.kprogresshud.KProgressHUD
import com.xuexiang.xpage.base.XPageActivity
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.core.CoreSwitchBean
import org.greenrobot.eventbus.EventBus

/**
 * Create by Panda on 2019/3/14
 */
abstract class BaseActivity : XPageActivity() {

    protected lateinit var mContext: Context
    private var dialog: ProgressDialog? = null
    private var mToast: Toast? = null
    private var dialogs: KProgressHUD? = null
    private lateinit var viewModel: MainViewModel
    private val handlerBaseActivity: Handler =  Handler()


    //用户没操作了
    private val runnableBaseActivity = Runnable {
        LogUtils.logD("用户没操作了")
        //获取固定广告
        viewModel.findPositionAdvert()
    }

    //页面是否处于前台
    var isFront = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layoutId)
        mContext = this

        viewModel = ViewModelProvider.AndroidViewModelFactory(application).create(MainViewModel::class.java)

        initView()
        initData()
        initEvent()
        initAdVert()

        val activity = ContextBean.getInstance().getActivity();
        if (activity == null) { return; }
        LogUtils.logE("activity"+activity)
        val win = activity.getWindow();

        win.setCallback(object :WinCallback(win.callback){
            override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
                when (event!!.getAction()) {
                    MotionEvent.ACTION_DOWN->{
                        LogUtils.logD( "dispatchTouchEvent:ACTION_DOWN");
                        handlerBaseActivity.removeCallbacks(runnableBaseActivity);
                    }
                    MotionEvent.ACTION_MOVE->{
                       // LogUtils.logD("dispatchTouchEvent:activity窗口被触摸");
                        //handlerBaseActivity.removeCallbacks(runnableBaseActivity)
                         }
                    MotionEvent.ACTION_UP->
                        {
                            handlerBaseActivity.removeCallbacks(runnableBaseActivity)
                            handlerBaseActivity.postDelayed(runnableBaseActivity, 1800 * 1000)
                            LogUtils.logD( "dispatchTouchEvent:ACTION_UP");
                        }
                }
                return super.dispatchTouchEvent(event)
            }
        })
    }


    /**
     * 初始化广告模块
     */
    private fun initAdVert() {
        viewModel.findPositionAdvertLiveData.observe(this) {res->
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    if (res.data!!.size != 0)
                    {
                        EventBus.getDefault().post(res.data)
                    }
                    finishLoading()
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        if(hasFocus)
        {
            handlerBaseActivity.removeCallbacks(runnableBaseActivity)
            handlerBaseActivity.postDelayed(runnableBaseActivity, 1800 * 1000)
        }else{
            handlerBaseActivity.removeCallbacks(runnableBaseActivity)
        }

        //Log.e("zhaofuxin", "onWindowFocusChanged: activity焦点变化=="+hasFocus );
        super.onWindowFocusChanged(hasFocus )
    }

    open protected fun initView() {}

    open protected fun initData() {}

    open protected fun initEvent() {}

    fun showLoading() {
        if (dialog == null) {
            dialog = CustomProgressDialog(this, R.style.CustomDialog)
        }
        if (dialog != null && !dialog!!.isShowing) {
            dialog?.show()
        }
    }

    fun finishLoading() {
        Log.i("finishLoading", "关闭刷新！")
        dialog?.dismiss()
    }

    override fun onResume() {
        super.onResume()
        handlerBaseActivity.postDelayed(runnableBaseActivity, 1800 * 1000)
        isFront = true
    }

    override fun onPause() {
        handlerBaseActivity.removeCallbacks(runnableBaseActivity)
        super.onPause()
        isFront = false
    }

    protected abstract override fun getLayoutId(): Int

    @SuppressLint("ShowToast")
    fun toast(str: String) {
        if (mToast == null) {
            mToast = Toast.makeText(this, str, Toast.LENGTH_SHORT)
        } else {
            mToast?.setText(str)
        }
        mToast?.show()
    }

    inline fun <reified T> go() {
        startActivity(Intent(this, T::class.java))
    }

    inline fun <reified T> go(bundle: Bundle) {
        startActivity(Intent(this, T::class.java).putExtras(bundle))
    }

    inline fun <reified T> goForResult(req: Int) {
        startActivityForResult(Intent(this, T::class.java), req)
    }

    inline fun <reified T> goForResult(req: Int, bundle: Bundle) {
        startActivityForResult(Intent(this, T::class.java).putExtras(bundle), req)
    }

    /**
     * 初始化状态栏的样式
     */
    protected open fun initStatusBarStyle() {}
    protected open fun showDialog() {
        if (!isFront) return
        try {
            if (dialogs == null) {
                dialogs = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            } else {
                dialogs!!.setLabel(null)
            }
            dialogs!!.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected open fun dismissDialog() {
        if (dialogs != null && dialogs!!.isShowing) {
            dialogs!!.dismiss()
        }
    }
    /**
     * 打开fragment
     *
     * @param clazz          页面类
     * @param addToBackStack 是否添加到栈中
     * @return 打开的fragment对象
     */
    open fun <T : XPageFragment?> openPage(
        clazz: Class<T>?,
        addToBackStack: Boolean
    ): T {
        val page = CoreSwitchBean(clazz)
            .setAddToBackStack(addToBackStack)
        return openPage(page) as T
    }

    /**
     * 打开fragment
     *
     * @return 打开的fragment对象
     */
    open fun <T : XPageFragment?> openNewPage(clazz: Class<T>?): T {
        val page = CoreSwitchBean(clazz)
            .setNewActivity(true)
        return openPage(page) as T
    }


    /**
     * 切换fragment
     *
     * @param clazz 页面类
     * @return 打开的fragment对象
     */
    open fun <T : XPageFragment?> switchPage(clazz: Class<T>?): T {
        return changePage(clazz)
    }

}