package com.qimai.log.ui

import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Build
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.*
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern
import com.qimai.log.R
import com.qimai.log.click

/**
 * Created by chuxiaoshan on 2021/5/27 14:10
 *
 * Description: 浮框
 */

object LogUpFloatView {

    //标识浮框的tag
    private const val FLOAT_VIEW_TAG = "tag_float_view"

    /**
     * 浮框权限判断与申请
     */
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtils.isGrantedDrawOverlays()) {
                PermissionUtils.requestDrawOverlays(object :
                    PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        LogUtils.d("---1111--->onGranted")
                        initFloat()
                    }

                    override fun onDenied() {
                        LogUtils.d("---1111--->onDenied")
                        ToastUtils.showShort("浮框权限未打开")
                    }
                })
            } else {
                initFloat()
                LogUtils.d("---1111--->浮框权限本来就是打开的")
            }
        } else {
            LogUtils.d("---1111--->低版本")
            initFloat()
        }
    }

    private fun initFloat() {
        try {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
                EasyFloat.dismiss(FLOAT_VIEW_TAG)
            }
            EasyFloat.with(Utils.getApp())
                .setTag(FLOAT_VIEW_TAG)
                .setShowPattern(ShowPattern.FOREGROUND)
                .setLocation(
                    ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(58f),
                    ScreenUtils.getScreenHeight() - ConvertUtils.dp2px(200f)
                )
                .setSidePattern(SidePattern.RESULT_HORIZONTAL)
                .setImmersionStatusBar(true)
                .setFilter(LogUpActivity::class.java)
                .setLayout(R.layout.float_logup) {
                    it.findViewById<ConstraintLayout>(R.id.cl_float_view).click {
                        Utils.getApp().startActivity(Intent(
                            Utils.getApp(),
                            LogUpActivity::class.java
                        ).apply {
                            flags = FLAG_ACTIVITY_NEW_TASK
                        })
                    }
                }.show()
        } catch (e: Exception) {
            LogUtils.e("---e--->${e.printStackTrace()}")
        }
    }

    /**
     * 初始化并显示全局浮框
     */
    fun show() {
        requestPermission()
    }
}