//
//  MaintaiViewModel.swift
//  PhoneManager
//
//  Created by edy on 2025/5/14.
//

import Foundation


class MaintaiViewModel{
    
    var dataSouece: [String: [AssetModel]] = [:]
    var souceOrder: [String] = []  // 记录分组ID的添加顺序
    var souces: [[AssetModel]] = []
    
    func getMaintaiData(complect: () -> Void) {
        dataSouece.removeAll()
        souceOrder.removeAll()
        
        let list = GroupDatabase.shared.queryAll()
        
        list.forEach { (localIdentifier: String, assetSize: Double, createDate: Date, mediaType: Int, groupId: String) in
            if mediaType == 2 {
                // 视频不分组
                let tempId = UUID().uuidString
                dataSouece[tempId] = [AssetModel(localIdentifier: localIdentifier, assetSize: assetSize, createDate: createDate, mediaType: mediaType)]
                souceOrder.append(tempId)  // 记录添加顺序
            } else {
                if dataSouece[groupId] == nil {
                    dataSouece[groupId] = []
                    souceOrder.append(groupId)  // 首次添加时记录顺序
                }
                dataSouece[groupId]?.append(AssetModel(localIdentifier: localIdentifier, assetSize: assetSize, createDate: createDate, mediaType: mediaType))
            }
        }
        
        // 按照记录的顺序生成souces
        souces = souceOrder.compactMap { dataSouece[$0] }
        complect()
    }
    
    func refreshData(completion: @escaping () -> Void) {
        dataSouece.removeAll()
        souces.removeAll()
        
        // 重新加载数据
        getMaintaiData(complect: completion)
    }
    
}


