package com.yidian.shenghuoquan.commodity.ui.coupon.adapter

import android.content.Context
import android.graphics.Paint
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.yidian.common.widget.CommonHintDialog
import com.yidian.shenghuoquan.commodity.BR
import com.yidian.shenghuoquan.commodity.R
import com.yidian.shenghuoquan.commodity.databinding.CommodityItemCommodityAuditListBinding
import com.yidian.shenghuoquan.commodity.databinding.CommodityItemCommodityOfflineListBinding
import com.yidian.shenghuoquan.commodity.databinding.CommodityItemCommodityOnlineListBinding
import com.yidian.shenghuoquan.commodity.databinding.CommodityItemCommodityRejectListBinding
import com.yidian.shenghuoquan.commodity.dto.CommodityStatus
import com.yidian.shenghuoquan.commodity.dto.Goods
import com.yidian.shenghuoquan.commodity.ui.coupon.viewmodel.CommodityListItemViewModel
import com.yidian.utils.DensityUtil
import com.yidian.utils.ToastUtil

/**
 * author: yinjiacheng
 * date: 7/2/21 2:33 PM
 * description: 商品管理列表adapter
 */
class CommodityListAdapter(private val context: Context, private val status: CommodityStatus) :
  RecyclerView.Adapter<RecyclerView.ViewHolder>() {

  companion object {
    // 商品状态标识
    private const val ID_COMMODITY_ONLINE = 1
    private const val ID_COMMODITY_AUDIT = 2
    private const val ID_COMMODITY_REJECT = 3
    private const val ID_COMMODITY_OFFLINE = 4

    /**
     * 加载圆角图片
     * @param url 图片url
     * @param corner 圆角值
     * @param target 目标ImageView
     */
    @BindingAdapter(value = ["url", "corner"], requireAll = true)
    @JvmStatic
    fun loadRoundCornerImage(target: ImageView, url: String, corner: Int = 12) {
      Glide.with(target.context).load(url)
        .apply(RequestOptions().transform(CenterCrop(), RoundedCorners(DensityUtil.dp2px(corner.toFloat()))))
        .into(target)
    }
  }

  /**
   * 商品数据
   */
  private val commodityData by lazy { ArrayList<Goods>() }

  /**
   * 商品数据变化
   */
  val commodityDataChange by lazy { MutableLiveData<ArrayList<Goods>>() }

  /**
   * 更新数据
   */
  fun updateData(data: List<Goods>?) {
    data?.let {
      notifyItemRangeRemoved(0, commodityData.size)
      commodityData.clear()
      commodityData.addAll(it)
      notifyItemRangeInserted(0, commodityData.size)
    }
  }

  /**
   * 插入数据
   */
  fun insertData(data: List<Goods>?) {
    data?.let {
      commodityData.addAll(it)
      notifyItemRangeInserted(commodityData.size - it.size, it.size)
    }
  }

  /**
   * 获取DataBinding
   */
  private fun <VB : ViewDataBinding> getBinding(parent: ViewGroup, layoutResId: Int): VB {
    return DataBindingUtil.inflate(LayoutInflater.from(parent.context), layoutResId, parent, false)
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    when (viewType) {
      // 上架中
      ID_COMMODITY_ONLINE -> {
        return getBinding<CommodityItemCommodityOnlineListBinding>(
          parent,
          R.layout.commodity_item_commodity_online_list
        ).let { CommodityOnlineItemViewHolder(it, it.root) }
      }
      // 被驳回
      ID_COMMODITY_REJECT -> {
        return getBinding<CommodityItemCommodityRejectListBinding>(
          parent,
          R.layout.commodity_item_commodity_reject_list
        ).let { CommodityRejectItemViewHolder(it, it.root) }
      }
      // 已下架
      ID_COMMODITY_OFFLINE -> {
        return getBinding<CommodityItemCommodityOfflineListBinding>(
          parent,
          R.layout.commodity_item_commodity_offline_list
        ).let { CommodityOfflineItemViewHolder(it, it.root) }
      }
      // 默认审核中
      else -> {
        return getBinding<CommodityItemCommodityAuditListBinding>(
          parent,
          R.layout.commodity_item_commodity_audit_list
        ).let { CommodityAuditItemViewHolder(it, it.root) }
      }
    }
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    // 绑定数据
    val data = commodityData[position]
    when (holder) {
      is CommodityOnlineItemViewHolder -> {
        holder.binding.setVariable(BR.data, data)
        holder.binding.setVariable(BR.vm, CommodityListItemViewModel())
        holder.binding.vm?.commodityOfflineOperationEvent?.observe(context as LifecycleOwner, {
          // 弹出确认下架弹窗
          CommonHintDialog(context, "确认下架优惠券?", arrayListOf("取消", "下架"), object : CommonHintDialog.OnHintOptionCallback {
            override fun onLeftOption() {

            }

            override fun onRightOption() {
              // 下架商品
              holder.binding.vm?.requestCommodityOffline(it.goodsSpuId)
            }

          }).show()
        })
        holder.binding.vm?.commodityOfflineSuccessEvent?.observe(context as LifecycleOwner, {
          // 下架成功 刷新列表
          ToastUtil.showToast(context, "下架成功")
          commodityData.remove(data)
          notifyItemRemoved(position)
          commodityDataChange.value = commodityData
        })
      }
      is CommodityAuditItemViewHolder -> {
        holder.binding.setVariable(BR.data, data)
      }
      is CommodityRejectItemViewHolder -> {
        holder.binding.setVariable(BR.data, data)
        holder.binding.setVariable(BR.vm, CommodityListItemViewModel())
      }
      is CommodityOfflineItemViewHolder -> {
        holder.binding.setVariable(BR.data, data)
        holder.binding.setVariable(BR.vm, CommodityListItemViewModel())
        holder.binding.vm?.commodityOnlineSuccessEvent?.observe(context as LifecycleOwner, {
          // 上架成功 刷新列表
          ToastUtil.showToast(context, "上架成功")
          commodityData.remove(data)
          notifyItemRemoved(position)
          commodityDataChange.value = commodityData
        })
      }
    }
  }

  override fun getItemCount(): Int {
    return commodityData.size
  }

  override fun getItemViewType(position: Int): Int {
    return status.tabId
  }

  /**
   * ViewHolder定义
   */
  class CommodityOnlineItemViewHolder(val binding: CommodityItemCommodityOnlineListBinding, itemView: View) :
    RecyclerView.ViewHolder(itemView) {
    init {
      // 商品原价加删除线
      binding.tvCommodityOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
      binding.tvCommodityOriginalPrice.paint.isAntiAlias = true
    }
  }

  class CommodityAuditItemViewHolder(val binding: CommodityItemCommodityAuditListBinding, itemView: View) :
    RecyclerView.ViewHolder(itemView) {
    init {
      binding.tvCommodityOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
      binding.tvCommodityOriginalPrice.paint.isAntiAlias = true
    }
  }

  class CommodityRejectItemViewHolder(val binding: CommodityItemCommodityRejectListBinding, itemView: View) :
    RecyclerView.ViewHolder(itemView) {
    init {
      binding.tvCommodityOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
      binding.tvCommodityOriginalPrice.paint.isAntiAlias = true
    }
  }

  class CommodityOfflineItemViewHolder(val binding: CommodityItemCommodityOfflineListBinding, itemView: View) :
    RecyclerView.ViewHolder(itemView) {
    init {
      binding.tvCommodityOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
      binding.tvCommodityOriginalPrice.paint.isAntiAlias = true
    }
  }

  class CommodityItemDecoration : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
      outRect.bottom = DensityUtil.dp2px(10f)
    }
  }
}
