package com.lukouguoji.gjc.page.assemble

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.databinding.ActivityIntExpAssembleStartBinding
import com.lukouguoji.gjc.viewModel.IntExpAssembleStartViewModel
import com.lukouguoji.module_base.base.BaseBindingActivity
import com.lukouguoji.module_base.base.CommonAdapter
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.interfaces.IOnItemClickListener
import com.lukouguoji.module_base.ktx.addOnItemClickListener
import com.lukouguoji.module_base.ktx.setUpperCaseAlphanumericFilter
import com.lukouguoji.module_base.router.ARouterConstants

/**
 * 国际出港-开始组装页面
 */
@Route(path = ARouterConstants.ACTIVITY_URL_INT_EXP_ASSEMBLE_START)
class IntExpAssembleStartActivity :
    BaseBindingActivity<ActivityIntExpAssembleStartBinding, IntExpAssembleStartViewModel>(),
    IOnItemClickListener {

    private var assembleInfoAdapter: CommonAdapter? = null
    private var assemblePositionAdapter: CommonAdapter? = null
    private var waybillAdapter: CommonAdapter? = null

    companion object {
        private const val EXTRA_ULD_NO = "uld"
        private const val EXTRA_EDIT_MODE = "edit_mode"
        private const val EXTRA_LOAD_AREA = "load_area"

        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, IntExpAssembleStartActivity::class.java)
            context.startActivity(starter)
        }

        /**
         * 从列表页"修改"模式启动
         * @param uldNo ULD编号（将被锁定，整个页面生命周期内不可编辑）
         * @param loadArea 组装位置（用于自动选中对应的组装位置）
         */
        @JvmStatic
        fun startForEdit(context: Context, uldNo: String, loadArea: String) {
            val starter = Intent(context, IntExpAssembleStartActivity::class.java)
                .putExtra(EXTRA_ULD_NO, uldNo)
                .putExtra(EXTRA_EDIT_MODE, true)
                .putExtra(EXTRA_LOAD_AREA, loadArea)
            context.startActivity(starter)
        }
    }

    override fun layoutId() = R.layout.activity_int_exp_assemble_start

    override fun viewModelClass() = IntExpAssembleStartViewModel::class.java

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow("国际出港开始组装")
        binding.viewModel = viewModel

        // 为ULD编号添加大写字母和数字的输入限制
        binding.uldNoInput.et.setUpperCaseAlphanumericFilter()

        // 初始化列表
        initRecyclerViews()

        // 初始化加载待组装运单数据
        viewModel.loadInitialWaitingAssemble()

        // 加载组装位置数据（从API）
        viewModel.loadAssemblePosition()

        // 加载组装人列表
        viewModel.loadAssemblerList()

        // 监听登出事件，清空缓存
        FlowBus.with<Any>(ConstantEvent.LOGOUT).observe(this) {
            viewModel.clearCachedOperator()
        }

        // 观察数据变化
        observeData()

        // 处理修改模式（从列表页侧滑"修改"跳转）
        handleEditModeIntent()
    }

    /**
     * 处理修改模式的 Intent 参数
     */
    private fun handleEditModeIntent() {
        val isEditMode = intent.getBooleanExtra(EXTRA_EDIT_MODE, false)
        if (isEditMode) {
            val uldNo = intent.getStringExtra(EXTRA_ULD_NO) ?: ""
            val loadArea = intent.getStringExtra(EXTRA_LOAD_AREA) ?: ""
            if (uldNo.isNotEmpty()) {
                viewModel.initFromEditMode(uldNo, loadArea)
            }
        }
    }

    /**
     * 初始化RecyclerView
     */
    private fun initRecyclerViews() {
        // 左侧组装信息列表
        assembleInfoAdapter = CommonAdapter(
            this,
            viewModel.assembleInfoLayoutId,
            viewModel.assembleInfoViewHolder
        )
        binding.rvAssembleInfo.layoutManager = LinearLayoutManager(this)
        binding.rvAssembleInfo.adapter = assembleInfoAdapter
        // 添加点击监听器
        binding.rvAssembleInfo.addOnItemClickListener(this)

        // 左侧组装位置列表
        assemblePositionAdapter = CommonAdapter(
            this,
            viewModel.assemblePositionLayoutId,
            viewModel.assemblePositionViewHolder
        )
        binding.rvAssemblePosition.layoutManager = LinearLayoutManager(this)
        binding.rvAssemblePosition.adapter = assemblePositionAdapter
        // 添加点击监听器
        binding.rvAssemblePosition.addOnItemClickListener(this)

        // 右侧运单列表
        waybillAdapter = CommonAdapter(
            this,
            viewModel.waybillLayoutId,
            viewModel.waybillViewHolder
        )
        binding.rvWaybillList.layoutManager = LinearLayoutManager(this)
        binding.rvWaybillList.adapter = waybillAdapter
        // 添加点击监听器
        binding.rvWaybillList.addOnItemClickListener(this)
    }

    /**
     * 观察数据变化
     */
    private fun observeData() {
        viewModel.assembleInfoList.observe(this) { list ->
            assembleInfoAdapter?.refresh(list)
        }

        viewModel.assemblePositionList.observe(this) { list ->
            assemblePositionAdapter?.refresh(list)
        }

        viewModel.waybillList.observe(this) { list ->
            waybillAdapter?.refresh(list)
        }
    }

    /**
     * 列表项点击事件
     */
    override fun onItemClick(position: Int, type: Int) {
        when (type) {
            0 -> viewModel.onPositionItemClick(position)       // 组装位置点击
            1 -> viewModel.onWaybillItemClick(position)        // 运单列表点击
            2 -> viewModel.onAssembleInfoItemClick(position)   // 组装信息列表点击
            else -> {}
        }
    }

    /**
     * 处理扫码结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == Constant.RequestCode.WAYBILL && resultCode == Activity.RESULT_OK) {
            // 获取扫码结果
            val codedContent = data?.getStringExtra(Constant.Result.CODED_CONTENT)

            // 更新搜索框内容
            viewModel.searchText.value = codedContent

            // 自动触发查询
            viewModel.loadWaitingAssembleWaybills()
        }
    }
}
