package com.lukouguoji.gjc.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.databinding.ActivityIntExpArriveBinding
import com.lukouguoji.gjc.viewModel.IntExpArriveViewModel
import com.lukouguoji.module_base.base.BaseBindingActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.impl.observe
import com.lukouguoji.module_base.ktx.addOnItemClickListener
import com.lukouguoji.module_base.router.ARouterConstants

/**
 * 国际出港-出港运抵页面
 */
@Route(path = ARouterConstants.ACTIVITY_URL_INT_EXP_ARRIVE)
class IntExpArriveActivity :
    BaseBindingActivity<ActivityIntExpArriveBinding, IntExpArriveViewModel>() {

    @JvmField
    @Autowired
    var wbNoParam: String? = null

    override fun layoutId() = R.layout.activity_int_exp_arrive
    override fun viewModelClass() = IntExpArriveViewModel::class.java

    override fun initOnCreate(savedInstanceState: Bundle?) {
        // 注入 ARouter 参数
        ARouter.getInstance().inject(this)

        setBackArrow("出港运抵")
        binding.viewModel = viewModel

        // 如果有传入运单号，自动填充并触发搜索
        if (!wbNoParam.isNullOrEmpty()) {
            viewModel.waybillNo.value = wbNoParam
            viewModel.searchClick()
        }

        // 观察全选状态，更新图标透明度
        viewModel.isAllChecked.observe(this) { isAllChecked ->
            binding.checkIcon.alpha = if (isAllChecked) 1.0f else 0.5f
        }

        // 绑定分页
        viewModel.pageModel.bindSmartRefreshLayout(binding.srl, binding.rv, viewModel, this)

        // 设置item点击监听
        binding.rv.addOnItemClickListener(viewModel)

        // 监听刷新事件
        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).observe(this) {
            viewModel.refresh()
        }

        // 初始加载数据（如果没有传入运单号，才执行初始加载）
        if (wbNoParam.isNullOrEmpty()) {
            viewModel.refresh()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            Constant.RequestCode.WAYBILL -> {
                if (resultCode == Activity.RESULT_OK) {
                    viewModel.waybillNo.value = data?.getStringExtra(Constant.Result.CODED_CONTENT)
                    viewModel.searchClick()
                }
            }
            Constant.RequestCode.CODE -> {
                if (resultCode == Activity.RESULT_OK) {
                    viewModel.hno.value = data?.getStringExtra(Constant.Result.CODED_CONTENT)
                    viewModel.searchClick()
                }
            }
        }
    }
}
