//
//  UIImageView+Ext.swift
//  E-Wow
//
//  Created by lym on 2021/1/8.
//

import Foundation
import Kingfisher
import UIKit

extension UIImageView
{
    private static let defaultOptions: KingfisherOptionsInfo = [
        .transition(.none),
        .loadDiskFileSynchronously,
    ]

    /**
     无s3逻辑
     默认给图片设置bgColor(csbn)
     */
    func loadImage(_ url: String?,
                   placeholder: Placeholder? = nil,
                   bgColor: UIColor? = .c.csbn,
                   options: KingfisherOptionsInfo? = defaultOptions)
    {
        backgroundColor = bgColor
        kf.setImage(with: URL(string: url ?? ""), placeholder: placeholder, options: options)
    }
    
    /// - Parameters:
    ///   - urlString: 图片的URL字符串
    ///   - placeholder: 占位图（可选）
    ///   - progressBlock: 进度回调，接收已下载字节和总字节
    ///   - completionBlock: 完成回调，接收加载结果
    func loadImage(
        _ urlString: String?,
        placeholder: Placeholder? = nil,
        bgColor: UIColor? = .hexInt32(0xFBDEFF).withAlphaComponent(0.08),
        progressBlock: ((_ receivedSize: Int64, _ totalSize: Int64) -> Void)? = nil,
        completionBlock: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil
    ) {
        guard let urlString = urlString, let url = URL(string: urlString) else {
            completionBlock?(.failure(.requestError(reason: .emptyRequest)))
            return
        }
        
        kf.setImage(
            with: url,
            placeholder: placeholder,
            options: nil,
            progressBlock: { receivedSize, totalSize in
                // 进度回调
                progressBlock?(receivedSize, totalSize)
            },
            completionHandler: { result in
                // 完成回调
                completionBlock?(result)
            }
        )
    }
    
    
}

struct ImageDownloader {
    /// 使用 Kingfisher 下载图片，带 completion 回调
//    static func downloadImage(
//        from url: URL?,
//        completion: @escaping (UIImage?) -> Void
//    ) {
//        guard let url = url else {
//            completion(nil)
//            return
//        }
//        
//        KingfisherManager.shared.retrieveImage(with: url) { result in
//            switch result {
//            case .success(let value):
//                completion(value.image) // 成功
//            case .failure(let error):
//                print("❌ 图片下载失败: \(error)")
//                completion(nil)
//            }
//        }
//    }
    
    /// 使用 Kingfisher 下载图片，传入可选 String 链接
    static func downloadImage(
        from urlString: String?,
        completion: @escaping (UIImage?) -> Void
    ) {
        guard
            let urlString = urlString,
            let url = URL(string: urlString)
        else {
            completion(nil)
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: url) { result in
            switch result {
            case .success(let value):
                completion(value.image) // 成功返回 UIImage
            case .failure(let error):
                print("❌ 图片下载失败: \(error)")
                completion(nil)
            }
        }
    }
}
