package com.pan_american.android.data.model.group_op.ground_convey_payment_insert.adapter

import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.data.model.group_op.ground_convey_payment_insert.entity.GroundConveyTableItem
import com.pan_american.android.util.MoneyInputFilter
import com.pan_american.android.util.ScrollEditText

class GroundConveyTableAdapter(private val itemList: ArrayList<GroundConveyTableItem>) :
    RecyclerView.Adapter<GroundConveyTableAdapter.ViewHolder>() {

    lateinit var onItemTextChanged: OnItemTextChanged

    lateinit var onItemClick: OnItemClick

    private val regex = Regex("^-?\\d+(\\.\\d{1,2})?\$")

    var price = 0.0

    var priceContentText = ""

    var count = ""

    private var canBeEdit = true

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val listItem: LinearLayout = view.findViewById(R.id.list_item)
        val paymentItemName: TextView = view.findViewById(R.id.payment_item_name)
        val price: EditText = view.findViewById(R.id.price)
        val priceUnit: TextView = view.findViewById(R.id.price_unit)
        val count: EditText = view.findViewById(R.id.count)
        val unit: TextView = view.findViewById(R.id.unit)
        val date: TextView = view.findViewById(R.id.date)
        val detail: ScrollEditText = view.findViewById(R.id.cost_detail)

    }

    override fun getItemViewType(position: Int): Int {
        return R.layout.item_ground_convey_table
    }

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

        val viewHolder = ViewHolder(view)

        if (!canBeEdit) {
            viewHolder.price.isEnabled = false
            viewHolder.count.isEnabled = false
            viewHolder.unit.isEnabled = false
            viewHolder.detail.isEnabled(false)
        } else {
            viewHolder.price.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun afterTextChanged(p0: Editable?) {
                    if (viewHolder.price.text.isNullOrBlank()) {
                        Toast.makeText(
                            OASystem.context,
                            String.format("%s 金额不能为空！", viewHolder.paymentItemName.text),
                            Toast.LENGTH_SHORT
                        ).show()
                        return
                    }

                    if (viewHolder.price.text.endsWith('.')) {
                        return
                    }

                    if (viewHolder.price.text.matches(regex)) {
                        price = viewHolder.price.text.toString().toDouble()
                        onItemTextChanged.onPriceTextChanged(viewHolder.bindingAdapterPosition)
                    } else {
                        Toast.makeText(
                            OASystem.context,
                            String.format("请输入正确的 %s 金额", viewHolder.paymentItemName.text),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })

            viewHolder.unit.setOnClickListener {
                onItemClick.onUnitClick(viewHolder.bindingAdapterPosition)
            }

            viewHolder.count.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun afterTextChanged(p0: Editable?) {
                    try {
                        if (viewHolder.count.text.isNullOrBlank()) {
                            Toast.makeText(
                                OASystem.context,
                                String.format("%s 数量不能为空！", viewHolder.paymentItemName.text),
                                Toast.LENGTH_SHORT
                            ).show()
                            return
                        } else {
                            count = viewHolder.count.text.toString()
                            onItemTextChanged.onCountChanged(viewHolder.bindingAdapterPosition)
                        }
                    } catch (e: Exception) {
                        Toast.makeText(OASystem.context, "超出最大数量!", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            })

            viewHolder.detail.addTextChangedListener({}, {}, {
                priceContentText = viewHolder.detail.getText()
                onItemTextChanged.onPriceContentChanged(viewHolder.bindingAdapterPosition)
            })
        }

        return viewHolder
    }

    override fun getItemCount() = itemList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val item = itemList[holder.bindingAdapterPosition]

        holder.listItem.visibility = View.VISIBLE
        holder.paymentItemName.text = item.sidName
        holder.price.setText(item.price.toString())
        holder.priceUnit.text = item.currencyStr
        holder.count.setText(item.count.toString())

        for (checkedItem in OASystem.unitList) {
            if (checkedItem.id == item.units) {
                holder.unit.text = checkedItem.name
            }
        }

        holder.listItem.visibility = View.VISIBLE

        if (item.sId == 1070 || item.sId == 1071) {
            holder.date.text = "无"
        } else {
            holder.date.text = item.datePrice.substring(0, 10)
        }

        holder.detail.setText(item.priceContent)

        holder.price.filters = arrayOf(MoneyInputFilter())

        holder.price.onFocusChangeListener = View.OnFocusChangeListener { _, flag ->
            if (!flag) {
                if (holder.price.text.isNullOrBlank()) {
                    holder.price.setText(item.price.toString())
                }
            }
        }

        holder.count.onFocusChangeListener = View.OnFocusChangeListener { _, flag ->
            if (!flag) {
                if (holder.count.text.isNullOrBlank()) {
                    holder.count.setText(item.count.toString())
                }
            }
        }
    }

    fun setCanBeEdit(flag: Boolean) {
        canBeEdit = flag
    }

    interface OnItemClick {
        fun onUnitClick(itemPosition: Int)
    }

    interface OnItemTextChanged {
        fun onPriceTextChanged(position: Int)
        fun onPriceContentChanged(position: Int)
        fun onCountChanged(position: Int)
    }
}