//
//  TopPopupView.m
//  AIIM
//
//  Created by qitewei on 2025/6/17.
//

#import "TopPopupView.h"
#import "GroupNetApi.h"

static const CGFloat kPopupHeight = 80.0f;
static const CGFloat kPopupCornerRadius = 20.0f;
static const NSTimeInterval kPopupShowDuration = 0.3;
static const NSTimeInterval kPopupHideDuration = 0.3;
static const NSTimeInterval kPopupDisplayTime = 3.0;

@interface TopPopupView ()
@property (nonatomic, strong) UIImageView * avatar;
@property (nonatomic, strong) UILabel *nicknameLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) NSTimer *dismissTimer;
@property (nonatomic, assign) BOOL isDismissing;

@end

@implementation TopPopupView

+ (void)showWithNickname:(NSString *)nickname avatar:(nonnull NSString *)avatar message:(NSString *)message chatId:(nonnull NSString *)chatId type:(NSInteger)type clickBlock:(PopupClickBlock)clickBlock {
    // 确保在主线程执行
    dispatch_async(dispatch_get_main_queue(), ^{
        // 移除可能已经存在的弹窗
        UIWindow *keyWindow = [UIApplication sharedApplication].delegate.window;
        for (UIView *subview in keyWindow.subviews) {
            if ([subview isKindOfClass:[TopPopupView class]]) {
                [subview removeFromSuperview];
            }
        }
        
        // 创建新弹窗
        TopPopupView *popup = [[TopPopupView alloc] initWithFrame:CGRectMake(20, -kPopupHeight, keyWindow.bounds.size.width - 40, kPopupHeight)];
        popup.clickBlock = clickBlock;
        [popup setupWithNickname:nickname avatar:avatar message:message chatId:chatId type:type];
        [keyWindow addSubview:popup];
        
        // 显示动画
        [popup show];
    });
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    // 背景设置
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = kPopupCornerRadius;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0, 2);
    self.layer.shadowOpacity = 0.2;
    self.layer.shadowRadius = 4;
    
    self.avatar = [[UIImageView alloc] init];
    [self addSubview:self.avatar];
    self.avatar.layer.cornerRadius = 30.f;
    self.avatar.layer.masksToBounds = YES;
    
    // 昵称标签
    self.nicknameLabel = [[UILabel alloc] init];
    self.nicknameLabel.font = [UIFont boldSystemFontOfSize:16];
    self.nicknameLabel.textColor = [UIColor blackColor];
    [self addSubview:self.nicknameLabel];
    
    // 消息标签
    self.messageLabel = [[UILabel alloc] init];
    self.messageLabel.font = [UIFont systemFontOfSize:14];
    self.messageLabel.textColor = [UIColor blackColor];
    self.messageLabel.numberOfLines = 2;
    [self addSubview:self.messageLabel];
    
    // 添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
    [self addGestureRecognizer:tap];
    
    // 添加上滑手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe)];
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    [self addGestureRecognizer:swipe];
}

- (void)setupWithNickname:(NSString *)nickname avatar:(nonnull NSString *)avatar message:(NSString *)message chatId:(NSString *)chatId type:(NSInteger)type{
    self.nicknameLabel.text = nickname;
    self.messageLabel.text = message;
    if (avatar) {
        [self.avatar sd_setImageWithURL:getURL(avatar) placeholderImage:kImageMake(@"Avatar")];
    }
    
    // 布局
    CGFloat padding = 12.0f;
    CGFloat labelWidth = self.bounds.size.width - 2 * padding;
    
    self.avatar.frame = CGRectMake(padding, padding, 60, 60);
    self.nicknameLabel.frame = CGRectMake(padding+60+padding, padding, labelWidth, 20);
    self.messageLabel.frame = CGRectMake(padding+60+padding, CGRectGetMaxY(self.nicknameLabel.frame) + 4, labelWidth, 40);
}

- (void)show {
    // 初始位置在屏幕外
    CGRect startFrame = self.frame;
    
    // 动画目标位置
    CGRect endFrame = startFrame;
    endFrame.origin.y = [UIApplication sharedApplication].statusBarFrame.size.height + 10;
    
    // 执行显示动画
    [UIView animateWithDuration:kPopupShowDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.frame = endFrame;
    } completion:^(BOOL finished) {
        // 启动自动消失计时器
        [self startDismissTimer];
    }];
}

- (void)startDismissTimer {
    self.dismissTimer = [NSTimer scheduledTimerWithTimeInterval:kPopupDisplayTime target:self selector:@selector(dismiss) userInfo:nil repeats:NO];
}

- (void)dismiss {
    if (self.isDismissing) return;
    self.isDismissing = YES;
    
    // 取消计时器
    [self.dismissTimer invalidate];
    self.dismissTimer = nil;
    
    // 动画目标位置
    CGRect endFrame = self.frame;
    endFrame.origin.y = -kPopupHeight;
    
    // 执行消失动画
    [UIView animateWithDuration:kPopupHideDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.frame = endFrame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)handleTap {
    if (self.clickBlock) {
        self.clickBlock();
    }
    [self dismiss];
}

- (void)handleSwipe {
    [self dismiss];
}

- (void)dealloc {
    [self.dismissTimer invalidate];
}

@end
