package com.pan_american.android.data.model.financial_module.accounts_receivable_report.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.data.model.financial_module.accounts_receivable_report.entity.AccountReceivableReportListItem

class AccountsReceivableReportAdapter(private val itemList: ArrayList<AccountReceivableReportListItem>): RecyclerView.Adapter<AccountsReceivableReportAdapter.ViewHolder>(){

    lateinit var onDetailClick: OnRecyclerViewItemClick

    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val groupName: TextView = view.findViewById(R.id.group_name)
        val departmentName: TextView = view.findViewById(R.id.department_name)
        val receivables: TextView = view.findViewById(R.id.receivables)
        val paymentCollected: TextView = view.findViewById(R.id.payment_collected)
        val paymentRefund: TextView = view.findViewById(R.id.payment_refund)
        val paymentBalance: TextView = view.findViewById(R.id.payment_balance)
        val paymentCollectionProgress: TextView = view.findViewById(R.id.payment_collection_progress)
        val detail: TextView = view.findViewById(R.id.detail)

        val parentView: LinearLayout = view.findViewById(R.id.item_view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(OASystem.context).inflate(R.layout.item_accounts_receivable_report, parent, false)
        val viewHolder = ViewHolder(view)

        viewHolder.detail.setOnClickListener {
            onDetailClick.onDetailClick(viewHolder.absoluteAdapterPosition)
        }

        return viewHolder
    }

    override fun getItemCount() = itemList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        itemList[position].also {

            if (it.frPrice.toDouble() == 0.0) {
                holder.parentView.visibility = View.GONE
            } else {
                holder.parentView.visibility = View.VISIBLE
                holder.groupName.text = it.teamName
                holder.departmentName.text = it.clientUnit
                holder.receivables.text = it.frPrice + " RMB"
                holder.paymentCollected.text = it.prPrice + " RMB"
                holder.paymentRefund.text = it.refundAmount + " RMB"
                holder.paymentBalance.text = it.balPrice + " RMB"
                holder.paymentCollectionProgress.text = it.schedule.ifBlank { "-" }
            }
        }
    }

    interface OnRecyclerViewItemClick {
        fun onDetailClick(position: Int)
    }
}