package com.lukouguoji.gjc.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.databinding.ActivityIntExpStorageUseBinding
import com.lukouguoji.gjc.dialog.IntExpMoveClearDialogModel
import com.lukouguoji.gjc.dialog.IntExpModifyStorageDialogModel
import com.lukouguoji.gjc.dialog.IntExpInStorageDialogModel
import com.lukouguoji.gjc.viewModel.IntExpStorageUseViewModel
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.model.ConfirmDialogModel
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.DeviceUtil

/**
 * 国际出港-仓库
 */
@Route(path = ARouterConstants.ACTIVITY_URL_INT_EXP_STORAGE_USE)
class IntExpStorageUseActivity :
    BaseBindingActivity<ActivityIntExpStorageUseBinding, IntExpStorageUseViewModel>() {

    override fun layoutId() = R.layout.activity_int_exp_storage_use
    override fun viewModelClass() = IntExpStorageUseViewModel::class.java

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow(if (DeviceUtil.isPhone()) "出港仓库" else "国际出港仓库")
        binding.viewModel = viewModel
        binding.activity = this

        // 手机形态专属：筛选字典 + 未清仓/已清仓分项统计（平板不调用，行为零变化）
        if (DeviceUtil.isPhone()) viewModel.initPhoneExtras()

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

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

        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 ->
            // 过滤出选中的子列表项
            val selectedStorageList = maWb.storageUseList?.filter { it.isSelected } ?: emptyList()

            // 只添加有选中子列表项的主列表项
            if (selectedStorageList.isNotEmpty() || maWb.isSelected) {
                // 创建主列表项的副本，只包含选中的子列表
                maWb.copy(storageUseList = selectedStorageList)
            } else {
                null
            }
        }

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

        // 显示清仓对话框
        IntExpMoveClearDialogModel { 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]

        // 显示修改库位对话框
        IntExpModifyStorageDialogModel { 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 selectedStorageUseList = mutableListOf<com.lukouguoji.module_base.bean.GjcStorageUse>()
        allItems.forEach { maWb ->
            maWb.storageUseList?.filter { it.isSelected }?.let { selectedStorageUseList.addAll(it) }
        }

        // 校验：必须至少选中一个库位
        if (selectedStorageUseList.isEmpty()) {
            showToast("请选择要出库的库位")
            return
        }

        // 显示二次确认对话框
        ConfirmDialogModel(
            message = "确定要将选中的 ${selectedStorageUseList.size} 个库位执行出库操作吗？",
            title = "出库确认"
        ) {
            // 用户确认后，执行出库操作
            viewModel.performOutStorage(selectedStorageUseList)
        }.show(this)
    }

    // ==================== 5.5寸手机版：卡片级操作 ====================
    // 语义等价于「勾选该主单 + 其全部库位」再执行平板的批量操作，复用 performXxx 请求链路。

    /** 卡片「清仓」（已清仓的卡片按钮置灰，ViewHolder 已拦截） */
    fun cardClear(bean: com.lukouguoji.module_base.bean.GjcMaWb) {
        val maWbListForClear = listOf(bean.copy(storageUseList = bean.storageUseList ?: emptyList()))
        IntExpMoveClearDialogModel { dialog ->
            viewModel.performClear(dialog.clearNormal.value ?: "", maWbListForClear)
        }.show(this)
    }

    /** 卡片「修改库位」：弹层内先单选原库位（单库位时默认选中）再选新库位 */
    fun cardModifyStorage(bean: com.lukouguoji.module_base.bean.GjcMaWb) {
        val storageList = bean.storageUseList ?: emptyList()
        if (storageList.isEmpty()) {
            showToast("该运单暂无库位")
            return
        }
        IntExpModifyStorageDialogModel(sourceStorageList = storageList) { dialog ->
            val sourceStorage = dialog.selectedSourceStorage ?: return@IntExpModifyStorageDialogModel
            viewModel.performModifyStorage(dialog.locationName, dialog.locationId, sourceStorage)
        }.show(this)
    }

    /** 卡片「出库」：该运单全部库位出库（与平板勾选主单后出库同语义） */
    fun cardOutStorage(bean: com.lukouguoji.module_base.bean.GjcMaWb) {
        val storageList = bean.storageUseList ?: emptyList()
        if (storageList.isEmpty()) {
            showToast("该运单暂无库位")
            return
        }
        ConfirmDialogModel(
            message = "确定要将运单 ${bean.wbNo} 的 ${storageList.size} 个库位执行出库操作吗？",
            title = "出库确认"
        ) {
            viewModel.performOutStorage(storageList)
        }.show(this)
    }

    /** 卡片「入库」：弹层选库位后整票入库 */
    fun cardInStorage(bean: com.lukouguoji.module_base.bean.GjcMaWb) {
        val maWbListForInStorage = listOf(bean.copy(storageUseList = bean.storageUseList ?: emptyList()))
        IntExpInStorageDialogModel { dialog ->
            viewModel.performInStorage(dialog.locationName, dialog.locationId, maWbListForInStorage)
        }.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 ->
            // 过滤出选中的子列表项
            val selectedStorageList = maWb.storageUseList?.filter { it.isSelected } ?: emptyList()

            // 只添加有选中子列表项的主列表项
            if (selectedStorageList.isNotEmpty() || maWb.isSelected) {
                // 创建主列表项的副本，只包含选中的子列表
                maWb.copy(storageUseList = selectedStorageList)
            } else {
                null
            }
        }

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

        // 显示入库对话框
        IntExpInStorageDialogModel { 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()
        }
    }
}
