package com.lukouguoji.aerologic.page.log.detail

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.aerologic.R
import com.lukouguoji.module_base.bean.StatusLogBean

class LogDetailTimelineAdapter : RecyclerView.Adapter<LogDetailTimelineAdapter.TimelineViewHolder>() {

    private var items: List<StatusLogBean> = emptyList()
    private var statusNameMap: Map<String, String> = emptyMap()

    fun setData(list: List<StatusLogBean>, stepMap: Map<String, String> = emptyMap()) {
        items = list
        statusNameMap = stepMap
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TimelineViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_log_timeline, parent, false)
        return TimelineViewHolder(view)
    }

    override fun onBindViewHolder(holder: TimelineViewHolder, position: Int) {
        val item = items[position]
        val isFirst = position == 0
        val isLast = position == items.size - 1

        val statusName = statusNameMap[item.status] ?: item.status
        holder.tvContent.text = if (statusName.isNotEmpty()) "$statusName  ${item.opDate}" else item.opDate
        holder.tvTime.text = item.content

        // 最后一项（当前步骤）用绿色圆点
        holder.dotView.setBackgroundResource(
            if (isLast) R.drawable.bg_timeline_dot_green
            else R.drawable.bg_timeline_dot_gray
        )

        // 第一项不显示顶部连线
        holder.lineTop.visibility = if (isFirst) View.INVISIBLE else View.VISIBLE

        // 最后一项不显示底部连线
        holder.lineBottom.visibility = if (isLast) View.INVISIBLE else View.VISIBLE
    }

    override fun getItemCount(): Int = items.size

    class TimelineViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val dotView: View = view.findViewById(R.id.view_dot)
        val lineTop: View = view.findViewById(R.id.view_line_top)
        val lineBottom: View = view.findViewById(R.id.view_line_bottom)
        val tvContent: TextView = view.findViewById(R.id.tv_content)
        val tvTime: TextView = view.findViewById(R.id.tv_time)
    }
}
