package com.lukouguoji.gjc.holder

import android.view.View
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.activity.GjcBoxWeighingAddActivity
import com.lukouguoji.gjc.activity.GjcBoxWeighingDetailsActivity
import com.lukouguoji.gjc.databinding.ItemGjcBoxWeighingBinding
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.bean.GjcUldUseBean
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody

/**
 * 国际出港板箱过磅列表 ViewHolder
 */
class GjcBoxWeighingViewHolder(view: View) :
    BaseViewHolder<GjcUldUseBean, ItemGjcBoxWeighingBinding>(view) {

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

        // 更新图标状态
        updateIcon(bean)

        // 图标点击切换选中状态
        binding.ivIcon.setOnClickListener {
            bean.checked.set(!bean.checked.get())
            updateIcon(bean)
        }

        // 整行点击跳转到表单页（带数据回填）
        binding.ll.setOnClickListener {
            if (bean.wtDate.isEmpty()) {
                GjcBoxWeighingAddActivity.startForEdit(it.context, bean)
            } else {
                val params = mapOf(
                    "fdate" to bean.fdate,
                    "fno" to bean.fno,
                    "countryType" to "1"
                ).toRequestBody()
                launchCollect({ NetApply.api.queryFlightByDateAndNo(params) }) {
                    onSuccess = { result ->
                        if (!result.data?.fclose.isNullOrEmpty()) {
                            showToast("该 ULD 已过磅且航班已离港，不允许重新过磅")
                        } else {
                            GjcBoxWeighingAddActivity.startForEdit(it.context, bean)
                        }
                    }
                }
            }
        }

        // 侧滑“详情”按钮点击跳转到只读详情页
        binding.btnDetail.setOnClickListener {
            binding.swipeMenu.quickClose()
            GjcBoxWeighingDetailsActivity.start(it.context, bean.useId)
        }
    }

    private fun updateIcon(bean: GjcUldUseBean) {
        binding.ivIcon.setImageResource(
            if (bean.checked.get()) R.drawable.img_plane_s else R.drawable.img_plane
        )
    }
}
