package com.lukouguoji.gjc.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.databinding.ActivityGjcWeighingRecordDetailsBinding
import com.lukouguoji.gjc.holder.GjcCheckInRecordViewHolder
import com.lukouguoji.gjc.viewModel.GjcWeighingRecordDetailsViewModel
import com.lukouguoji.module_base.base.BaseBindingActivity
import com.lukouguoji.module_base.base.CommonAdapter
import com.lukouguoji.module_base.bean.GjcWeighingRecordBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants

/**
 * 国际出港计重明细页
 */
@Route(path = ARouterConstants.ACTIVITY_URL_GJC_WEIGHING_RECORD_DETAILS)
class GjcWeighingRecordDetailsActivity :
    BaseBindingActivity<ActivityGjcWeighingRecordDetailsBinding, GjcWeighingRecordDetailsViewModel>() {

    private lateinit var adapter: CommonAdapter

    override fun layoutId() = R.layout.activity_gjc_weighing_record_details

    override fun viewModelClass() = GjcWeighingRecordDetailsViewModel::class.java

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow("计重明细")

        binding.viewModel = viewModel

        // 初始化RecyclerView
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = CommonAdapter(
            this,
            R.layout.item_gjc_check_in_record,
            GjcCheckInRecordViewHolder::class.java
        )
        binding.recyclerView.adapter = adapter

        // 监听数据变化更新RecyclerView
        viewModel.recordList.observe(this) { records ->
            adapter.refresh(records)
        }

        // 监听编辑模式变化，更新所有ViewHolder的编辑状态
        viewModel.isEditMode.observe(this) { isEditMode ->
            val layoutManager = binding.recyclerView.layoutManager as? LinearLayoutManager
            layoutManager?.let {
                for (i in 0 until adapter.itemCount) {
                    val holder = binding.recyclerView.findViewHolderForAdapterPosition(i)
                            as? GjcCheckInRecordViewHolder
                    holder?.updateEditMode(isEditMode)
                    adapter.notifyItemChanged(i)
                }
            }
        }

        // 初始化数据
        viewModel.initOnCreated(intent)
    }

    companion object {
        @JvmStatic
        fun start(context: Context, bean: GjcWeighingRecordBean) {
            val starter = Intent(context, GjcWeighingRecordDetailsActivity::class.java)
                .putExtra(Constant.Key.BEAN, bean)
            context.startActivity(starter)
        }
    }
}
