package com.yidian.shenghuoquan.bmanagercenter.widget

import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.View
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.yidian.nightmode.widget.YdConstraintLayout
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.databinding.ViewLifeAccountAuthImageBinding

/**
 * author: yinjiacheng
 * date: 6/2/21 6:09 PM
 * description: 生活号认证 身份证上传
 */
class LifeAccountAuthImageView @JvmOverloads constructor(
  context: Context,
  val attrs: AttributeSet? = null,
  defStyle: Int = 0
) : YdConstraintLayout(context, attrs, defStyle), View.OnClickListener {

  private val viewBinding = ViewLifeAccountAuthImageBinding.bind(
    View.inflate(
      getContext(),
      R.layout.view_life_account_auth_image,
      this
    )
  )

  private var callback: OnLifeAccountAuthImageViewCallback? = null

  init {
    val typeArray =
      getContext().obtainStyledAttributes(attrs, R.styleable.LifeAccountAuthImageView)
    viewBinding.ivPlaceHolder.setImageResource(
      typeArray.getResourceId(
        R.styleable.LifeAccountAuthImageView_LifeAccountAuthImageView_place_holder_image,
        -1
      )
    )
    typeArray.recycle()
    viewBinding.ivClear.setOnClickListener(this)
  }

  /**
   * 填充图片
   * @param resId 图片资源id
   */
  fun addImage(resId: Int) {
    viewBinding.ivContent.setImageResource(resId)
    isEnabled = false
    viewBinding.ivClear.isVisible = true
  }

  /**
   * 填充图片
   * @param bitmap 图片bitmap
   */
  fun addImage(bitmap: Bitmap?) {
    if (bitmap == null) return
    viewBinding.ivContent.setImageBitmap(bitmap)
    isEnabled = false
    viewBinding.ivClear.isVisible = true
  }

  /**
   * 填充图片
   * @param url 图片url
   */
  fun addImage(url: String) {
    if (url.isEmpty()) return
    Glide.with(context).load(url).into(viewBinding.ivContent)
    isEnabled = false
    viewBinding.ivClear.isVisible = true
  }

  /**
   * 清除图片
   */
  fun clearImage() {
    viewBinding.ivContent.setImageDrawable(null)
    isEnabled = true
    viewBinding.ivClear.isVisible = false
    callback?.onImageClear(this)
  }

  /**
   * 禁止修改
   */
  fun disableModify() {
    viewBinding.ivClear.isVisible = false
    isEnabled = false
  }

  override fun onClick(v: View?) {
    if (v?.id == R.id.iv_clear) {
      // 清除填充的图片
      clearImage()
    }
  }

  fun setOnLifeAccountAuthImageViewCallback(callback: OnLifeAccountAuthImageViewCallback) {
    this.callback = callback
  }

  interface OnLifeAccountAuthImageViewCallback {
    /**
     * 清除图片
     */
    fun onImageClear(from: LifeAccountAuthImageView)
  }

}
