//
//  UIImageView+KBWebImage.m
//  keyBoard
//

#import "UIImageView+KBWebImage.h"
#import <SDWebImage/SDWebImage.h>

// 默认下载配置：失败重试、后台续传、降采样、大图优先级
static inline SDWebImageOptions KBWebImageDefaultOptions(void) {
    return SDWebImageRetryFailed |
           SDWebImageContinueInBackground |
           SDWebImageHighPriority |
           SDWebImageScaleDownLargeImages |
           SDWebImageProgressiveLoad; // 渐进式
}

static inline NSURL *_KBURL(id url) {
    if (!url) return nil;
    if ([url isKindOfClass:NSURL.class]) return url;
    if ([url isKindOfClass:NSString.class]) return [NSURL URLWithString:(NSString *)url];
    return nil;
}

@implementation UIImageView (KBWebImage)

- (void)kb_setImageURL:(id)url placeholder:(UIImage *)placeholder {
    [self kb_setImageURL:url placeholder:placeholder options:KBWebImageDefaultOptions()];
}

- (void)kb_setImageURL:(id)url placeholder:(UIImage *)placeholder options:(NSUInteger)options {
    NSURL *u = _KBURL(url);
    // 默认渐隐动画
    __weak typeof(self) weakSelf = self;
    [self sd_setImageWithURL:u
            placeholderImage:placeholder
                     options:options
                    progress:nil
                   completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!error && image && cacheType == SDImageCacheTypeNone) {
            // 网络新图，做一次淡入动画
            weakSelf.alpha = 0.0;
            [UIView animateWithDuration:0.25 animations:^{ weakSelf.alpha = 1.0; }];
        }
    }];
}

- (void)kb_setImageURL:(id)url
           placeholder:(UIImage *)placeholder
        thumbnailToFit:(BOOL)thumbnailToFit
            targetSize:(CGSize)targetPixelSize {
    NSURL *u = _KBURL(url);
    SDWebImageOptions options = KBWebImageDefaultOptions();
    NSMutableDictionary<SDWebImageContextOption, id> *context = [NSMutableDictionary dictionary];

    if (thumbnailToFit) {
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = self.bounds.size;
        if (CGSizeEqualToSize(size, CGSizeZero) && !CGSizeEqualToSize(targetPixelSize, CGSizeZero)) {
            size = CGSizeMake(targetPixelSize.width/scale, targetPixelSize.height/scale);
        }
        if (!CGSizeEqualToSize(size, CGSizeZero)) {
            CGSize pixelSize = CGSizeMake(size.width * scale, size.height * scale);
            context[SDWebImageContextImageThumbnailPixelSize] = @(pixelSize);
        }
    }

    __weak typeof(self) weakSelf = self;
    [self sd_setImageWithURL:u
            placeholderImage:placeholder
                     options:options
                     context:context
                    progress:nil
                   completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!error && image && cacheType == SDImageCacheTypeNone) {
            weakSelf.alpha = 0.0;
            [UIView animateWithDuration:0.25 animations:^{ weakSelf.alpha = 1.0; }];
        }
    }];
}

- (void)kb_setImageURL:(id)url
           placeholder:(UIImage *)placeholder
         cornerRadius:(CGFloat)radius
               corners:(UIRectCorner)corners
           borderWidth:(CGFloat)borderWidth
           borderColor:(UIColor *)borderColor {
    NSURL *u = _KBURL(url);
    SDWebImageOptions options = KBWebImageDefaultOptions();

    // 组合圆角 + 缩略（按视图大小）
    CGFloat scale = UIScreen.mainScreen.scale;
    CGSize size = self.bounds.size;
    NSMutableArray<id<SDImageTransformer>> *trans = [NSMutableArray array];
    if (!CGSizeEqualToSize(size, CGSizeZero)) {
        // 先按像素缩到视图大小，避免在解码后再裁切浪费内存
        CGSize pixel = CGSizeMake(size.width * scale, size.height * scale);
        [trans addObject:[SDImageResizingTransformer transformerWithSize:pixel scaleMode:SDImageScaleModeAspectFill]];
    }
    [trans addObject:[SDImageRoundCornerTransformer transformerWithRadius:radius
                                                                  corners:(SDRectCorner)corners
                                                              borderWidth:borderWidth
                                                              borderColor:borderColor]];
    SDImagePipelineTransformer *pipeline = [SDImagePipelineTransformer transformerWithTransformers:trans];

    NSDictionary *context = @{ SDWebImageContextImageTransformer : pipeline };

    __weak typeof(self) weakSelf = self;
    [self sd_setImageWithURL:u
            placeholderImage:placeholder
                     options:options
                     context:context
                    progress:nil
                   completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!error && image && cacheType == SDImageCacheTypeNone) {
            weakSelf.alpha = 0.0;
            [UIView animateWithDuration:0.25 animations:^{ weakSelf.alpha = 1.0; }];
        }
    }];
}

- (void)kb_setAvatarURL:(id)url placeholder:(UIImage *)placeholder {
    // 圆形：以视图最短边的一半为半径
    CGSize sz = self.bounds.size;
    CGFloat r = MIN(sz.width, sz.height) * 0.5;
    if (r <= 0) {
        // 若尚未布局，使用占位图尺寸估算
        r = MIN(placeholder.size.width, placeholder.size.height) * 0.5;
    }
    [self kb_setImageURL:url
             placeholder:placeholder
           cornerRadius:r
                 corners:UIRectCornerAllCorners
             borderWidth:0
             borderColor:nil];
}

- (void)kb_cancelImageLoad {
    [self sd_cancelCurrentImageLoad];
}

@end
