//
//  AllFunctionsViewModel.swift
//  suixinkan
//

import Foundation

/// 全部功能页 ViewModel，管理常用应用与更多功能的增删与持久化。
final class AllFunctionsViewModel {

    private(set) var commonMenus: [HomeMenuItem] = []
    private(set) var moreMenus: [HomeMenuItem] = []

    var onStateChange: (() -> Void)?
    private(set) var didCustomize = false

    private let appStore: AppStore
    private let commonMenuStore: HomeCommonMenuStore

    init(
        appStore: AppStore = .shared,
        commonMenuStore: HomeCommonMenuStore = HomeCommonMenuStore()
    ) {
        self.appStore = appStore
        self.commonMenuStore = commonMenuStore
    }

    /// 加载全部功能并按常用配置拆分。
    func loadFunctions() {
        let permissions = appStore.permissions.permissionItems()
        let allMenus = HomeMenuCatalog.visibleMenus(from: permissions)
        let accountScope = appStore.session.accountCachePrefix
        let roleCode = appStore.session.roleCode
        let savedURIs = commonMenuStore.savedCommonURIs(accountScope: accountScope, roleCode: roleCode)
        let defaultURIs = HomeCommonMenuStore.defaultCommonURIs(from: permissions)
        let commonURIs = savedURIs.isEmpty ? defaultURIs : savedURIs

        let split = HomeCommonMenuStore.splitMenus(from: allMenus, commonURIs: commonURIs)
        commonMenus = split.common
        moreMenus = split.more

        if savedURIs.isEmpty, !split.common.isEmpty {
            commonMenuStore.saveCommonURIs(split.common.map(\.uri), accountScope: accountScope, roleCode: roleCode)
        }

        notifyStateChange()
    }

    /// 将菜单加入常用应用。
    func addToCommon(_ menu: HomeMenuItem) {
        guard HomeMenuCatalog.isCustomizable(uri: menu.uri) else { return }
        guard !commonMenus.contains(where: { $0.uri == menu.uri }) else { return }
        commonMenus.append(menu)
        moreMenus.removeAll { $0.uri == menu.uri }
        persistCommonMenus()
        didCustomize = true
        notifyStateChange()
    }

    /// 将菜单移出常用应用。
    func removeFromCommon(_ menu: HomeMenuItem) {
        guard commonMenus.contains(where: { $0.uri == menu.uri }) else { return }
        commonMenus.removeAll { $0.uri == menu.uri }
        if !moreMenus.contains(where: { $0.uri == menu.uri }) {
            moreMenus.append(menu)
        }
        persistCommonMenus()
        didCustomize = true
        notifyStateChange()
    }

    private func persistCommonMenus() {
        commonMenuStore.saveCommonURIs(
            commonMenus.map(\.uri),
            accountScope: appStore.session.accountCachePrefix,
            roleCode: appStore.session.roleCode
        )
    }

    private func notifyStateChange() {
        onStateChange?()
    }
}
