package com.develop.common.ui

import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.os.IBinder
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.viewbinding.ViewBinding
import com.develop.base.ext.navigateTo
import com.develop.base.mvvm.BaseBindingActivity
import com.develop.base.util.MMkvUtils
import com.develop.common.R
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.common.dialog.PlainDialogView
import com.develop.common.food_sdk.FoodSdkUtils
import com.develop.common.food_sdk.GlobalDevEvent
import com.develop.common.router.Screens
import com.develop.common.tag.SCREENSAVER
import com.develop.common.utils.TimeDownUtil
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.DevPromptEvent
import me.jessyan.autosize.AutoSizeCompat
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import com.develop.base.util.TopResumedAtyHolder

/**
 * 带业务逻辑的基类
 */
abstract class CommonBindingActivity<T : ViewBinding> : BaseBindingActivity<T>() {

    protected var hasShowScreenSaver = false

    private val plainDialogView by lazy {
        PlainDialogView(
            this, R.layout.dialog_easy_view
        )
    }

    private var isResume = false

    private val screenSaverDialog by lazy {
        CancelConfirmDialog()
    }

    private var timeDownUtil: TimeDownUtil? = null
    private var screenSaverTime = 3 //minute

    override fun onCreate(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        super.onCreate(savedInstanceState)
        val time = MMkvUtils.getInt(SCREENSAVER)
        if (time != 0) {
            screenSaverTime = time
        }
        screenSaverDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    navigateTo(Screens.Setting.SCREEN_SAVER)
                }

                override fun onCancel() {
                    if (!hasShowScreenSaver) startScreenSaverCount()
                }
            }
    }

    override fun onResume() {
        super.onResume()
        isResume = true
        if (!hasShowScreenSaver) {
            startScreenSaverCount()
        } else {
            stopScreenSaverCount()
        }
    }

    override fun onPause() {
        super.onPause()
        isResume = false
        stopScreenSaverCount()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.x == 0f && ev.y == 0f) {
            return true
        }
        when (ev.action) {
            MotionEvent.ACTION_UP -> if (!hasShowScreenSaver) startScreenSaverCount()
            else -> stopScreenSaverCount()
        }
        if (ev.action == MotionEvent.ACTION_DOWN) {
            //全局点击外面关闭软键盘
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v?.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun showPlainDialog(cancelable: Boolean = false) {
        plainDialogView.showDialog(cancelable)
    }

    fun dismissPlainDialog() {
        plainDialogView.hideDialog()
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val manager: InputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
     * 因为当用户点击EditText时没必要隐藏
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = (left + v.width)
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    private fun startScreenSaverCount() {
        if (FoodSdkUtils.isDevRunning()) {
            return
        }
        stopScreenSaverCount()
        val totalTime = screenSaverTime * 60 * 1000L
        timeDownUtil = object : TimeDownUtil(totalTime, 1000) {
            override fun onTick(millisUntilFinished: Long) {

                if (FoodSdkUtils.isDevRunning()) {
                    return
                }

                if (millisUntilFinished == 30 * 1000L) {
                    runOnUiThread {
                        showScreenSaverDialog()
                    }
                }
            }

            override fun onFinish() {

                if (FoodSdkUtils.isDevRunning()) {
                    return
                }

                runOnUiThread {
                    screenSaverDialog.removeSelf()
                    navigateTo(Screens.Setting.SCREEN_SAVER)
                }
            }
        }
        timeDownUtil?.start()
    }

    private fun stopScreenSaverCount() {
        timeDownUtil?.cancel()
        timeDownUtil = null
    }

    private fun showScreenSaverDialog() {
        screenSaverDialog.title = getString(R.string.screen_saver_title)
        screenSaverDialog.showDialog(supportFragmentManager, "cancelConfirmDialog")
    }

//    @Subscribe
//    fun onCookDevMsgEvent(event: DevPromptEvent) {
//        if (isResume) {
//            GlobalDevEvent.globalDevMsgEvent(event, supportFragmentManager, resources)
//        }
//    }

    var lastMsg = ""

    private val cancelConfirmDialog = CancelConfirmDialog()


    @Subscribe
    fun onCookDevMsgEvent(event: DevPromptEvent) {
        if (!this.equals(TopResumedAtyHolder.getCurrentActivity())) {
            return
        }

        //            //已显示弹窗不重复显示
//            if(FloatWindowManager.confirmCancelDialog.isAdded){
//                return
//            }
        if (lastMsg == event.msg) {
            return
        }
        lastMsg = event.msg
        var confirmCancelDialog = CancelConfirmDialog()
        confirmCancelDialog.showCancel = event.isShowCancelBtn
        confirmCancelDialog.showConfirm = event.isShowConfirmBtn

        confirmCancelDialog.cancelStr = resources.getString(
            resources.getIdentifier(
                event.cancelBtnText, "string", this.packageName
            )
        )
        confirmCancelDialog.confirmStr = resources.getString(
            resources.getIdentifier(
                event.confirmButtonText, "string", this.packageName
            )
        )
        confirmCancelDialog.title =
            resources.getString(resources.getIdentifier(event.msg, "string", this.packageName))

        confirmCancelDialog.showDialog(supportFragmentManager, "confirmCancelDialog")

        confirmCancelDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    if (event.confirm != null) {
                        event.confirm.callback();
                    }
                    cancelConfirmDialog.removeSelf();
                    lastMsg = "";
                }

                override fun onCancel() {
                    if (event.cancel != null) {
                        event.cancel.callback();
                    }
                    cancelConfirmDialog.removeSelf();
                    lastMsg = "";
                }

            }

    }

    override fun getResources(): Resources {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources())
        }
        return super.getResources()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        GlobalDevEvent.dismissDialog()
        dismissPlainDialog()
    }
}