import UIKit
import Photos

// 图片缓存管理（单例）
private let imageCache: NSCache<NSString, UIImage> = {
    let cache = NSCache<NSString, UIImage>()
    cache.totalCostLimit = 50 * 1024 * 1024  // 50MB
    cache.countLimit = 100  // 最多缓存100张图片
    return cache
}()

extension UIImageView {
    // 关联对象键，用于存储当前请求的 localIdentifier
    private struct AssociatedKeys {
        static var currentRequestID = "currentRequestID"
        static var currentAssetIdentifier = "currentAssetIdentifier"
    }
    
    // 当前请求 ID
    private var currentRequestID: PHImageRequestID? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.currentRequestID) as? PHImageRequestID
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.currentRequestID, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // 当前请求的 asset identifier
    private var currentAssetIdentifier: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.currentAssetIdentifier) as? String
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.currentAssetIdentifier, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // 加载图片的主方法
    func loadImage(
        withLocalIdentifier identifier: String,
        targetSize: CGSize = CGSize(width: 300, height: 300),
        placeholder: UIImage? = nil,
        completion: ((UIImage?) -> Void)? = nil
    ) {
        // 1. 先取消当前进行中的请求
        if let requestID = currentRequestID {
            PHImageManager.default().cancelImageRequest(requestID)
        }
        
        // 2. 设置占位图
        image = placeholder
        
        // 3. 检查缓存
        if let cachedImage = imageCache.object(forKey: identifier as NSString) {
            self.image = cachedImage
            completion?(cachedImage)
            return
        }
        
        // 4. 存储当前请求信息
        currentRequestID = nil
        currentAssetIdentifier = identifier
        
        // 5. 获取 PHAsset
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil)
        guard let asset = fetchResult.firstObject else {
            completion?(nil)
            return
        }

        // 6. 配置图片请求选项
        let options = PHImageRequestOptions()
        options.version = .current
        options.deliveryMode = .highQualityFormat  // 改为渐进式加载
        options.isNetworkAccessAllowed = true
        options.resizeMode = .fast  // 改为快速加载模式
        options.isSynchronous = false
        options.progressHandler = { progress, error, stop, info in
            DispatchQueue.main.async {
                // 可以在这里添加加载进度的处理
               // print("Loading progress: \(progress)")
                if let error = error {
                    print("Loading error: \(error.localizedDescription)")
                }
            }
        }
        
        // 7. 请求图片
        currentRequestID = PHImageManager.default().requestImage(
            for: asset,
            targetSize: targetSize,
            contentMode: .aspectFit,
            options: options
        ) { [weak self] image, info in
            guard let self = self else { return }
            
            // 8. 验证请求是否匹配（避免复用导致的错乱）
            if self.currentAssetIdentifier != identifier {
                return
            }
            
            // 9. 处理结果
            if let image = image {
                // 缓存图片
                imageCache.setObject(image, forKey: identifier as NSString)
                
                // 更新 UI
                DispatchQueue.main.async {
                    self.image = image
                    completion?(image)
                }
            } else {
                DispatchQueue.main.async {
                    completion?(nil)
                }
            }
            
            // 10. 重置请求状态
            self.currentRequestID = nil
            self.currentAssetIdentifier = nil
        }
    }
    
    // 取消当前图片请求
    func cancelImageRequest() {
        if let requestID = currentRequestID {
            PHImageManager.default().cancelImageRequest(requestID)
            currentRequestID = nil
            currentAssetIdentifier = nil
        }
    }
    
    // 清理缓存
    @objc func clearCacheOnMemoryWarning() {
        imageCache.removeAllObjects()
    }
    
    // 命名空间
    struct AssetLoader {
        fileprivate weak var imageView: UIImageView?
        
        func clearImageCache() {
            imageCache.removeAllObjects()
        }
    }
    
    var asset: AssetLoader {
        return AssetLoader(imageView: self)
    }
}

extension UIImageView.AssetLoader {
    func load(
        withLocalIdentifier identifier: String,
        targetSize: CGSize = PHImageManagerMaximumSize,
        placeholder: UIImage? = nil,
        completion: ((UIImage?) -> Void)? = nil
    ) {
        imageView?.loadImage(
            withLocalIdentifier: identifier,
            targetSize: targetSize,
            placeholder: placeholder,
            completion: completion
        )
    }
    
    // 圆角图片扩展
    func loadRounded(
        withLocalIdentifier identifier: String,
        targetSize: CGSize = PHImageManagerMaximumSize,
        cornerRadius: CGFloat? = nil,
        placeholder: UIImage? = nil
    ) {
        load(
            withLocalIdentifier: identifier,
            targetSize: targetSize,
            placeholder: placeholder
        ) {  image in
           
            DispatchQueue.main.async {
                if let radius = cornerRadius {
                    self.imageView?.layer.cornerRadius = radius
                } else {
                    self.imageView?.layer.cornerRadius = (self.imageView?.bounds.width ?? 0) / 2
                }
                self.imageView?.layer.masksToBounds = true
                self.imageView?.image = image
            }
        }
    }
}
