package com.lukouguoji.aerologic.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.aerologic.R
import com.lukouguoji.aerologic.page.accident.visa.list.AccidentVisaListActivity
import com.lukouguoji.aerologic.page.car.list.CarListActivity
import com.lukouguoji.aerologic.page.flight.query.list.FlightQueryListActivity
import com.lukouguoji.aerologic.page.gnj.jiaojie.GnjHandoverListActivity
import com.lukouguoji.aerologic.page.gnj.manifest.list.GnjManifestListActivity
import com.lukouguoji.aerologic.page.gnj.move.stash.list.GnjMoveStashListActivity
import com.lukouguoji.aerologic.page.gnj.query.list.GnjQueryListActivity
import com.lukouguoji.aerologic.page.gnj.stash.list.GnjStashListActivity
import com.lukouguoji.aerologic.page.gnj.unload.list.GnjUnloadListActivity
import com.lukouguoji.aerologic.page.log.list.LogListActivity
import com.lukouguoji.aerologic.page.log.list.LogQueryActivity
import com.lukouguoji.aerologic.page.message.list.MessageListActivity
import com.lukouguoji.aerologic.page.telegram.list.TelegramListActivity
import com.lukouguoji.aerologic.page.test.PrintActivity
import com.lukouguoji.aerologic.page.transport.GoodsTransportActivity
import com.lukouguoji.aerologic.page.transportLog.list.TransportLogActivity
import com.lukouguoji.aerologic.page.coldStorage.list.ColdStorageActivity
import com.lukouguoji.aerologic.page.uld.list.UldListActivity
import com.lukouguoji.gnc.page.deposit.list.GncDepositListActivity
import com.lukouguoji.gnc.page.distribution.home.GncDistributionHomeActivity
import com.lukouguoji.gnc.page.fubang.list.GncFuBangListActivity
import com.lukouguoji.gnc.page.shouyun.unlist.GncShouYunUnListActivity
import com.lukouguoji.gnj.activity.GnjChuKuListActivity
import com.lukouguoji.module_base.MyApplication
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.router.ARouterConstants
import kotlin.properties.Delegates


class HomeFragment : Fragment() {

    private val TAG: String = HomeFragment::class.java.simpleName

    /**
     * ========== 开发调试开关 ==========
     * TODO: 正式发布前务必设置为 false
     */
    companion object {
        private const val DEV_AUTO_SELECT_MENU = false  // 开发调试：自动选择菜单开关，正式发布前设为 false
        private const val DEV_AUTO_SELECT_MENU_ID = Constant.AuthName.IntImp  // 自动选择的目标菜单
    }

    private var rvLeft: RecyclerView by Delegates.notNull()
    private var rvRight: RecyclerView by Delegates.notNull()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val inflate = inflater.inflate(R.layout.fragment_home, container, false)
        rvLeft = inflate.findViewById(R.id.left_menu_list)
        rvRight = inflate.findViewById(R.id.right_menu_list)
        return inflate
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val leftMenuList = initLeftMenuData()
        rvLeft.adapter = HomeLeftAdapt(leftMenuList)
        // 权限过滤后列表可能为空（账号无任何菜单权限），避免 first() 抛异常
        val firstMenuId = leftMenuList.firstOrNull()?.id
        rvRight.adapter = HomeRightAdapt(
            if (firstMenuId != null) getRightMenu4Id(firstMenuId) else emptyList()
        )

        // ========== 开发调试：自动选择指定菜单 ==========
        autoSelectMenuForDev()
    }

    ///////////  左边的list循环
    inner class HomeLeftAdapt(private val leftMenuList: List<LeftMenu>) :
        RecyclerView.Adapter<HomeLeftAdapt.ViewHolder>() {

        private var mPosition = 0

        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val itemLayout: LinearLayout = view.findViewById(R.id.left_item_layout)
            val itemImg: ImageView = view.findViewById(R.id.left_item_img)
            val itemText: TextView = view.findViewById(R.id.left_item_text)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.home_left_item, parent, false)
            val viewHolder = ViewHolder(view)
            val leftMenu = leftMenuList[mPosition]
            viewHolder.itemView.setOnClickListener {
                val oldPosition = mPosition
                mPosition = viewHolder.adapterPosition
                val leftMenuTemp = leftMenuList[mPosition]

                //航班查询
                if (Constant.AuthName.Flight == leftMenuTemp.id) {
//                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_HANG_BAN_QUERY)
//                        .navigation(activity, Constant.RequestCode.home_left_hang_ban_query)
//                    FlightQueryListActivity.start(requireContext()) // 已废弃
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_HB_QUERY_LIST)
                        .navigation()
                    mPosition = oldPosition
                }
                //货物查询
                if (Constant.AuthName.CargoStatus == leftMenuTemp.id) {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_CARGO_TRACKING)
                        .navigation(activity, Constant.RequestCode.home_left_hang_ban_query)
                    mPosition = oldPosition
                }
                //其他查询
                else {
                }
                refreshRight(leftMenuList[mPosition].id)

                //更新菜单状态
                notifyDataSetChanged()
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            var item = leftMenuList[position]
            holder.itemText.text = item.text
            holder.itemImg.setImageResource(item.img)
            if (mPosition == position) {
                holder.itemLayout.setBackgroundResource(R.color.white)
                holder.itemImg.drawable.setTint(
                    MyApplication.context.resources.getColor(
                        R.color.colorPrimary,
                        activity?.theme
                    )
                )
                holder.itemText.setTextColor(
                    MyApplication.context.resources.getColor(
                        R.color.colorPrimary,
                        activity?.theme
                    )
                )
            } else {
                holder.itemLayout.setBackgroundResource(R.color.list_bg)
                holder.itemImg.drawable.setTint(
                    MyApplication.context.resources.getColor(
                        R.color.weak_grey,
                        activity?.theme
                    )
                )
                holder.itemText.setTextColor(
                    MyApplication.context.resources.getColor(
                        R.color.weak_grey,
                        activity?.theme
                    )
                )
            }

        }

        override fun getItemCount() = leftMenuList.size

        /**
         * 开发调试：模拟点击菜单项
         * TODO: 正式发布前删除此方法
         */
        fun simulateClick(position: Int) {
            if (position < 0 || position >= leftMenuList.size) return

            val leftMenuTemp = leftMenuList[position]

            // 跳过特殊菜单（航班查询、货物查询）
            if (Constant.AuthName.Flight == leftMenuTemp.id ||
                Constant.AuthName.CargoStatus == leftMenuTemp.id
            ) {
                return
            }

            // 更新选中位置
            mPosition = position

            // 刷新右侧菜单
            refreshRight(leftMenuList[mPosition].id)

            // 更新菜单状态
            notifyDataSetChanged()
        }
    }

    inner class LeftMenu(val id: String, val img: Int, val text: String)

    fun initLeftMenuData(): List<LeftMenu> {
        val list = arrayListOf<LeftMenu>()
        list.add(LeftMenu(Constant.AuthName.DomExp, R.mipmap.gncn_icon, "国内出港"))
        list.add(LeftMenu(Constant.AuthName.DomImp, R.mipmap.gnjg, "国内进港"))
        list.add(LeftMenu(Constant.AuthName.IntExp, R.mipmap.gjcn_icon, "国际出港"))
        list.add(LeftMenu(Constant.AuthName.IntImp, R.mipmap.gjjn_icon, "国际进港"))
        list.add(LeftMenu(Constant.AuthName.Flight, R.mipmap.hangban_icon, "航班查询"))
        list.add(LeftMenu(Constant.AuthName.CargoStatus, R.mipmap.huowu_icon, "货物追踪"))
        list.add(LeftMenu(Constant.AuthName.Supervision, R.mipmap.monitor_up_down_icon, "监装监卸"))

        list.add(LeftMenu(Constant.AuthName.Comprehensive, R.mipmap.zhgl_icon, "综合管理"))

        /**
         * 左侧菜单 权限过滤：仅保留接口下发、且含有二级权限的主菜单
         * auths 结构：{ 主菜单ID: [二级权限串, ...], ... }
         */
        getAuthsObj()?.let { authsObj ->
            return list.filter { m ->
                val arr = authsObj.getJSONArray(m.id)
                arr != null && arr.size > 0
            }
        }
        return list
    }

    private fun getAuthsObj(): JSONObject? {
        val authsString = SharedPreferenceUtil.getString(Constant.Share.authList)
        if (authsString != "") {
            val authsObj = JSON.parseObject(authsString)
            return authsObj
        }
        return null
    }


    ///////////  右边的list循环
    inner class HomeRightAdapt(rightMenuList: List<RightMenu>) :
        RecyclerView.Adapter<HomeRightAdapt.ViewHolder>() {

        private var rightMenuList = arrayListOf<RightMenu>().apply {
            addAll(rightMenuList)
        }

        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val itemImg: ImageView = view.findViewById(R.id.right_item_img)
            val itemText: TextView = view.findViewById(R.id.right_item_text)
        }

        /**
         * 刷新
         */
        fun refresh(list: List<RightMenu>) {
            rightMenuList.clear()
            rightMenuList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.home_right_item, parent, false)
            val viewHolder = ViewHolder(view)

            viewHolder.itemView.setOnClickListener {

                val position = viewHolder.adapterPosition
                var rightMenu = rightMenuList[position]
                when (rightMenu.id) {
                    //// 国内出港
                    Constant.AuthName.AppDomExpCheckin -> {
                        GncShouYunUnListActivity.start(requireContext())
                    }

                    Constant.AuthName.AppDomExpWeighting -> {
                        GncFuBangListActivity.start(requireContext())
                    }

                    Constant.AuthName.AppDomExpTransport -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_GOUT_TRANSFER_ACTIVITY)
                            .navigation()
                    }

                    Constant.AuthName.AppDomExpWareHouse -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNC_WAREHOUSE)
                            .navigation()
                    }

                    Constant.AuthName.AppDomExpSearch -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNC_QUERY_LIST)
                            .navigation()
                    }

                    Constant.AuthName.AppTest -> {
                        PrintActivity.start(requireContext())
                    }

                    Constant.AuthName.AppDomExpAssemble -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNC_ASSEMBLE_LIST)
                            .navigation()
                    }

                    Constant.AuthName.AppDomExpDistribution -> {
                        GncDistributionHomeActivity.start(requireContext())
                    }

                    Constant.AuthName.AppDomExpDeposit -> {
                        GncDepositListActivity.start(requireContext())
                    }

                    /**
                     * 国内进港
                     */
                    //舱单
                    Constant.AuthName.GnjAppDomExpCheckin -> {
                        GnjManifestListActivity.start(requireContext())
                    }
                    //出库
                    Constant.AuthName.GnjChuKuList -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNJ_CHU_KU_LIST)
                            .navigation()
                    }
                    //仓库管理
                    Constant.AuthName.GnjWareHouse -> {
                        GnjStashListActivity.start(requireContext())
                    }
                    //查询 列表
                    Constant.AuthName.GnjQueryList -> {
                        GnjQueryListActivity.start(requireContext())
                    }
                    //入库
                    Constant.AuthName.GnjRuKu -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNJ_RU_KU)
                            .navigation()
                    }
                    //移库
                    Constant.AuthName.GnjYiKu -> {
                        GnjMoveStashListActivity.start(requireContext())
                    }

                    Constant.AuthName.GnjHandover -> {
                        GnjHandoverListActivity.start(requireContext())
                    }
                    /**
                     * 国际出港
                     */
                    //收运
                    Constant.AuthName.GjcAppDomExpCheckin -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_RECEIVE_LIST)
                            .navigation()
                    }
                    //复磅（板箱过磅）
                    Constant.AuthName.GjcFuBangActivity -> {
                        // TODO: 2025-11-21 旧版跳转，已改为新的列表页面
                        // ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_FU_BANG)
                        //     .navigation()

                        // 新版板箱过磅列表页面
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_BOX_WEIGHING)
                            .navigation()
                    }
                    //出港计重
                    Constant.AuthName.GjcCheckWeighing -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_WEIGHING_LIST)
                            .navigation()
                    }
                    //仓库
                    Constant.AuthName.GjcWareHouseActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_WARE_HOUSE)
                            .navigation()
                    }
                    //查询
                    Constant.AuthName.GjcQueryListActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_QUERY_LIST)
                            .navigation()
                    }
                    //移库
                    Constant.AuthName.GjcYiKuListActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_EXP_MOVE)
                            .navigation()
                    }
                    // 板箱
                    Constant.AuthName.GjcBanXListActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_BOX_ASSEMBLE)
                            .navigation()
                    }
                    // 货物交接
                    Constant.AuthName.GjcGoodsListActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_GOODS_LIST)
                            .navigation()
                    }
                    // 收运检查
                    Constant.AuthName.GjcInspectionActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJC_INSPECTION)
                            .navigation()
                    }
                    // 出港组装
                    Constant.AuthName.GjcIntExpAssembleActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_EXP_ASSEMBLE)
                            .navigation()
                    }
                    // 组装分配
                    Constant.AuthName.GjcAssembleAllocateActivity -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_GJC_ASSEMBLE_ALLOCATE)
                            .navigation()
                    }
                    // 出库交接
                    Constant.AuthName.GjcIntExpOutHandover -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_EXP_OUT_HANDOVER)
                            .navigation()
                    }
                    // 出港装载
                    Constant.AuthName.GjcIntExpLoad -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_EXP_LOAD)
                            .navigation()
                    }
                    // 出港理货
                    Constant.AuthName.GjcIntExpTally -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_EXP_TALLY)
                            .navigation()
                    }
                    // 出港运抵
                    Constant.AuthName.GjcIntExpArrive -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_EXP_ARRIVE)
                            .navigation()
                    }
                    // 出港仓库
                    Constant.AuthName.GjcIntExpStorageUse -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_EXP_STORAGE_USE)
                            .navigation()
                    }
                    /**
                     * 国际进港
                     */
                    // 电报解析（电报生成）
                    Constant.AuthName.IntImpMsgParseActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_IMP_MSG_PARSE)
                            .navigation()
                    }
                    // 原始舱单
                    Constant.AuthName.IntArrAirManifest -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_ARR_AIR_MANIFEST)
                            .navigation()
                    }
                    // 进港舱单
                    Constant.AuthName.IntImpManifest -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_IMP_MANIFEST)
                            .navigation()
                    }

                    // 理货报告
                    Constant.AuthName.IntImpTally -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_IMP_TALLY)
                            .navigation()
                    }

                    // 进港仓库
                    Constant.AuthName.GjjWareHouseActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJJ_WARE_HOUSE)
                            .navigation()
                    }

                    // 提取记录
                    Constant.AuthName.IntImpPickUpRecord -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_IMP_PICK_UP_RECORD)
                            .navigation()
                    }

                    // 提取出库
                    Constant.AuthName.IntImpPickUpDLV -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_INT_IMP_PICK_UP_DLV)
                            .navigation()
                    }

                    // 进港查询
                    Constant.AuthName.GjjQueryListActivity -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GJJ_QUERY_LIST)
                            .navigation()
                    }

                    // 事故签证
                    Constant.AuthName.IntImpAccidentVisa -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_INT_IMP_ACCIDENT_VISA)
                            .navigation()
                    }

                    /**
                     * 航班查询
                     */
                    //航班查询
                    Constant.AuthName.HangBanQuery -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_HANG_BAN_QUERY)
                            .navigation()
                    }
                    /**
                     * 货物追踪
                     */
                    //货物追踪
                    Constant.AuthName.CargoTracking -> {
                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_CARGO_TRACKING)
                            .navigation()
                    }
                    /**
                     * 监装监卸
                     */
                    //进港卸机
                    Constant.AuthName.MonitorInPack -> {
//                        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MONITOR_IN_PACK)
//                            .navigation()
                        GnjUnloadListActivity.start(requireContext())
                    }
                    //事故签证
                    Constant.AuthName.AccidentVisa -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_MONITOR_ACCIDENT_VISA).navigation()
                    }
                    //出港装板
                    Constant.AuthName.OutLoadingActivity -> {
                        ARouter.getInstance()
                            .build(ARouterConstants.ACTIVITY_URL_MONITOR_OUT_LOADING).navigation()
                    }
                    /**
                     * 综合管理
                     */
                    // 消息管理
                    Constant.AuthName.ComprehensiveMessage -> {
                        MessageListActivity.start(requireContext())
                    }
                    // 电报管理
                    Constant.AuthName.ComprehensiveTelegram -> {
                        TelegramListActivity.start(requireContext())
                    }
                    // 货物转运
                    Constant.AuthName.ComprehensiveTransfer -> {
                        GoodsTransportActivity.start(requireContext())
                    }
                    // 事故签证
                    Constant.AuthName.ComprehensiveAccidentVisa -> {
                        AccidentVisaListActivity.start(requireContext())
                    }
                    // 平板车管理
                    Constant.AuthName.ComprehensiveCar -> {
                        CarListActivity.start(requireContext())
                    }
                    // 转运记录
                    Constant.AuthName.TransportLog -> {
                        TransportLogActivity.start(requireContext())
                    }
                    // 日志查询
                    Constant.AuthName.ComprehensiveLog -> {
                        LogQueryActivity.start(requireContext())
                    }
                    // ULD管理
                    Constant.AuthName.ComprehensiveUld -> {
                        UldListActivity.start(requireContext())
                    }
                    // 冷库登记
                    Constant.AuthName.ComprehensiveColdStorage -> {
                        ColdStorageActivity.start(requireContext())
                    }

                    else -> {
                        Toast.makeText(
                            parent.context,
                            "暂无入口，等待后期开放...",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }


            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = rightMenuList[position]
            holder.itemText.text = item.text
            // 直接设置本地资源，避免 Glide 缓存导致的图标错乱问题
            holder.itemImg.setImageResource(item.img)
        }

        override fun getItemCount() = rightMenuList.size
    }

    inner class RightMenu(val id: String, val img: Int, val text: String)

    private fun getRightMenu4Id(id: String): List<RightMenu> {
        val list = arrayListOf<RightMenu>()
        when (id) {
            Constant.AuthName.DomExp -> {
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpCheckin,
                        com.lukouguoji.module_base.R.drawable.img_gnc_shouyun,
                        "出港收运"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpWeighting,
                        R.mipmap.gnc_fubang,
                        "出港复磅"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpAssemble,
                        com.lukouguoji.module_base.R.drawable.img_gnc_zuzhuang,
                        "出港组装"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpDistribution,
                        com.lukouguoji.module_base.R.drawable.img_gnc_fenpei,
                        "出港分配"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpDeposit,
                        com.lukouguoji.module_base.R.drawable.img_gnc_cunfang,
                        "出港存放"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AppDomExpWareHouse,
                        R.mipmap.gnc_cangku,
                        "仓库管理"
                    )
                )
                list.add(RightMenu(Constant.AuthName.AppDomExpSearch, R.mipmap.gnc_cha, "出港查询"))
                list.add(RightMenu(Constant.AuthName.AppTest, R.mipmap.gnc_cha, "测试页"))
            }

            Constant.AuthName.DomImp -> {
                list.add(
                    RightMenu(
                        Constant.AuthName.GnjAppDomExpCheckin,
                        R.mipmap.gnj_cang_dan_icon,
                        "进港舱单"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.GnjChuKuList,
                        R.mipmap.gnj_chu_ku_icon,
                        "进港出库"
                    )
                )
                list.add(RightMenu(Constant.AuthName.GnjYiKu, R.mipmap.gnj_yi_ku_icon, "进港移库"))
                list.add(
                    RightMenu(
                        Constant.AuthName.GnjWareHouse,
                        R.mipmap.gnj_cang_ku_icon,
                        "仓库管理"
                    )
                )
//                list.add(RightMenu(Constant.AuthName.GnjRuKu, R.mipmap.gnc_zhuanyun, "转运确认"))
                list.add(
                    RightMenu(
                        Constant.AuthName.GnjQueryList,
                        R.mipmap.gnj_query_icon,
                        "进港查询"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.GnjHandover,
                        R.mipmap.gnj_handover,
                        "进港交接"
                    )
                )

            }

            Constant.AuthName.IntExp -> {
                // 1. 收运检查
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcInspectionActivity,
                        R.drawable.img_gjc_shouyunjiancha,
                        "收运检查"
                    )
                )

                // 2. 出港计重
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcCheckWeighing,
                        R.drawable.img_gjc_chugangjizhong,
                        "出港计重"
                    )
                )

                // 3. 出港运抵
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpArrive,
                        R.drawable.img_gjc_chugang_diyun,
                        "出港运抵"
                    )
                )

                // 4. 组装分配
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcAssembleAllocateActivity,
                        R.drawable.img_gjc_zuzhuangfenpei,
                        "组装分配"
                    )
                )

                // 5. 出港组装
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpAssembleActivity,
                        R.drawable.img_gjc_banxiangzuzhuang,
                        "出港组装"
                    )
                )

                // 6. 板箱过磅
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcFuBangActivity,
                        R.drawable.img_gjc_banxiangguobang,
                        "板箱过磅"
                    )
                )

                // 7. 出港装载
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpLoad,
                        R.drawable.img_gjc_chugang_zhuangzai,
                        "出港装载"
                    )
                )

                // 8. 出港理货
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpTally,
                        R.drawable.img_gjc_chugang_lihuo,
                        "出港理货"
                    )
                )

                // 9. 出库交接
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpOutHandover,
                        R.drawable.img_gjc_chuku_jiaojie,
                        "出库交接"
                    )
                )

                // 10. 出港移库
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcYiKuListActivity,
                        R.drawable.gjc_yi_ku_icon,
                        "出港移库"
                    )
                )

                // 11. 出港仓库
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcIntExpStorageUse,
                        R.drawable.gjc_cang_ku_icon,
                        "出港仓库"
                    )
                )

                // 12. 出港查询
                list.add(
                    RightMenu(
                        Constant.AuthName.GjcQueryListActivity,
                        R.drawable.gjc_query_icon,
                        "出港查询"
                    )
                )

//                list.add(
//                    RightMenu(
//                        Constant.AuthName.GjcWareHouseActivity,
//                        R.mipmap.gjc_cang_ku_icon,
//                        "仓库管理"
//                    )
//                )


//                list.add(
//                    RightMenu(
//                        Constant.AuthName.GjcBanXListActivity,
//                        com.lukouguoji.module_base.R.drawable.img_gjc_banxiangzuzhuang,
//                        "板箱组装"
//                    )
//                )

//                list.add(
//                    RightMenu(
//                        Constant.AuthName.GjcGoodsListActivity,
//                        R.mipmap.img_hwjj,
//                        "货物交接"
//                    )
//                )
            }

            Constant.AuthName.IntImp -> {
                // 国际进港菜单 - 新版
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpMsgParseActivity,
                        R.mipmap.img_bwjx,
                        "电报解析"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpManifest,
                        R.mipmap.gjj_jin_gang_cang_dan_icon,
                        "进港舱单"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntArrAirManifest,
                        R.mipmap.gjj_yuan_shi_cang_dan_icon,
                        "原始舱单"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpTally,
                        R.mipmap.gjj_li_huo_bao_gao_icon,
                        "理货报告"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.GjjWareHouseActivity,
                        R.drawable.gjc_cang_ku_icon,
                        "进港仓库"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpPickUpRecord,
                        R.mipmap.gjj_ti_qu_ji_lu_icon,
                        "提取记录"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpPickUpDLV,
                        R.mipmap.gjj_chu_ku_icon,
                        "提取出库"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.GjjQueryListActivity,
                        R.mipmap.gjj_query_icon,
                        "进港查询"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.IntImpAccidentVisa,
                        R.drawable.gjj_jgqz,
                        "事故签证"
                    )
                )
            }

            Constant.AuthName.Flight -> {
//                list.add(RightMenu(Constant.AuthName.HangBanQuery, R.mipmap.guoji_in, "航班查询"))
            }

            Constant.AuthName.CargoStatus -> {
//                list.add(RightMenu(Constant.AuthName.CargoTracking, R.mipmap.guoji_in, "货物状态查询"))
            }

            Constant.AuthName.Supervision -> {
                list.add(
                    RightMenu(
                        Constant.AuthName.MonitorInPack,
                        R.mipmap.mit_in_pack,
                        "进港卸机"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.AccidentVisa,
                        R.drawable.img_gj_shiguqianzheng,
                        "事故签证"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveAccidentVisa,
                        R.mipmap.mit_accident_visa,
                        "事故签证"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.OutLoadingActivity,
                        R.mipmap.mit_out_pack,
                        "出港装板"
                    )
                )
            }

            Constant.AuthName.Comprehensive -> {
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveMessage,
                        com.lukouguoji.module_base.R.drawable.img_xiaoxiguanli,
                        "消息管理"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveTelegram,
                        com.lukouguoji.module_base.R.drawable.img_gnc_dianbaoguanli,
                        "电报管理"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveTransfer,
                        com.lukouguoji.module_base.R.drawable.img_gnc_huowuzhuanyun,
                        "货物转运"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveCar,
                        com.lukouguoji.module_base.R.drawable.img_pingbancheguanli,
                        "平板车管理"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveLog,
                        R.mipmap.gnc_shou,
                        "日志查询"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.TransportLog,
                        R.mipmap.transport_log,
                        "转运记录"
                    )
                )
                list.add(
                    RightMenu(
                        Constant.AuthName.ComprehensiveUld,
                        R.mipmap.cargo,
                        "ULD管理"
                    )
                )
            }

            else -> {
                Log.e(TAG, "没有找到对应 $id 的右侧功能列表 ")
            }
        }

        /**
         * 右侧菜单 权限过滤：仅保留当前主菜单下、接口下发的二级入口
         * 使用集合精确匹配，避免子串误判（如 AppIntExpAssemble 是 AppIntExpAssembleAllocate 的子串）
         */
        getAuthsObj()?.let { authsObj ->
            val authArr = authsObj.getJSONArray(id)
            // trim：兜底后端下发的权限串可能带首尾空格（如 "AppDomImpManiFest "），避免精确匹配失败
            val authSet = authArr?.map { it.toString().trim() }?.toSet() ?: emptySet()
            return list.filter { m -> authSet.contains(m.id) }
        }
        return list
    }

    private fun refreshRight(id: String) {
        (rvRight.adapter as? HomeRightAdapt)?.refresh(getRightMenu4Id(id))
    }

    /**
     * 开发调试：自动选择指定菜单
     * 正式发布前将 DEV_AUTO_SELECT_MENU 设置为 false 即可关闭
     */
    private fun autoSelectMenuForDev() {
        if (!DEV_AUTO_SELECT_MENU) return

        rvLeft.postDelayed({
            val leftAdapter = rvLeft.adapter as? HomeLeftAdapt ?: return@postDelayed
            val leftMenuList = initLeftMenuData()
            val targetIndex = leftMenuList.indexOfFirst { it.id == DEV_AUTO_SELECT_MENU_ID }

            if (targetIndex >= 0) {
                leftAdapter.simulateClick(targetIndex)
            }
        }, 300)
    }
}