package com.casic.br.adapter

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.casic.br.R
import com.casic.br.model.AddressListModel
import com.pengxh.kt.lite.extensions.dp2px
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction
import com.qmuiteam.qmui.recyclerView.QMUISwipeViewHolder

class AddressListAdapter(
    context: Context, private val dataRows: MutableList<AddressListModel.DataModel.RowsModel>
) : RecyclerView.Adapter<QMUISwipeViewHolder>() {

    private var layoutInflater: LayoutInflater = LayoutInflater.from(context)

    private var deleteAction = QMUISwipeAction.ActionBuilder()
        .icon(ContextCompat.getDrawable(context, R.drawable.ic_delete_white))
        .textSize(16f.dp2px(context))
        .textColor(Color.WHITE)
        .paddingStartEnd(16f.dp2px(context)).text("删除")
        .backgroundColor(Color.RED)
        .build()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QMUISwipeViewHolder {
        val view = layoutInflater.inflate(R.layout.item_address_rv_l, parent, false)
        val swipeViewHolder = QMUISwipeViewHolder(view)
        swipeViewHolder.addSwipeAction(deleteAction)
        return swipeViewHolder
    }

    override fun onBindViewHolder(holder: QMUISwipeViewHolder, position: Int) {
        //初始化控件
        val userPhoneView: TextView = holder.itemView.findViewById(R.id.userPhoneView)
        val detailAddressView: TextView = holder.itemView.findViewById(R.id.detailAddressView)
        val updateTimeView: TextView = holder.itemView.findViewById(R.id.updateTimeView)
        val editAddressView: ImageView = holder.itemView.findViewById(R.id.editAddressView)

        //绑定数据
        val rowsBean = dataRows[position]
        userPhoneView.text = rowsBean.account
        detailAddressView.text = rowsBean.detailAddress
        updateTimeView.text = rowsBean.updateTime

        editAddressView.setOnClickListener {
            clickListener?.onEditButtonClicked(position)
        }
    }

    override fun getItemCount(): Int = dataRows.size

    private var clickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onEditButtonClicked(position: Int)
    }

    fun setOnItemClickListener(clickListener: OnItemClickListener?) {
        this.clickListener = clickListener
    }
}