import Foundation
import Combine


class HomeViewModel {
    
    static let shared = HomeViewModel()
    
    private init(){}
    
    func config(){}

    
    private var photoManager = PhotoManager.shared
    // 相册资源总大小
    var totalSize:Int64{
        return photoManager.videoTotalSize + photoManager.otherTotalSize + photoManager.screenShotTotalSize //videoSize + otherSize + screentSize
    }
    var totalFilesCount:Int = 0
    
    // 首页UI数据结构
    var headerGroup:[HomePhotosModel]{
        return [
            HomePhotosModel.init(
                folderName: HomeUIEnum.Dublicates.title,
                allFileSize:getTotalSize(source: photoManager.duplicateModels),
                assets: photoManager.duplicateModels),
            
            HomePhotosModel.init(
                folderName: HomeUIEnum.Similar.title,
                allFileSize:getTotalSize(source: photoManager.filterSimilarModels),
                assets:photoManager.filterSimilarModels)
        ]
        
    }
    // 首页UI数据结构
    var cardGroup:[HomePhotosModel]{
        return [
            HomePhotosModel.init(
                folderName: HomeUIEnum.Videos.title,
                allFileSize:getTotalSize(source: [photoManager.filterVideoModels]),
                assets: [photoManager.filterVideoModels],
                originalAssets: [photoManager.videoModels]
            ),
            HomePhotosModel.init(
                folderName: HomeUIEnum.SimilarScreenshots.title,
                allFileSize: getTotalSize(source: photoManager.filterSimilarScreenShotModels),
                assets: photoManager.filterSimilarScreenShotModels),
            HomePhotosModel.init(
                folderName: HomeUIEnum.Screensshots.title,
                allFileSize:getTotalSize(source: [photoManager.filterScreenShotModels]),
                assets:[photoManager.filterScreenShotModels],
                originalAssets: [photoManager.screenShotModels]
            ),
            HomePhotosModel.init(
                folderName: HomeUIEnum.SimilarVideos.title,
                allFileSize:getTotalSize(source: photoManager.filterSimilarVideoModels),
                assets: photoManager.filterSimilarVideoModels),
            HomePhotosModel.init(
                folderName: HomeUIEnum.Other.title,
                allFileSize:getTotalSize(source: [photoManager.filterOtherModels]),
                assets: [photoManager.filterOtherModels],
                originalAssets: [photoManager.otherModels]
            )
        ]
    }
    
    func getTotalSize(source:[[AssetModel]]) ->Double{
        return source.flatMap{$0}.reduce(0){$0+$1.assetSize}
    }
    
    var hadLoad = false

    var coverAssets:[[AssetModel]]{
        return [
            photoManager.duplicateModels.first ?? [],
            photoManager.filterSimilarModels.first ?? []
        ]
    }
    
    var homeDataChanged:((_ section:Int,_ row:Int,_ needReloadCol:Bool) ->Void)?
    
    func setupBindings() {
        
        NotificationCenter.default.addObserver(forName: .getBaseAssetsSuccess, object: nil, queue: nil) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.configBaseData()
        }
        
        //处理 homeview还未创建就发送通知的情况，通过hadLoad判断是否加载过
        configBaseData()
    }
    
    
    func configBaseData(){
        print("监听拿到基本资源",photoManager.baseDataLoadingState,hadLoad)
        
        guard case .loaded = photoManager.baseDataLoadingState,hadLoad == false else{
            return
        }
        
        guard photoManager.permissionStatus == .authorized else{
            return
        }
        
        totalFilesCount = photoManager.allAssets.count

        hadLoad = true
        
        photoManager.convertScreenShotModels {[weak self] screens, size in
            guard let weakSelf = self else { return }
            let type = HomeUIEnum.Screensshots
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,true)
        }
        
        photoManager.convertOtherPhotoModels {[weak self] others, size in
            guard let weakSelf = self else { return }

            let type = HomeUIEnum.Other
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,true)
        }
        
        photoManager.convertVideoModels {[weak self] videos, size in
            guard let weakSelf = self else { return }
          
            let type = HomeUIEnum.Videos
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,true)
        }
        
        startMainTask()
    }
    
    func startMainTask(){
        
        getSimilarOptimizer()
        getSimilarScreenOptimizer()
        getSimilarVideoOptimizer()
        getGroupDuplicateImages()
    }
    
    // 获取相似图片
    func getSimilarOptimizer(){
        
        let type = HomeUIEnum.Similar
        
        var needReloadAll = true
        
        PhotoSimilarManager.shared.findSimilarAssets(in: photoManager.otherAssets) {[weak self] group in
            guard let weakSelf = self else { return }

            weakSelf.photoManager.similarModels.append(group)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(0,type.index,needReloadAll)
            needReloadAll = false
            
        } completionHandler: {[weak self]  totalGroup in
            guard let weakSelf = self else { return }
            print("获取相似图片完成",totalGroup.count)
            weakSelf.photoManager.similarModels = weakSelf.sortGroupsByTime(totalGroup)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(0,type.index,true)
            
            NotificationManager().scheduleOneTimeNotification(afterHours: 24, identifier: "notification_24h")
            NotificationManager().scheduleOneTimeNotification(afterHours: 72, identifier: "notification_72h")
        }
    }
    
    // 获取相似截图
    func getSimilarScreenOptimizer(){
        
        let type = HomeUIEnum.SimilarScreenshots

        ScreenshotSimilarJSONManager.shared.findSimilarAssets(in: photoManager.screenShotAssets) {[weak self] group in
            guard let weakSelf = self else { return }

            weakSelf.photoManager.similarScreenShotModels.append(group)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,false)
          
        } completionHandler: {[weak self] totalGroup in
            guard let weakSelf = self else { return }
            print("获取相似截图完成",totalGroup.count)
            weakSelf.photoManager.similarScreenShotModels = weakSelf.sortGroupsByTime(totalGroup)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,false)
        }
    }
    

    func getSimilarVideoOptimizer(){
        
        let type = HomeUIEnum.SimilarVideos

        VideoSimilarJSONManager.shared.findSimilarVideos(in: photoManager.videoAssets) {[weak self] group in
            guard let weakSelf = self else { return }
            weakSelf.photoManager.similarVideoModels.append(group)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,false)

        } completionHandler: {[weak self] totalGroup in
            print("获取相似视频完成",totalGroup.count)
            guard let weakSelf = self else { return }
            weakSelf.photoManager.similarVideoModels = weakSelf.sortGroupsByTime(totalGroup)
            weakSelf.filterResource()
            weakSelf.homeDataChanged?(1,type.index,false)
        }
    }
    
    
    // 获取重复图片
    func getGroupDuplicateImages(){
        
        let type = HomeUIEnum.Dublicates

        PhotoDuplicateManager.shared.findDuplicateAssets(in: photoManager.otherAssets, mediaType: .photo) {[weak self] groups in
            guard let weakSelf = self else { return }

            weakSelf.photoManager.duplicateModels = groups
            weakSelf.filterResource()
            let currentThread = Thread.current
            if currentThread.isMainThread {
                print("在主线程执行")
            } else {
                print("在后台线程执行")
            }
          //  weakSelf.reloadCellHeight?()
            
            weakSelf.homeDataChanged?(0,type.index,true)
            
        } progressHandler: {group in
 
            
        } completionHandler: {[weak self] totalGroup in
            guard let weakSelf = self else { return }
            print("获得重复图片完成",totalGroup.count)
            let currentThread = Thread.current
            if currentThread.isMainThread {
                print("在主线程执行")
            } else {
                print("在后台线程执行")
            }
            weakSelf.photoManager.duplicateModels = weakSelf.sortGroupsByTime(totalGroup)
            weakSelf.filterResource()
           // weakSelf.reloadCellHeight?()
            weakSelf.homeDataChanged?(0,type.index,true)
        }
    }
    
    func reloadTrashAndKeep(){
        photoManager.reloadTrashAndKeep()
    }
    
    func filterResource(){
        photoManager.filterResource()
    }
    
    
    func sortGroupsByTime(_ groups: [[AssetModel]]) -> [[AssetModel]] {
          return groups.sorted { group1, group2 in
              guard let firstAsset1 = group1.first,
                    let firstAsset2 = group2.first else {
                  return false
              }
              return firstAsset1.createDate > firstAsset2.createDate
          }
    }
}

