package com.lukouguoji.gjj.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.ActivityIntImpLoadingListBinding
import com.lukouguoji.gjj.dialog.IntImpInStorageDialogModel
import com.lukouguoji.gjj.dialog.IntImpModifyStorageDialogModel
import com.lukouguoji.gjj.viewModel.IntImpLoadingListViewModel
import com.lukouguoji.module_base.base.BaseBindingActivity
import com.lukouguoji.module_base.bean.GjjManifest
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.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.router.ARouterConstants

/**
 * 国际进港-装机单页面（分拣理货）
 */
@Route(path = ARouterConstants.ACTIVITY_URL_INT_IMP_LOADING_LIST)
class IntImpLoadingListActivity :
    BaseBindingActivity<ActivityIntImpLoadingListBinding, IntImpLoadingListViewModel>() {

    override fun layoutId() = R.layout.activity_int_imp_loading_list
    override fun viewModelClass() = IntImpLoadingListViewModel::class.java

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow("国际进港装机单")
        binding.viewModel = viewModel
        binding.activity = this

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

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

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

        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).observe(this) {
            viewModel.refresh()
        }

        // 设置运单号自动查询的额外参数（FID、FDGP）
        binding.pslWaybillNo.autoQueryConfig.extraParamsProvider = {
            mapOf(
                "fid" to viewModel.fid,
                "fdep" to viewModel.fdep
            )
        }

        // 接收从进港舱单传递的参数（FID和FDGP用于查询，fdate/fno/fdest用于界面显示）
        intent.getStringExtra("fid")?.let { if (it.isNotEmpty()) viewModel.fid = it }
        intent.getStringExtra("fdep")?.let { if (it.isNotEmpty()) viewModel.fdep = it }
        intent.getStringExtra("fdate")?.let { if (it.isNotEmpty()) viewModel.flightDate.value = it }
        intent.getStringExtra("fno")?.let { if (it.isNotEmpty()) viewModel.flightNo.value = it }
        intent.getStringExtra("fdest")?.let { if (it.isNotEmpty()) viewModel.fdest.value = it }

        // 如果收到了航班号和日期参数，触发航班查询来构建始发站下拉列表
        val fdate = intent.getStringExtra("fdate")
        val fno = intent.getStringExtra("fno")
        if (!fdate.isNullOrEmpty() && !fno.isNullOrEmpty()) {
            viewModel.onFlightNoInputComplete()
        }

        // 初始加载数据
        viewModel.refresh()
    }

    /**
     * 显示入库操作对话框
     */
    fun showInStorageDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val selectedItems = list.filterIsInstance<GjjManifest>().filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要入库的记录")
            return
        }

        IntImpInStorageDialogModel { dialog ->
            val locationName = dialog.locationName
            val locationId = dialog.locationId
            viewModel.performInStorage(locationName, locationId, selectedItems)
        }.show(this)
    }

    /**
     * 显示修改库位对话框
     */
    fun showModifyStorageDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val selectedItems = list.filterIsInstance<GjjManifest>().filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要修改库位的记录")
            return
        }

        // 单选时自动带出该项的库位号，多选不带出
        val presetLocation = if (selectedItems.size == 1) selectedItems.first().locationTally ?: "" else ""

        IntImpModifyStorageDialogModel(
            currentLocationName = presetLocation
        ) { dialog ->
            val locationName = dialog.locationName
            val locationId = dialog.locationId
            viewModel.performModifyStorage(locationName, locationId, selectedItems)
        }.show(this)
    }

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