//
//  AIChatUploadImageView.m
//  ChatAgentApp
//
//  Created by caoshiqian on 2025/7/4.
//

#import "AIChatUploadImageView.h"

static CGFloat const STATUS_SIZE = 20;

@interface AIChatUploadImageView ()

@property (nonatomic, assign) BOOL needReload;

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImageView *statusView;

@end

@implementation AIChatUploadImageView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
//        self.backgroundColor = [UIColor lightGrayColor];
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    _imageView = [[UIImageView alloc] init];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    _imageView.clipsToBounds = YES;
    [self addSubview:_imageView];
    
    _statusView = [[UIImageView alloc] init];
    _statusView.contentMode = UIViewContentModeScaleAspectFit;
    _imageView.clipsToBounds = NO;
    [self addSubview:_statusView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect frame = self.bounds;
    if (_imageView.image) {
        CGSize size = _imageView.image.size;
        CGFloat w = frame.size.height * size.width / size.height;
        frame = CGRectMake(frame.size.width - w, frame.origin.y, w, frame.size.height);
    }
    _imageView.frame = frame;
    
    _statusView.frame = CGRectMake(_imageView.frame.origin.x - STATUS_SIZE - 10, self.bounds.size.height - STATUS_SIZE, STATUS_SIZE, STATUS_SIZE);
}

- (void)setImage:(UIImage *)image {
    self.imageView.image = image;
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)setImageUrl:(NSURL *)imageUrl {
    if ([imageUrl.path isEqualToString:_imageUrl.path]) {
        return;
    }
    
    _imageUrl = imageUrl;
    _imageView.image = nil;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *image = [UIImage imageWithData:imageData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = image;
            [self setNeedsLayout];
            [self layoutIfNeeded];
        });
    });
}

- (void)setStatus:(UploadStatus)status {
    _status = status;
    NSString *imageName = @"";
    switch (status) {
        case UploadStatusWait:
            imageName = @"upload_wait";
            break;
        case UploadStatusFail:
            imageName = @"upload_warn";
            break;
        default:
            break;
    }
    if (imageName.length) {
        _statusView.image = [UIImage imageNamed:imageName];
    } else {
        _statusView.image = nil;
    }
}

@end
