package com.lukouguoji.gjj.holder

import android.view.View
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.ItemIntImpTallyBinding
import com.lukouguoji.gjj.activity.IntImpTallyDetailsActivity
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.GjjImportTally
import com.google.gson.Gson
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.refresh
import com.lukouguoji.module_base.ktx.toRequestBody

/**
 * 国际进港理货报告 ViewHolder
 */
class IntImpTallyViewHolder(view: View) :
    BaseViewHolder<GjjImportTally, ItemIntImpTallyBinding>(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.llContent.setOnClickListener {
            IntImpTallyDetailsActivity.start(it.context, bean)
        }

        // 展开按钮点击事件
        binding.ivShow.setOnClickListener {
            if (bean.haWbList != null) {
                // 已加载过数据，直接切换显隐
                bean.showMore.set(!bean.showMore.get())
            } else {
                // 首次展开，调用接口加载分单数据
                loadSubList(bean)
            }
        }

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

        // 刷新分单数据（传递父Bean引用用于反向联动）
        binding.rvSub.tag = bean
        val subList = bean.haWbList ?: emptyList()
        binding.rvSub.refresh(subList)
        updateSubListVisibility(subList.isNotEmpty())
    }

    /**
     * 加载分单列表数据（将主单整体作为请求参数）
     */
    private fun loadSubList(bean: GjjImportTally) {
        // 将 bean 转为 Map 并补充 wbNo 字段（prefix + no）
        val map = Gson().fromJson(Gson().toJson(bean), HashMap::class.java) as HashMap<String, Any?>
        map["wbNo"] = bean.getWaybillNo()
        val params = map.toRequestBody()

        launchCollect({ NetApply.api.getIntImpTallySubList(params) }) {
            onSuccess = { result ->
                val list = result.data?.toMutableList() ?: mutableListOf()
                bean.haWbList = list
                bean.showMore.set(true)
                binding.rvSub.refresh(list)
                updateSubListVisibility(list.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
        }
    }
}
