

#import "SLCustomizeAlert.h"

@interface SLCustomizeAlert()<UITextViewDelegate>

@property (nonatomic, strong) UIWindow *rootWindow;
@property (nonatomic, strong) UIView *alertView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *line1View;
@property (nonatomic, strong) UITextView *messageTextView;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *sureBtn;
@property (nonatomic, copy) SLAlertAction sureActionBlock;
@property (nonatomic, copy) SLAlertAction cancleActionBlock;

@property (nonatomic, copy) SLCustomizeAlertClick alertClick;
@property (nonatomic, copy) SLAlertAttrAction attributedAction;

@end

@implementation SLCustomizeAlert

- (void)bottomBtnClick:(UIButton *)btn
{
    if (self.alertClick) {
        self.alertClick(btn.tag - 6688);
        [self removeFromSuperview];
    }
}

- (void)showBottomAletrWithTitles:(NSArray<NSString *> *)titles
                        cancelTitle:(NSString *)cancelTitle
                        buttonIndex:(void (^)(NSInteger index))buttonIndex
{
    self.alertClick = buttonIndex;
    CGFloat cancelHeight = cancelTitle.length ? 70 * KScaleW + kSafeAreaBottom : 0;
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectZero];
    bottomView.backgroundColor = SLBgColor;
    [self addSubview:bottomView];
    bottomView.clipsToBounds = YES;
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self);
        make.height.mas_equalTo(60 * titles.count * KScaleW + cancelHeight);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGFloat cornerRadius = 12;
        //设置所需的圆角位置以及大小
        UIBezierPath *maskPath;
        maskPath = [UIBezierPath bezierPathWithRoundedRect:bottomView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(cornerRadius , cornerRadius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = bottomView.bounds;
        maskLayer.path = maskPath.CGPath;
        bottomView.layer.mask = maskLayer;
    });
    
    NSMutableArray *marr = [[NSMutableArray alloc] init];
    [titles enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:obj forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor whiteColor];
        btn.tag = 6688 + idx;
        [btn setTitleColor:SLColor(@"#666666") forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont fontWithName:@"PingFang SC" size:16];
        [btn addTarget:self action:@selector(bottomBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
        [marr addObject:btn];
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectZero];
        [btn addSubview:lineView];
        lineView.backgroundColor = SLBgColor;
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(btn);
            make.height.mas_equalTo(1);
            make.bottom.mas_equalTo(-1);
        }];
    }];
    
    if (marr.count > 1) {
        [marr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:0 leadSpacing:0 tailSpacing:cancelHeight];
        [marr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.left.equalTo(bottomView);
        }];
    }else {
        [marr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.left.top.equalTo(bottomView);
            make.height.mas_equalTo(60 * KScaleW);
        }];
    }
    
    if (cancelTitle.length) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectZero];
        bgView.backgroundColor = [UIColor whiteColor];
        [bottomView addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(bottomView);
            make.height.mas_equalTo(kSafeAreaBottom);
        }];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:cancelTitle forState:UIControlStateNormal];
        [bottomView addSubview:btn];
        [btn setTitleColor:SLColor(@"#666666") forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont fontWithName:@"PingFang SC" size:16];
        btn.backgroundColor = [UIColor whiteColor];
        btn.tag = 6688 + titles.count;
        [btn addTarget:self action:@selector(bottomBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.height.mas_equalTo(60 * KScaleW);
            make.bottom.mas_offset(- kSafeAreaBottom);
        }];
    }
    
    [self alertShow];
}

+ (void)showBottomAletrWithTitles:(NSArray<NSString *> *)titles
                      cancelTitle:(NSString *)cancelTitle
                      buttonIndex:(void (^)(NSInteger index))buttonIndex
{
    SLCustomizeAlert * alert = [[SLCustomizeAlert alloc] init];
    [alert showBottomAletrWithTitles:titles cancelTitle:cancelTitle buttonIndex:buttonIndex];
}

+ (instancetype)showAletrWithTitle:(NSString *)title
                           message:(NSString *)message
                      sureBtnTitle:(NSString *)sureBtnTitle
                    cancelBtnTitle:(NSString *)cancelBtnTitle
                     sureBtnAction:(SLAlertAction)sureBtnAction
                   cancelBtnAction:(SLAlertAction)cancelBtnAction
{
    SLCustomizeAlert *alert = [[SLCustomizeAlert alloc] initWithTitle:title message:message sureBtnTitle:sureBtnTitle cancelBtnTitle:cancelBtnTitle sureBtnAction:sureBtnAction cancelBtnAction:cancelBtnAction];
    [alert alertShow];
    return alert;
}


- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
                 sureBtnTitle:(NSString *)sureBtnTitle
               cancelBtnTitle:(NSString *)cancelBtnTitle
                sureBtnAction:(SLAlertAction)sureBtnAction
              cancelBtnAction:(SLAlertAction)cancelBtnAction
{
    self = [super init];
    if (self) {
        self.titleLabel.text = title;
        if ([message hasSuffix:@">"] && [message containsString:@"</"]) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSMutableAttributedString *attributedMessage = [[NSMutableAttributedString alloc] initWithData:[message dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType} documentAttributes:nil error:nil];
                [attributedMessage setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14],
                                                   NSForegroundColorAttributeName : SLColor(@"#333333")}
                                           range:NSMakeRange(0, attributedMessage.length)];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.messageTextView.attributedText = attributedMessage;
                    [self updateConstraintsMsgTextView];
                });
            });
        }else {
            self.messageTextView.text = message;
        }
        BOOL hasCancelBtn = cancelBtnTitle.length > 0 ? YES : NO;
        [self confignUIWith:hasCancelBtn];
        [self.sureBtn setTitle:sureBtnTitle forState:UIControlStateNormal];
        self.sureActionBlock = sureBtnAction;
        if (hasCancelBtn) {
            [self.cancelBtn setTitle:cancelBtnTitle forState:UIControlStateNormal];
            self.cancleActionBlock = cancelBtnAction;
        }
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)title
                attributedMsg:(NSAttributedString *)attributedMsg
                 sureBtnTitle:(NSString *)sureBtnTitle
               cancelBtnTitle:(NSString *)cancelBtnTitle
                sureBtnAction:(SLAlertAction)sureBtnAction
              cancelBtnAction:(SLAlertAction)cancelBtnAction
             attributedAction:(SLAlertAttrAction)attributedAction
{
    self = [super init];
    if (self) {
        self.titleLabel.text = title;
        self.messageTextView.attributedText = attributedMsg;
        self.messageTextView.selectable = YES;
        BOOL hasCancelBtn = cancelBtnTitle.length > 0 ? YES : NO;
        [self confignUIWith:hasCancelBtn];
        [self.sureBtn setTitle:sureBtnTitle forState:UIControlStateNormal];
        self.sureActionBlock = sureBtnAction;
        self.attributedAction = attributedAction;
        if (hasCancelBtn) {
            [self.cancelBtn setTitle:cancelBtnTitle forState:UIControlStateNormal];
            self.cancleActionBlock = cancelBtnAction;
        }
    }
    return self;
}

#pragma mark - alertShow
- (void)alertShow
{
    UIWindow *window = kWindow;
    if (window) {
        self.frame = window.frame;
        self.backgroundColor = [SLColor(@"#000000") colorWithAlphaComponent:0.55];
        [window makeKeyAndVisible];
        [window makeKeyWindow];
        [window addSubview:self];
    }
}

- (void)alertShowWithViewcontroller:(UIViewController *)vc
{
    self.frame = vc.view.bounds;
    self.backgroundColor = [SLColor(@"#000000") colorWithAlphaComponent:0.3];
    [vc.view addSubview:self];
}

- (void)confignUIWith:(BOOL)hasCancelBtn
{
    CGSize constraintSize = CGSizeMake(270 * KScaleW - 16*2, MAXFLOAT);
    CGSize size = [self.messageTextView sizeThatFits:constraintSize];
    if (size.height > 300) {
        size.height = 300;
    }
    
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(270 * KScaleW));
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.alertView);
        make.top.equalTo(self.alertView).offset(24);
        make.left.greaterThanOrEqualTo(self.alertView).offset(16);
    }];
    
    [self.messageTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(8);
        make.centerX.equalTo(self.alertView);
        make.left.equalTo(@(16));
        make.bottom.equalTo(self.lineView.mas_top).offset(-16);
        make.height.greaterThanOrEqualTo(@(size.height));
    }];
    
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.messageTextView.mas_bottom).offset(16);
        make.centerX.equalTo(self.alertView);
        make.left.equalTo(@(0));
        make.height.equalTo(@(0.0));
    }];
    
    self.sureBtn.backgroundColor = SLBlueColor;
    self.cancelBtn.backgroundColor = [SLBlueColor colorWithAlphaComponent:0.1];
    if (!hasCancelBtn) {
        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lineView.mas_bottom);
            make.centerX.equalTo(self.alertView);
            make.width.equalTo(self.alertView);
            make.height.equalTo(@(52));
            make.bottom.equalTo(self.alertView.mas_bottom);
        }];
    }else{
        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lineView.mas_bottom);
            make.centerX.equalTo(self.alertView.mas_centerX).multipliedBy(3 / 2.0).offset(-6);
            make.width.equalTo(@(110));
            make.height.equalTo(@(50));
            make.bottom.equalTo(self.alertView.mas_bottom).offset(-20);
        }];
        self.sureBtn.layer.cornerRadius = 25;
        self.cancelBtn.layer.cornerRadius = 25;
        [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.cancelBtn setTitleColor:SLBlueColor forState:UIControlStateNormal];
        
        [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lineView.mas_bottom);
            make.centerX.equalTo(self.alertView.mas_centerX).multipliedBy(1 / 2.0).offset(6);
            make.width.equalTo(@(110));
            make.height.equalTo(@(50));
            make.bottom.equalTo(self.alertView.mas_bottom).offset(-20);
        }];
        
    }
}


//- (void)confignUIWith:(BOOL)hasCancelBtn
//{
//    CGSize constraintSize = CGSizeMake(270 * KScaleW - 16*2, MAXFLOAT);
//    CGSize size = [self.messageTextView sizeThatFits:constraintSize];
//    if (size.height > 300) {
//        size.height = 300;
//    }
//
//    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.equalTo(self);
//        make.width.equalTo(@(270 * KScaleW));
//    }];
//
//    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self.alertView);
//        make.top.equalTo(self.alertView).offset(24);
//        make.left.greaterThanOrEqualTo(self.alertView).offset(16);
//    }];
//
//    [self.messageTextView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleLabel.mas_bottom).offset(8);
//        make.centerX.equalTo(self.alertView);
//        make.left.equalTo(@(16));
//        make.bottom.equalTo(self.lineView.mas_top).offset(-16);
//        make.height.greaterThanOrEqualTo(@(size.height));
//    }];
//
//
//    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.messageTextView.mas_bottom).offset(16);
//        make.centerX.equalTo(self.alertView);
//        make.left.equalTo(@(0));
//        make.height.equalTo(@(0.5));
//    }];
//
//
//    if (!hasCancelBtn) {
//        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.lineView.mas_bottom);
//            make.centerX.equalTo(self.alertView);
//            make.width.equalTo(self.alertView);
//            make.height.equalTo(@(52));
//            make.bottom.equalTo(self.alertView.mas_bottom);
//        }];
//    }else{
//        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.lineView.mas_bottom);
//            make.centerX.equalTo(self.alertView.mas_centerX).multipliedBy(3 / 2.0);
//            make.width.equalTo(self.alertView).multipliedBy(1 / 2.0);
//            make.height.equalTo(@(52));
//            make.bottom.equalTo(self.alertView.mas_bottom);
//        }];
//
//        [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.lineView.mas_bottom);
//            make.centerX.equalTo(self.alertView.mas_centerX).multipliedBy(1 / 2.0);
//            make.width.equalTo(self.alertView).multipliedBy(1 / 2.0);
//            make.height.equalTo(@(52));
//            make.bottom.equalTo(self.alertView.mas_bottom);
//        }];
//
//        [self.line1View mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(self.alertView);
//            make.centerY.equalTo(self.sureBtn);
//            make.height.equalTo(@(32));
//            make.width.equalTo(@(0.5));
//        }];
//    }
//}

- (void)updateConstraintsMsgTextView
{
    CGSize constraintSize = CGSizeMake(270 * KScaleW - 16*2, MAXFLOAT);
    CGSize size = [self.messageTextView sizeThatFits:constraintSize];
    if (size.height > 300) {
        size.height = 300;
    }
    [self.messageTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.greaterThanOrEqualTo(@(size.height));
    }];
}

#pragma mark - textViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([[URL scheme] isEqualToString:@"privacyPolicy"]) {
        if (self.attributedAction) {
            self.attributedAction(@"privacyPolicy");
        }
        return NO;
    }
    return YES;
}

#pragma mark - layz
- (UIView *)alertView
{
    if (!_alertView) {
        _alertView = [[UIView alloc] initWithFrame:CGRectZero];
        _alertView.backgroundColor = UIColor.whiteColor;
        _alertView.layer.cornerRadius = 8.f;
        [self addSubview:_alertView];
    }
    return _alertView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.textColor = SLColor(@"#333333");
        _titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [self.alertView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UIView *)lineView
{
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectZero];
        _lineView.backgroundColor = SLColor(@"#EEEEEE");
        [self.alertView addSubview:_lineView];
    }
    return _lineView;
}

- (UIView *)line1View
{
    if (!_line1View) {
        _line1View = [[UIView alloc] initWithFrame:CGRectZero];
        _line1View.backgroundColor = SLColor(@"#EEEEEE");
        [self.alertView addSubview:_line1View];
    }
    return _line1View;
}

- (UITextView *)messageTextView
{
    if (!_messageTextView) {
        _messageTextView = [[UITextView alloc] initWithFrame:CGRectZero];
        _messageTextView.textColor = [UIColor colorFormString:@"#333333"];
        _messageTextView.font = [UIFont systemFontOfSize:14];
        _messageTextView.textAlignment = NSTextAlignmentCenter;
//        _messageTextView.showsVerticalScrollIndicator = NO;
        _messageTextView.editable = NO;
        _messageTextView.selectable = NO;
        _messageTextView.scrollEnabled = YES;
        _messageTextView.delegate = self;
        _messageTextView.bounces = NO;
        [self.alertView addSubview:_messageTextView];
    }
    return _messageTextView;
}

- (UIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sureBtn setTitleColor:SLColor(@"#EB2B2B") forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
        [self.alertView addSubview:_sureBtn];
    }
    return _sureBtn;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelBtn setTitleColor:SLColor(@"#333333") forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        [self.alertView addSubview:_cancelBtn];
    }
    return _cancelBtn;
}

- (void)sureAction
{
    if (self.sureActionBlock) {
        self.sureActionBlock();
    }
    if (!self.remainOnClick) {
        [self removeFromSuperview];
    }
}

- (void)cancelAction
{
    if (self.cancleActionBlock) {
        self.cancleActionBlock();
    }
    if (!self.remainOnClick) {
        [self removeFromSuperview];
    }
}

- (void)dealloc {
}

@end
