package com.lukouguoji.gjc.holder

import android.view.View
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.activity.IntExpArriveActivity
import com.lukouguoji.gjc.databinding.ItemIntExpArriveBinding
import com.lukouguoji.module_base.adapter.setCommonAdapter
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.bean.GjcMaWb
import com.lukouguoji.module_base.ktx.refresh

/**
 * 国际出港-出港运抵 列表项ViewHolder
 *
 * item 布局分平板（layout-sw600dp/item_int_exp_arrive.xml，内嵌分单子列表 rv_sub 展开/收起）
 * 与手机（layout/item_int_exp_arrive.xml，分单改为独立「分单明细」页，无 rv_sub/iv_show 等 id）
 * 两个变体，单侧独有的 id 在 Binding 基类中为 `@Nullable`，需判空调用。
 */
class IntExpArriveViewHolder(view: View) :
    BaseViewHolder<GjcMaWb, ItemIntExpArriveBinding>(view) {

    override fun onBind(item: Any?, position: Int) {
        val bean = getItemBean(item) ?: return
        val activity = itemView.context as? IntExpArriveActivity
        binding.bean = bean
        binding.position = position
        binding.activity = activity
        binding.viewModel = activity?.itemViewModel
        binding.executePendingBindings()

        // 添加图标点击事件 - 切换选择状态（平板独有）
        binding.ivIcon?.setOnClickListener {
            bean.checked.set(!bean.checked.get())
            FlowBus.with<String>(ConstantEvent.EVENT_CHECK_CHANGED).tryEmit("check_changed")
            binding.executePendingBindings()
        }

        // 展开按钮点击事件（平板独有）
        binding.ivShow?.setOnClickListener {
            bean.showMore.set(!bean.showMore.get())
        }

        // 选择圈点击事件（手机独有，仅待运抵 Tab 可见）
        binding.ivSelect?.setOnClickListener {
            bean.checked.set(!bean.checked.get())
            activity?.onItemCheckChanged()
            binding.executePendingBindings()
        }

        // 子列表 RecyclerView 仅平板存在，手机版分单改走独立页面
        val rvSub = binding.rvSub ?: return

        // 初始化子列表 RecyclerView
        setCommonAdapter(
            rvSub,
            IntExpArriveSubViewHolder::class.java,
            R.layout.item_int_exp_arrive_sub
        )

        // 刷新子列表数据
        val subList = bean.haWbList ?: emptyList()
        rvSub.refresh(subList)
        updateSubListVisibility(subList.isNotEmpty())
    }

    private fun updateSubListVisibility(hasData: Boolean) {
        val llHeader = binding.llHeader ?: return
        val dividerHeader = binding.dividerHeader ?: return
        val rvSub = binding.rvSub ?: return
        val tvEmpty = binding.tvEmpty ?: return
        if (hasData) {
            llHeader.visibility = View.VISIBLE
            dividerHeader.visibility = View.VISIBLE
            rvSub.visibility = View.VISIBLE
            tvEmpty.visibility = View.GONE
        } else {
            llHeader.visibility = View.GONE
            dividerHeader.visibility = View.GONE
            rvSub.visibility = View.GONE
            tvEmpty.visibility = View.VISIBLE
        }
    }
}
