package com.lukouguoji.gjj.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.ActivityIntImpQueryBinding
import com.lukouguoji.gjj.viewModel.IntImpQueryViewModel
import com.lukouguoji.module_base.base.BaseBindingActivity
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.getLifecycleOwner
import com.lukouguoji.module_base.ktx.setUpperCaseAlphanumericFilter
import com.lukouguoji.module_base.ktx.setUpperCaseLetterFilter
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.DeviceUtil

/**
 * 国际进港查询列表页
 */
@Route(path = ARouterConstants.ACTIVITY_URL_GJJ_QUERY_LIST)
class IntImpQueryActivity :
    BaseBindingActivity<ActivityIntImpQueryBinding, IntImpQueryViewModel>() {

    override fun layoutId() = R.layout.activity_int_imp_query

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

    override fun initOnCreate(savedInstanceState: Bundle?) {
        setBackArrow(if (DeviceUtil.isPhone()) "进港查询" else "国际进港查询")

        binding.viewModel = viewModel

        viewModel.pageModel
            .bindSmartRefreshLayout(binding.srl, binding.rv, viewModel, getLifecycleOwner())

        // 注册列表项点击事件
        binding.rv.addOnItemClickListener(viewModel)

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

        viewModel.initAgentList()
        viewModel.initSpecialCodeList()
        viewModel.initFilterLists()

        // 平板变体才有侧滑筛选面板（filter_panel/filter_overlay 手机变体不存在，Binding 字段为 null）
        val padFilterPanel = binding.filterPanel
        if (padFilterPanel != null) {
            // 观察筛选面板显示状态（滑入/滑出动画）
            viewModel.filterVisible.observe(this) { visible ->
                if (visible) showFilterPanel() else hideFilterPanel()
            }

            // 航班号：大写字母+数字
            padFilterPanel.filterFlightNo.et.setUpperCaseAlphanumericFilter()
            // 始发港：仅大写字母
            padFilterPanel.filterOrigin.et.setUpperCaseLetterFilter()
        } else {
            // 手机变体：PhoneFilterPanel 的显隐由 XML 直接绑定 viewModel.filterVisible，无需动画代码
            binding.phoneFilterFlightNo?.et?.setUpperCaseAlphanumericFilter()
            binding.phoneFilterOrigin?.et?.setUpperCaseLetterFilter()
        }

        // 手机形态专属：已入库/已出库统计计数
        if (DeviceUtil.isPhone()) {
            viewModel.initPhoneExtras()
        }

        viewModel.refresh()
    }

    private fun showFilterPanel() {
        val panel = binding.filterPanel?.root ?: return
        val overlay = binding.filterOverlay ?: return
        val panelWidth = window.decorView.width / 3

        panel.layoutParams = (panel.layoutParams as FrameLayout.LayoutParams).apply {
            width = panelWidth
            gravity = Gravity.END
        }

        // 先 INVISIBLE 完成测量，避免第一次显示时闪烁
        panel.visibility = View.INVISIBLE
        panel.translationX = panelWidth.toFloat()
        overlay.visibility = View.VISIBLE
        overlay.alpha = 0f

        panel.post {
            panel.visibility = View.VISIBLE
            panel.animate().translationX(0f).setDuration(250).start()
            overlay.animate().alpha(1f).setDuration(250).start()
        }
    }

    private fun hideFilterPanel() {
        val panel = binding.filterPanel?.root ?: return
        val overlay = binding.filterOverlay ?: return

        if (panel.visibility != View.VISIBLE) return

        panel.animate()
            .translationX(panel.width.toFloat())
            .setDuration(250)
            .withEndAction { panel.visibility = View.GONE }
            .start()

        overlay.animate()
            .alpha(0f)
            .setDuration(250)
            .withEndAction { overlay.visibility = View.GONE }
            .start()
    }

    override fun onBackPressed() {
        if (viewModel.filterVisible.value == true) {
            viewModel.closeFilter()
        } else {
            super.onBackPressed()
        }
    }

    companion object {
        @JvmStatic
        fun start(context: Context) {
            context.startActivity(Intent(context, IntImpQueryActivity::class.java))
        }
    }
}
