package com.base.scanqrclear.ui.widget

import android.app.AlertDialog
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.base.scanqrclear.R
import com.base.scanqrclear.databinding.DialogHistoryMoreBinding
import com.base.scanqrclear.ui.widget.DeleteQRDialog.showDeleteQRDialog
import com.base.scanqrclear.utils.DialogUtils.viewIsTopHalf
import com.base.scanqrclear.utils.LogEx

object HistoryMoreDialog {
    private val TAG = "HistoryMoreDialog"
    fun Context.showHistoryMoreDialog(
        anchorView: View,
        detailAction: (() -> Unit)? = null,
        removeAction: (() -> Unit)? = null,
    ) {
        val dialog = AlertDialog.Builder(this).create()
        val binding = DialogHistoryMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        val params = dialog.window?.attributes
        params?.dimAmount = 0f
        params?.width = resources.getDimensionPixelOffset(R.dimen.dp_200)
//        params?.width = FrameLayout.LayoutParams.WRAP_CONTENT
        params?.height = FrameLayout.LayoutParams.WRAP_CONTENT
        params?.gravity = Gravity.TOP

        val location = IntArray(2)
        val isTopHalf = viewIsTopHalf(anchorView)
        LogEx.logDebug(TAG, "isTopHalf=$isTopHalf")
        anchorView.getLocationOnScreen(location)
        //减少宽度附近的值
        val x = location[0] - resources.getDimensionPixelOffset(R.dimen.dp_256)
        val y = if (isTopHalf) {
            location[1] - resources.getDimensionPixelOffset(R.dimen.dp_15)
        } else {
            //减少高度附近的值
            location[1] - resources.getDimensionPixelOffset(R.dimen.dp_114) - anchorView.height
        }
        params?.x = x
        params?.y = y
        dialog.window?.attributes = params

        binding.tvDetail.setOnClickListener {
            dialog.dismiss()
            detailAction?.invoke()
        }
        binding.tvRemove.setOnClickListener {
            dialog.dismiss()
            showDeleteQRDialog(removeAction)
        }
    }
}