package com.gh.common.util

import android.app.Activity
import android.os.Build
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.dip2px
import com.lightgame.utils.Util_System_Keyboard
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern

/**
 * 返回小浮窗管理类
 * 支持两种类型，网页活动(type_activity) 和 积分任务(type_task)
 *
 * 两种浮窗冲突，显示其中一个的时候就会把另一个判定为隐藏
 */
object FloatingBackViewManager {

    const val TYPE_ACTIVITY = "type_activity"

    private const val FLOATING_BACK_VIEW = "floating_back_view"

    private var mType = ""
    private var mActivityUrl = ""
    private var mLastPositionY = 114F.dip2px()

    /**
     * 显示返回小浮窗
     */
    fun showBackView(activity: Activity) {
        // 不支持 Android 4.1 的设备
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) return

        EasyFloat.with(activity)
            .setLayout(R.layout.layout_task_back)
            .setTag(FLOATING_BACK_VIEW)
            .setAnimator(null)
            .setGravity(Gravity.TOP.xor(Gravity.START), 0, mLastPositionY)
            .setSidePattern(SidePattern.LEFT)
            .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
            .registerCallback {
                createResult { _, _, view ->
                    val titleView = view?.findViewById<TextView>(R.id.titleTv)

                    view?.setOnClickListener {
                        // 先收起键盘
                        Util_System_Keyboard.hideSoftKeyboard(activity)

                        if (mType == TYPE_ACTIVITY) {
                            titleView?.text = "返回活动"

                            DirectUtils.directToWebView(activity, mActivityUrl, ("返回活动浮窗"))
                        }

                        disableBackView()
                    }
                }

                dragEnd { view ->
                    // 记录停止拖动的最后位置
                    view.findViewById<View>(R.id.titleTv)?.apply {
                        val outLocation = IntArray(2)
                        getLocationOnScreen(outLocation)
                        val yOffset = outLocation[1]

                        mLastPositionY = yOffset
                    }
                }
            }
            .show()
    }

    /**
     * 隐藏返回小浮窗
     */
    @JvmStatic
    fun dismissBackView() {
        EasyFloat.dismiss(FLOATING_BACK_VIEW)
    }

    fun getType(): String {
        return mType
    }

    /**
     * 启用返回小浮窗
     * @param type 类型
     * @param activityUrl 类型为活动的时候用的地址
     */
    fun enableBackView(type: String, activityUrl: String = "") {
        mType = type
        mActivityUrl = activityUrl
    }

    /**
     * 停用返回小浮窗
     */
    @JvmStatic
    fun disableBackView() {
        mType = ""
        mActivityUrl = ""
    }

}