package com.yidian.bcommon.widget

import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.yidian.bcommon.R
import com.yidian.bcommon.base.BaseDialog
import com.yidian.bcommon.databinding.DialogCommonInfoBinding
import com.yidian.utils.DensityUtil

/**
 * author: yinjiacheng
 * date: 7/16/21 08:50 PM
 * description: 通用信息dialog
 */
class CommonInfoDialog @JvmOverloads constructor(
  context: Context,
  val title: String,
  val content: CharSequence,
  val options: ArrayList<String>,
  val callback: OnOptionCallback?,
  private val widthDp: Int = 280,
  private val leftBtnColor: Int = R.color.color_8F000000,
  private val rightBtnColor: Int = R.color.color_1852F1,
) : BaseDialog<DialogCommonInfoBinding>(context), View.OnClickListener {

  override fun createViewBinding(): DialogCommonInfoBinding {
    return DialogCommonInfoBinding.inflate(layoutInflater)
  }

  override fun initView() {
    viewBinding.tvTitle.text = title
    viewBinding.tvContent.text = content
    when (options.size) {
      1 -> {
        viewBinding.btnRight.text = options[0]
        viewBinding.btnLeft.isVisible = false
        viewBinding.viewVerticalDivider.isVisible = false
        viewBinding.btnRight.setTextColor(ContextCompat.getColor(context, rightBtnColor))
      }
      2 -> {
        viewBinding.btnLeft.text = options[0]
        viewBinding.btnRight.text = options[1]
        viewBinding.btnLeft.setTextColor(ContextCompat.getColor(context, leftBtnColor))
        viewBinding.btnRight.setTextColor(ContextCompat.getColor(context, rightBtnColor))
      }
    }
  }

  override fun initListener() {
    viewBinding.btnLeft.setOnClickListener(this)
    viewBinding.btnRight.setOnClickListener(this)
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    setCanceledOnTouchOutside(false)
  }

  override fun show() {
    super.show()
    val attrs = window?.attributes
    attrs?.width = DensityUtil.dp2px(widthDp.toFloat())
    attrs?.height = WindowManager.LayoutParams.WRAP_CONTENT
    window?.attributes = attrs
    window?.attributes?.gravity = Gravity.CENTER
  }

  override fun onClick(v: View?) {
    if (v?.id == R.id.btn_left) {
      callback?.onLeftOption()
    } else if (v?.id == R.id.btn_right) {
      callback?.onRightOption()
    }
    // 点击左右均要关闭弹框
    dismiss()
  }

  interface OnOptionCallback {
    /**
     * 左操作项
     */
    fun onLeftOption()

    /**
     * 右操作项
     */
    fun onRightOption()
  }

}
