import Flutter
import Photos
import UIKit

public class PhotoClassifyPlugin: NSObject, FlutterPlugin {
    
    var photoClassifier = PhotoClassifier()

  private static let METHOD_GET_PHOTO = "getPhoto"

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "photo_classify", binaryMessenger: registrar.messenger())
    let instance = PhotoClassifyPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case PhotoClassifyPlugin.METHOD_GET_PHOTO:
        self.getPhoto(flutterResult: result)
    default:
        result(FlutterMethodNotImplemented)
    }
  }

    private func getPhoto(flutterResult: @escaping FlutterResult) {

       print("正在寻找照片中")
       let fetchOptions = PHFetchOptions()
       let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)

       photoClassifier.classifyPhotos(
           assets: allPhotos,
           progressHandler: { [weak self] (stage, progress) in
//                DispatchQueue.main.async {
//                    self?.updateProgress(stage: stage, progress: progress)
//                }
           },
           completion: { [weak self] result in
               guard let self = self else { return }

               var similarPhotos = result.similarPhotos

               // 创建数组存储最终结果
               var resultData: [[String: Any]] = []

               // 创建组来同步异步操作
               let group = DispatchGroup()

               // 遍历每组相似照片
               for photoGroup in similarPhotos {
                   var groupData: [[String: Any]] = []

                   // 处理组内每张照片
                   for asset in photoGroup {
                       group.enter()

                       let options = PHImageRequestOptions()
                       options.deliveryMode = .highQualityFormat
                       options.isSynchronous = false

                       PHImageManager.default().requestImage(
                           for: asset,
                           targetSize: CGSize(width: 800, height: 800), // 可调整尺寸
                           contentMode: .aspectFit,
                           options: options
                       ) { image, info in
                           defer { group.leave() }

                           if let image = image,
                              let imageData = image.jpegData(compressionQuality: 0.8) {
                               // 创建照片信息字典
                               let photoInfo: [String: Any] = [
                                   "data": FlutterStandardTypedData(bytes: imageData),
                                   "id": asset.localIdentifier,
                                   "width": image.size.width,
                                   "height": image.size.height,
                                   "creationDate": asset.creationDate?.timeIntervalSince1970 ?? 0
                               ]
                               DispatchQueue.main.async {
                                   groupData.append(photoInfo)
                               }
                           }
                       }
                   }

                   // 等待当前组的所有照片处理完成
                   group.wait()

                   // 只有当组内有照片时才添加到结果中
                   if !groupData.isEmpty {
                       resultData.append(["group": groupData])
                   }
               }

               // 在主线程返回结果
               DispatchQueue.main.async {
                   flutterResult(resultData)
               }
           }
       )
    }
}
