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

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.lukouguoji.aerologic.R
import com.lukouguoji.aerologic.databinding.ActivityLogDetailBinding
import com.lukouguoji.module_base.base.BaseBindingActivity
import com.lukouguoji.module_base.bean.LogBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants

@Route(path = ARouterConstants.ACTIVITY_URL_LOG_DETAIL)
class LogDetailActivity : BaseBindingActivity<ActivityLogDetailBinding, LogDetailViewModel>() {

    private val timelineAdapter = LogDetailTimelineAdapter()

    override fun layoutId(): Int {
        return R.layout.activity_log_detail
    }

    override fun viewModelClass(): Class<LogDetailViewModel> {
        return LogDetailViewModel::class.java
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow("操作日志详情")
        binding.viewModel = viewModel

        // 配置操作详情 RecyclerView（垂直时间线）
        binding.rvTimeline.adapter = timelineAdapter

        // 观察数据变化，重新构建步骤进度条
        viewModel.allSteps.observe(this) { rebuildSteps() }
        viewModel.activeStepCodes.observe(this) { rebuildSteps() }
        viewModel.latestStepCode.observe(this) { rebuildSteps() }

        viewModel.statusLogList.observe(this) { list ->
            timelineAdapter.setData(list)
        }

        viewModel.initOnCreated(intent)
    }

    private fun rebuildSteps() {
        val steps = viewModel.allSteps.value ?: return
        val activeCodes = viewModel.activeStepCodes.value ?: emptySet()
        val latestCode = viewModel.latestStepCode.value ?: ""
        if (steps.isEmpty()) return
        buildStepProgressBar(steps, activeCodes, latestCode)
    }

    private fun buildStepProgressBar(
        steps: List<StepInfo>,
        activeCodes: Set<String>,
        latestCode: String
    ) {
        val container = binding.llSteps
        container.removeAllViews()

        val colorBlue = 0xFF1C8CF5.toInt()
        val colorGray = 0xFFCCCCCC.toInt()
        val colorGreen = 0xFF4CAF50.toInt()
        val dotSize = dp(10)
        val lineHeight = dp(2)

        // 计算每个节点宽度：屏幕宽度的 80% 均分给所有节点
        val screenWidth = resources!!.displayMetrics.widthPixels
        val stepWidth = (screenWidth * 0.8 / steps.size).toInt()

        // 找到最新节点在步骤列表中的索引
        val latestIndex = steps.indexOfFirst { it.code == latestCode }

        for (i in steps.indices) {
            val step = steps[i]
            val isActive = step.code in activeCodes
            val isLatest = step.code == latestCode
            val isFirst = i == 0
            val isLast = i == steps.size - 1

            // 每个步骤的根容器
            val stepLayout = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER_HORIZONTAL
                layoutParams = LinearLayout.LayoutParams(stepWidth, LinearLayout.LayoutParams.WRAP_CONTENT)
            }

            // 步骤名称（所有步骤统一 padding 确保高度一致）
            val tvName = TextView(this).apply {
                text = step.name
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
                gravity = Gravity.CENTER
                setPadding(dp(6), dp(2), dp(6), dp(2))
                if (isLatest) {
                    setBackgroundResource(R.drawable.bg_step_current_badge)
                    setTextColor(0xFFFFFFFF.toInt())
                } else {
                    setTextColor(if (isActive) 0xFF333333.toInt() else 0xFF999999.toInt())
                }
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            }
            stepLayout.addView(tvName)

            // 圆点和连线区域（FrameLayout 叠加）
            val dotLineContainer = FrameLayout(this).apply {
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, dp(20)
                ).apply { topMargin = dp(8) }
            }

            // 左半连线（从左边缘到中心）
            if (!isFirst) {
                // 如果当前节点索引 <= latestIndex，左半线为蓝色；否则为浅灰色
                val leftLineColor = if (latestIndex >= 0 && i <= latestIndex) colorBlue else colorGray
                val lineLeft = View(this).apply {
                    setBackgroundColor(leftLineColor)
                    layoutParams = FrameLayout.LayoutParams(0, lineHeight).apply {
                        gravity = Gravity.CENTER_VERTICAL or Gravity.START
                    }
                }
                dotLineContainer.addView(lineLeft)
                dotLineContainer.post {
                    lineLeft.layoutParams = FrameLayout.LayoutParams(
                        dotLineContainer.width / 2 + dotSize / 2, lineHeight
                    ).apply { gravity = Gravity.CENTER_VERTICAL or Gravity.START }
                }
            }

            // 右半连线（从中心到右边缘）
            if (!isLast) {
                // 如果当前节点索引 < latestIndex，右半线为蓝色；否则为浅灰色
                val rightLineColor = if (latestIndex >= 0 && i < latestIndex) colorBlue else colorGray
                val lineRight = View(this).apply {
                    setBackgroundColor(rightLineColor)
                    layoutParams = FrameLayout.LayoutParams(0, lineHeight).apply {
                        gravity = Gravity.CENTER_VERTICAL or Gravity.END
                    }
                }
                dotLineContainer.addView(lineRight)
                dotLineContainer.post {
                    lineRight.layoutParams = FrameLayout.LayoutParams(
                        dotLineContainer.width / 2 + dotSize / 2, lineHeight
                    ).apply { gravity = Gravity.CENTER_VERTICAL or Gravity.END }
                }
            }

            // 圆点（叠加在连线之上）
            val dot = View(this).apply {
                setBackgroundResource(
                    when {
                        isLatest -> R.drawable.bg_step_dot_green
                        isActive -> R.drawable.bg_step_dot_blue
                        else -> R.drawable.bg_step_dot_gray
                    }
                )
                layoutParams = FrameLayout.LayoutParams(dotSize, dotSize).apply {
                    gravity = Gravity.CENTER
                }
            }
            dotLineContainer.addView(dot)

            stepLayout.addView(dotLineContainer)
            container.addView(stepLayout)
        }
    }

    private fun dp(value: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, value.toFloat(), resources?.displayMetrics
        ).toInt()
    }

    companion object {
        @JvmStatic
        fun start(context: Context, bean: LogBean) {
            val starter = Intent(context, LogDetailActivity::class.java)
            starter.putExtra(Constant.Key.DATA, Gson().toJson(bean))
            context.startActivity(starter)
        }
    }
}
