package com.lukouguoji.gjj.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.lukouguoji.module_base.model.ConfirmDialogModel
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.ActivityIntImpStorageUseBinding
import com.lukouguoji.gjj.dialog.IntImpMoveClearDialogModel
import com.lukouguoji.gjj.dialog.IntImpModifyStorageDialogModel
import com.lukouguoji.gjj.dialog.IntImpInStorageDialogModel
import com.lukouguoji.gjj.viewModel.IntImpStorageUseViewModel
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.commonAdapter
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.router.ARouterConstants

/**
 * 国际进港-仓库
 */
@Route(path = ARouterConstants.ACTIVITY_URL_GJJ_WARE_HOUSE)
class IntImpStorageUseActivity :
    BaseBindingActivity<ActivityIntImpStorageUseBinding, IntImpStorageUseViewModel>() {

    override fun layoutId() = R.layout.activity_int_imp_storage_use
    override fun viewModelClass() = IntImpStorageUseViewModel::class.java

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

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

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

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

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

    /**
     * 显示清仓操作对话框
     */
    fun showClearDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val allItems = list.filterIsInstance<com.lukouguoji.module_base.bean.GjcMaWb>()

        val maWbListForClear = allItems.mapNotNull { maWb ->
            if (maWb.isSelected) {
                // 勾选运单号 → 默认全选该运单号下的所有库位
                maWb.copy(storageUseList = maWb.storageUseList ?: emptyList())
            } else {
                // 勾选库位号 → 只对选择的库位进行操作
                val selectedStorageList = maWb.storageUseList?.filter { it.isSelected } ?: emptyList()
                if (selectedStorageList.isNotEmpty()) {
                    maWb.copy(storageUseList = selectedStorageList)
                } else {
                    null
                }
            }
        }

        if (maWbListForClear.isEmpty()) {
            showToast("请至少选择一个库位")
            return
        }

        IntImpMoveClearDialogModel { dialog ->
            val clearNormal = dialog.clearNormal.value ?: ""
            viewModel.performClear(clearNormal, maWbListForClear)
        }.show(this)
    }

    /**
     * 显示修改库位对话框
     */
    fun showModifyStorageDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val allItems = list.filterIsInstance<com.lukouguoji.module_base.bean.GjcMaWb>()

        val selectedStorageUseList = mutableListOf<com.lukouguoji.module_base.bean.GjcStorageUse>()
        allItems.forEach { maWb ->
            maWb.storageUseList?.filter { it.isSelected }?.let { selectedStorageUseList.addAll(it) }
        }

        when {
            selectedStorageUseList.isEmpty() -> {
                showToast("请选择要修改的库位")
                return
            }
            selectedStorageUseList.size > 1 -> {
                showToast("只能选择一个库位进行修改")
                return
            }
        }

        val selectedStorage = selectedStorageUseList[0]

        // 已出库的分单不允许修改库位
        if (!selectedStorage.outOpId.isNullOrEmpty() || !selectedStorage.outDate.isNullOrEmpty()) {
            showToast("该分单已出库，不允许修改库位")
            return
        }

        // 弹出库位选择弹框，选择后再调用接口，传入当前库位ID以预填充
        IntImpModifyStorageDialogModel(
            currentLocationId = selectedStorage.locationId?.toString() ?: ""
        ) { dialog ->
            val locationName = dialog.locationName
            val locationId = dialog.locationId
            viewModel.performModifyStorage(locationName, locationId, selectedStorage)
        }.show(this)
    }

    /**
     * 显示出库二次确认对话框
     */
    fun showOutStorageDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val allItems = list.filterIsInstance<com.lukouguoji.module_base.bean.GjcMaWb>()

        val selectedStorageList = mutableListOf<com.lukouguoji.module_base.bean.GjcStorageUse>()
        allItems.forEach { maWb ->
            maWb.storageUseList?.filter { it.isSelected }?.let { selectedStorageList.addAll(it) }
        }

        if (selectedStorageList.isEmpty()) {
            showToast("请选择要出库的库位")
            return
        }

        ConfirmDialogModel(
            message = "是否确认出库？",
            title = "出库确认"
        ) {
            viewModel.performOutStorage(selectedStorageList)
        }.show(this)
    }

    /**
     * 显示入库操作对话框
     */
    fun showInStorageDialog() {
        val list = viewModel.pageModel.rv?.commonAdapter()?.items as? List<*> ?: return
        val allItems = list.filterIsInstance<com.lukouguoji.module_base.bean.GjcMaWb>()

        val maWbListForInStorage = allItems.mapNotNull { maWb ->
            if (maWb.isSelected) {
                // 勾选运单号 → 默认全选该运单号下的所有库位
                maWb.copy(storageUseList = maWb.storageUseList ?: emptyList())
            } else {
                // 勾选库位号 → 只对选择的库位进行操作
                val selectedStorageList = maWb.storageUseList?.filter { it.isSelected } ?: emptyList()
                if (selectedStorageList.isNotEmpty()) {
                    maWb.copy(storageUseList = selectedStorageList)
                } else {
                    null
                }
            }
        }

        if (maWbListForInStorage.isEmpty()) {
            showToast("请至少选择一个单据")
            return
        }

        IntImpInStorageDialogModel { dialog ->
            val locationName = dialog.locationName
            val locationId = dialog.locationId
            viewModel.performInStorage(locationName, locationId, maWbListForInStorage)
        }.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.wbNo.value = data?.getStringExtra(Constant.Result.CODED_CONTENT)
            viewModel.searchClick()
        }
    }
}
