package com.lukouguoji.gjc.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
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.router.ARouterConstants

/**
 * 国际出港-仓库
 */
@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("国际出港仓库")
        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 ->
            // 过滤出选中的子列表项
            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
        }

        // 显示二次确认对话框
        AlertDialog.Builder(this)
            .setTitle("出库确认")
            .setMessage("确定要将选中的 ${selectedStorageUseList.size} 个库位执行出库操作吗？")
            .setPositiveButton("确定") { _, _ ->
                // 用户确认后，执行出库操作
                viewModel.performOutStorage(selectedStorageUseList)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 显示入库操作对话框
     */
    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()
        }
    }
}
