package com.lukouguoji.gjj.holder

import android.view.View
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.ItemIntArrAirManifestBinding
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.GjjAirManifest
import com.lukouguoji.module_base.ktx.refresh

/**
 * 国际进港原始舱单 ViewHolder
 */
class IntArrAirManifestViewHolder(view: View) :
    BaseViewHolder<GjjAirManifest, ItemIntArrAirManifestBinding>(view) {

    override fun onBind(item: Any?, position: Int) {
        val bean = getItemBean(item) ?: return
        val manifest = bean.getMainManifest()

        binding.bean = bean
        binding.manifest = manifest
        binding.position = position
        binding.executePendingBindings()

        // 整卡点击 - 跳转详情页
        notifyItemClick(position, binding.ll)

        // 图标点击 - 切换选择状态（独立选择，不联动子列表）
        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())
        }

        // 初始化分单子列表 RecyclerView
        setCommonAdapter(
            binding.rvSub,
            IntArrAirManifestSubViewHolder::class.java,
            R.layout.item_int_arr_air_manifest_sub
        )

        val subList = bean.haWbList ?: emptyList()
        binding.rvSub.tag = bean
        binding.rvSub.refresh(subList)
        updateSubListVisibility(subList.isNotEmpty())
    }

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