package com.lukouguoji.gjc.holder

import android.view.View
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.databinding.ItemIntExpTallyBinding
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
 */
class IntExpTallyViewHolder(view: View) :
    BaseViewHolder<GjcMaWb, ItemIntExpTallyBinding>(view) {

    override fun onBind(item: Any?, position: Int) {
        val bean = getItemBean(item) ?: return
        binding.bean = bean
        binding.position = position
        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())
        }

        // 初始化子列表 RecyclerView
        setCommonAdapter(
            binding.rvSub,
            IntExpTallySubViewHolder::class.java,
            R.layout.item_int_exp_tally_sub
        )

        // 刷新子列表数据
        val subList = bean.haWbList ?: emptyList()
        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
        }
    }
}
