//
//  HomeRouteHandler.swift
//  suixinkan
//

import UIKit

/// 首页菜单路由，将 permission URI 映射到已有页面或提示。
enum HomeRouteHandler {

    /// 处理菜单点击。
    @MainActor
    static func open(
        uri: String,
        from viewController: UIViewController,
        storeItem: StoreItem?,
        onCommonMenusChanged: (() -> Void)? = nil
    ) {
        if uri == "pilot_controller" {
            showDeveloping(from: viewController)
            return
        }

        if uri != "pilot_controller", uri != "wallet", AppStore.shared.session.currentScenicId <= 0 {
            showToast("请先选择景区", from: viewController)
            return
        }

        switch uri {
        case "more_functions":
            let controller = AllFunctionsViewController()
            controller.onDidCustomize = onCommonMenusChanged
            viewController.navigationController?.pushViewController(controller, animated: true)
        case "verification_order":
            selectTab(.orders, from: viewController)
        case "photographer_stats":
            selectTab(.statistics, from: viewController)
        case "system_settings":
            viewController.navigationController?.pushViewController(SettingViewController(), animated: true)
        case "message_center":
            viewController.navigationController?.pushViewController(MessageCenterViewController(), animated: true)
        case "space_settings":
            viewController.navigationController?.pushViewController(ProfileSpaceSettingsViewController(), animated: true)
        case "cloud_management":
            viewController.navigationController?.pushViewController(CloudDriveListViewController(), animated: true)
        case "pilot_cert":
            let controller = RealNameAuthViewController()
            viewController.navigationController?.pushViewController(controller, animated: true)
        case "operating-area":
            handleOperatingArea(from: viewController, storeItem: storeItem)
        case "cooperation_order":
            if !hasCooperationOrderPermission() {
                showToast("暂无合作订单权限", from: viewController)
                return
            }
            viewController.navigationController?.pushViewController(CooperationOrderListViewController(), animated: true)
        case "location_report":
            viewController.navigationController?.pushViewController(LocationReportViewController(), animated: true)
        case "report_photographer":
            viewController.navigationController?.pushViewController(WildPhotographerReportHomeViewController(), animated: true)
        case "registration_invitation", "photographer_invite":
            viewController.navigationController?.pushViewController(PhotographerInviteViewController(), animated: true)
        case "invite_record":
            viewController.navigationController?.pushViewController(InviteRecordViewController(), animated: true)
        case "/scenic-queue":
            viewController.navigationController?.pushViewController(ScenicQueueViewController(), animated: true)
        case "task_management", "task_management_editor":
            viewController.navigationController?.pushViewController(TaskAddViewController(), animated: true)
        case "travel_album":
            viewController.navigationController?.pushViewController(TravelAlbumEntryViewController(), animated: true)
        case "sample_management":
            viewController.navigationController?.pushViewController(SampleListViewController(), animated: true)
        case "asset_management":
            viewController.navigationController?.pushViewController(MaterialListViewController(), animated: true)
        case "checkin_points":
            viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true)
        case "live_stream_management":
            viewController.navigationController?.pushViewController(LiveManageViewController(), animated: true)
        case "live_album":
            viewController.navigationController?.pushViewController(LiveAlbumListViewController(), animated: true)
        case "wallet":
            viewController.navigationController?.pushViewController(WalletViewController(), animated: true)
        default:
            showDeveloping(from: viewController)
        }
    }

    @MainActor
    private static func handleOperatingArea(from viewController: UIViewController, storeItem: StoreItem?) {
        guard let role = AppStore.shared.session.currentAppRole else {
            showToast("当前账号暂不支持运营区域", from: viewController)
            return
        }
        switch role {
        case .storeAdmin:
            guard let storeItem, storeItem.id > 0 else {
                showToast("请先选择店铺", from: viewController)
                return
            }
            showDeveloping(from: viewController)
        case .scenicAdmin:
            guard AppStore.shared.session.currentScenicId > 0 else {
                showToast("请先选择景区", from: viewController)
                return
            }
            showDeveloping(from: viewController)
        default:
            showToast("当前账号暂不支持运营区域", from: viewController)
        }
    }

    private static func hasCooperationOrderPermission() -> Bool {
        let permissions = AppStore.shared.permissions.permissionItems()
        return permissions.contains { $0.uri == "cooperation_order" }
            || permissions.contains(where: { containsCooperationOrder(in: $0) })
    }

    private static func containsCooperationOrder(in item: HomePermissionItem) -> Bool {
        item.uri == "cooperation_order"
    }

    @MainActor
    private static func selectTab(_ tab: AppTab, from viewController: UIViewController) {
        guard let tabBar = viewController.tabBarController as? MainTabBarController else { return }
        tabBar.selectTab(tab)
    }

    @MainActor
    private static func showDeveloping(from viewController: UIViewController) {
        showToast("功能开发中", from: viewController)
    }

    @MainActor
    private static func showToast(_ message: String, from viewController: UIViewController) {
        if let base = viewController as? BaseViewController {
            base.showToast(message)
            return
        }
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        viewController.present(alert, animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            alert.dismiss(animated: true)
        }
    }
}
