package com.lukouguoji.aerologic.page.gnj.move.stash.list

import android.view.View
import android.widget.Toast
import com.lukouguoji.aerologic.databinding.ItemGnjMoveStashListBinding
import com.lukouguoji.aerologic.page.gnj.move.stash.detail.GnjMoveStashDetailActivity
import com.lukouguoji.gnj.page.yiku.handover.GnjYiKuHandoverActivity
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.bean.MoveStashBean
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.impl.FlowBus
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 国内进港移库列表项 ViewHolder（双形态共用）
 *
 * 平板/手机布局差异较大，单侧独有的控件 id 在 Binding 基类中为 @Nullable，
 * 全部走判空调用（平板：swipe_menu/btn_edit/ll；手机：ll_detail）。
 */
class GnjMoveStashListViewHolder(view: View) :
    BaseViewHolder<MoveStashBean, ItemGnjMoveStashListBinding>(view) {

    override fun onBind(item: Any?, position: Int) {
        val bean = getItemBean(item)!!
        binding.bean = bean
        binding.position = position
        binding.activity = itemView.context as? GnjMoveStashListActivity

        // 勾选框（双形态共有）：切换选中；手机端另行广播刷新全选/已选计数
        binding.ivIcon.setOnClickListener {
            bean.checked.set(!bean.checked.get())
            binding.executePendingBindings()

            GlobalScope.launch {
                FlowBus.with<String>(ConstantEvent.EVENT_CHECK_CHANGED).emit("check_changed")
            }
        }

        // ===== 平板独有交互 =====

        // 点击列表项进入移交详情
        binding.ll?.setOnClickListener {
            GnjYiKuHandoverActivity.startForDetails(itemView.context, bean.mawbId)
        }

        // 侧滑菜单 - 编辑按钮
        binding.btnEdit?.setOnClickListener {
            binding.swipeMenu?.quickClose()
            if (bean.pickFlag == "1") {
                Toast.makeText(itemView.context, "已出库，不可编辑", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            GnjYiKuHandoverActivity.startForEdit(itemView.context, bean.mawbId)
        }

        // ===== 手机独有交互 =====

        // 「查看详情」→ 手机版运单详情页
        binding.llDetail?.setOnClickListener {
            GnjMoveStashDetailActivity.start(itemView.context, bean)
        }

        binding.executePendingBindings()
    }
}
