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

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
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
import com.lukouguoji.module_base.util.DeviceUtil

@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(if (DeviceUtil.isPhone()) "运单追踪" else "操作日志详情")
        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 ->
            val stepMap = viewModel.allSteps.value?.associate { it.code to it.name } ?: emptyMap()
            timelineAdapter.setData(list, stepMap)
        }

        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
        // 手机布局是竖排时间线（layout/activity_log_detail.xml），平板保持横向步骤条
        if (DeviceUtil.isPhone()) {
            buildVerticalSteps(steps, activeCodes, latestCode)
        } else {
            buildStepProgressBar(steps, activeCodes, latestCode)
        }
    }

    /**
     * 手机版竖排流转时间线（对应设计稿「运单追踪」）：
     * 每个节点 = 左侧圆点 + 连接竖线，右侧步骤名 + 该环节最新操作时间。
     * 已发生节点绿色，未发生节点灰色。
     */
    private fun buildVerticalSteps(
        steps: List<StepInfo>,
        activeCodes: Set<String>,
        latestCode: String
    ) {
        val container = binding.llSteps
        container.removeAllViews()
        container.orientation = LinearLayout.VERTICAL

        val logs = viewModel.statusLogList.value ?: emptyList()
        val colorGreen = 0xFF16A34A.toInt()
        val colorGray = 0xFF9CA3AF.toInt()
        val colorLine = 0xFFE5E7EB.toInt()

        for (i in steps.indices) {
            val step = steps[i]
            val isActive = step.code in activeCodes
            val isLast = i == steps.size - 1
            val stepLog = logs.lastOrNull { it.status == step.code }
            val time = stepLog?.opDate ?: ""
            val statusContent = stepLog?.content ?: ""

            val row = LinearLayout(this).apply {
                orientation = LinearLayout.HORIZONTAL
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            }

            // 左列：圆点 + 连接竖线
            val dotColumn = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER_HORIZONTAL
                layoutParams = LinearLayout.LayoutParams(dp(20), LinearLayout.LayoutParams.MATCH_PARENT)
            }
            val dot = View(this).apply {
                setBackgroundResource(
                    if (isActive) com.lukouguoji.module_base.R.drawable.bg_phone_dot_green
                    else com.lukouguoji.module_base.R.drawable.bg_phone_dot_gray
                )
                layoutParams = LinearLayout.LayoutParams(
                    dp(if (isActive) 12 else 8), dp(if (isActive) 12 else 8)
                ).apply { topMargin = dp(if (isActive) 2 else 4) }
            }
            dotColumn.addView(dot)
            if (!isLast) {
                val line = View(this).apply {
                    setBackgroundColor(colorLine)
                    layoutParams = LinearLayout.LayoutParams(dp(2), 0).apply {
                        weight = 1f
                        topMargin = dp(2)
                        bottomMargin = dp(2)
                    }
                }
                dotColumn.addView(line)
            }
            row.addView(dotColumn)

            // 右列：步骤名 + 时间
            val content = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                layoutParams = LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    weight = 1f
                    leftMargin = dp(10)
                }
                setPadding(0, 0, 0, if (isLast) 0 else dp(24))
            }
            // 名称行：步骤名（左）+ 已发生节点的状态 pill（右，设计稿如「放行状态：01」）
            val nameRow = LinearLayout(this).apply {
                orientation = LinearLayout.HORIZONTAL
                gravity = Gravity.CENTER_VERTICAL
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            }
            nameRow.addView(TextView(this).apply {
                text = step.name
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
                setTextColor(if (isActive) colorGreen else colorGray)
                if (isActive) setTypeface(typeface, android.graphics.Typeface.BOLD)
                layoutParams = LinearLayout.LayoutParams(
                    0, LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply { weight = 1f }
            })
            if (isActive && statusContent.isNotEmpty()) {
                nameRow.addView(TextView(this).apply {
                    text = statusContent
                    setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
                    setTextColor(colorGreen)
                    setBackgroundResource(com.lukouguoji.module_base.R.drawable.bg_phone_tag_green)
                    setPadding(dp(8), dp(3), dp(8), dp(3))
                    maxLines = 1
                    ellipsize = android.text.TextUtils.TruncateAt.END
                    maxWidth = dp(180)
                    layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    ).apply { leftMargin = dp(8) }
                })
            }
            content.addView(nameRow)
            if (time.isNotEmpty()) {
                content.addView(TextView(this).apply {
                    text = time
                    setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
                    setTextColor(colorGray)
                    layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    ).apply { topMargin = dp(4) }
                })
            }
            row.addView(content)

            container.addView(row)
        }
    }

    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 dotSize = dp(10)
        val lineHeight = dp(2)
        val labelHPadding = dp(6)
        val alignBase = dp(27)

        // 按"四个汉字 label"估算节点 label 宽度（含左右各 6dp padding）
        val labelTextSizePx = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP, 13f, resources?.displayMetrics
        )
        val fourCharTextWidth = Paint().apply { textSize = labelTextSizePx }
            .measureText("测测测测").toInt()
        val estimatedLabelWidth = fourCharTextWidth + labelHPadding * 2

        // 计算每个节点宽度：屏幕宽度的 80% 均分给所有节点，并加上限避免步数少时单格过宽
        val screenWidth = resources!!.displayMetrics.widthPixels
        val rawStepWidth = (screenWidth * 0.8 / steps.size).toInt()
        val maxStepWidth = estimatedLabelWidth + dp(40)
        val stepWidth = minOf(rawStepWidth, maxStepWidth)

        // 让第一个 label（居中在 stepWidth 内）的左边缘对齐到卡片内 15dp 基准线
        // labelLeftInStep = (stepWidth - estimatedLabelWidth) / 2
        // 所需 ll_steps leftMargin = alignBase - labelLeftInStep
        val labelLeftInStep = (stepWidth - estimatedLabelWidth) / 2
        (container.layoutParams as? ViewGroup.MarginLayoutParams)?.let {
            it.leftMargin = alignBase - labelLeftInStep
            container.layoutParams = it
        }

        // 找到最新节点在步骤列表中的索引
        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

            // 每个步骤的根容器（内部水平居中：label 与圆点都在 stepWidth 中心）
            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(labelHPadding, dp(2), labelHPadding, 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) {
                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) {
                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)
        }
    }
}
