//
//  PNSBuildModelUtils.m
//  XinMai
//
//  Created by mac on 2020/10/19.
//

#import "PNSBuildModelUtils.h"
#import "UIImage+Common.h"
#import "BottomThirdView.h"
#import <ATAuthSDK/ATAuthSDK.h>

@implementation PNSBuildModelUtils


+ (CGFloat)safeAreaInsetsBottom {
    // 根据安全区域判断
    if (@available(iOS 11.0, *)) {
        CGFloat height = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom;
        return height;
    } else {
        return 0;
    }
}


+ (BOOL)isBlankString:(NSString *)aStr {
    if (!aStr ) {
        return YES;
    }
    if([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if(!aStr.length) {
        return YES;
    }
    if(aStr == nil) {
        return YES;
    }
    if(aStr == NULL) {
        return YES;
    }
    if ([aStr isEqualToString:@"NULL"]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
        
    }
    return NO;
}

+ (BOOL)isBlankArr:(NSArray *)arr{
    if (!arr) {
        return YES;
    }
    if (![arr isKindOfClass:[NSArray class]]) {
        return YES;
    }
    if ([arr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!arr.count) {
        return YES;
    }
    if (arr == nil || arr == NULL) {
        return YES;
    }
    return NO;
}

+ (nullable UIColor *)colorWithHexString:(NSString *)hexString {
    return [self colorWithHexString:hexString alpha:1.0];
}

+ (nullable UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
    if ([hexString hasPrefix:@"#"]) {
        hexString = [hexString substringFromIndex:1];
    }
    if ([[hexString lowercaseString] hasPrefix:@"0x"]) {
        hexString = [hexString substringFromIndex:2];
    }
    if ([hexString length] != 6) {
        return nil;
    }
    
    NSScanner *scanner = [[NSScanner alloc] initWithString:hexString];
    unsigned hexValue = 0;
    if ([scanner scanHexInt:&hexValue] && [scanner isAtEnd]) {
        return [self colorWithHex:hexValue alpha:alpha];
    }
    
    return nil;
}

+ (nullable UIColor *)colorWithHex:(unsigned)hex {
    return [self colorWithHex:hex alpha:1.0];
}

+ (nullable UIColor *)colorWithHex:(unsigned)hex alpha:(CGFloat)alpha {
    int r = ((hex & 0xFF0000) >> 16);
    int g = ((hex & 0x00FF00) >>  8);
    int b = ( hex & 0x0000FF)       ;
    return [UIColor colorWithRed:((CGFloat)r / 255)
                        green:((CGFloat)g / 255)
                         blue:((CGFloat)b / 255)
                        alpha:alpha];
}

///全屏 竖屏
+ (TXCustomModel *)buildSheetPortraitModelWithLogoImageName:(NSString *)logoImageName registerPrivacyUrl:(NSString *)registerPrivacyUrl protectPrivacyUrl:(NSString *)protectPrivacyUrl registerTitle:(NSString *)registerTitle protectTitle:(NSString *)protectTitle sloganText:(NSString *)sloganText loginBtnText:(NSString *)loginBtnText loginBtnColor:(NSString *)loginBtnColor actionBlock:(void (^_Nullable)(PNSOtherActionType type))actionBlock {
    TXCustomModel *model = [[TXCustomModel alloc] init];
    model.supportedInterfaceOrientations = UIInterfaceOrientationMaskPortrait;
    NSDictionary *attributes = @{
        NSForegroundColorAttributeName : [UIColor colorWithRed:153.f/255.f green:153.f/255.f blue:153.f/255.f alpha:1.0],
        NSFontAttributeName : [UIFont systemFontOfSize:12.0]
    };
    if ([self isBlankString:logoImageName]) {
        logoImageName = @"login_logo_icon";
    }
    model.navColor = [UIColor clearColor];
    model.navTitle = [[NSAttributedString alloc] initWithString:@""];
    model.hideNavBackItem = NO;
    model.navBackImage = [UIImage imageNamed:@"app_close_btn"];
    model.changeBtnIsHidden = NO;
    // logo
    model.logoImage = [UIImage imageNamed:logoImageName];
    model.logoFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.size.width = 155;
        frame.size.height = 148;
        frame.origin.y = frame.origin.y;
        frame.origin.x = (superViewSize.width - 155) * 0.5;
        return frame;
    };
    
    //sloga
    if ([self isBlankString:sloganText]) {
        sloganText = @"阿里云提供认证服务";
    }
    model.sloganText =  [[NSAttributedString alloc] initWithString:@"阿里云提供认证服务" attributes:attributes];
    model.sloganFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y =  frame.origin.y - 30;
        return frame;
    };
    model.sloganIsHidden = YES;
    
    model.numberFont = [UIFont boldSystemFontOfSize:30.0];
    
    model.numberFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y =  frame.origin.y - 30;
        return frame;
    };
    
    NSDictionary *loginAttributes = @{
        NSForegroundColorAttributeName : [UIColor whiteColor],
        NSFontAttributeName : [UIFont boldSystemFontOfSize:18.0]
    };
    
    if ([self isBlankString:loginBtnText]) {
        loginBtnText = @"本机号码一键登录";
    }
    model.loginBtnText = [[NSAttributedString alloc] initWithString:loginBtnText attributes:loginAttributes];
    
    UIImage *unloginImage = [UIImage imageNamed:@"one_click_bg"];
    UIImage *loginImage = [UIImage imageNamed:@"one_click_bg"];
//    UIImage *unloginImage = [UIImage dh_imageWithColor:[UIColor colorWithRed:116.f/255.f green:180.f/255.f blue:247.f/255.f alpha:1.0] size:CGSizeMake([UIScreen mainScreen].bounds.size.width - 60.f, 44.f)];
    UIColor *loginColor = [UIColor colorWithRed:67/255.f green:121.f/255.f blue:255.f/255.f alpha:1.0];
    if (![self isBlankString:loginBtnColor]) {
        loginColor = [self colorWithHexString:loginBtnColor];
        UIColor *unloginColor = [loginColor colorWithAlphaComponent:0.6];
    /*    unloginImage = [UIImage dh_imageWithColor:unloginColor size:CGSizeMake([UIScreen mainScreen].bounds.size.width - 60.f, 44.f)]*/;
    }
//    UIImage *loginImage = [UIImage dh_imageWithColor:loginColor size:CGSizeMake([UIScreen mainScreen].bounds.size.width - 60.f, 44.f)];
//    loginImage = [loginImage dh_getCornerRadius:22.f];
//    unloginImage = [unloginImage dh_getCornerRadius:22.f];
    NSArray *loginBtnBgImgs = @[loginImage,unloginImage,loginImage];
    
    model.loginBtnBgImgs = loginBtnBgImgs;
    model.loginBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y = frame.origin.y - 45;
        frame.size.height = 80;
        frame.origin.x = (screenSize.width - 334.55) * 0.5;
        frame.size.width = 334.55;
        return frame;
    };
    
    NSDictionary *changeAttributes = @{
        NSForegroundColorAttributeName : [UIColor colorWithRed:153.f/225.f green:153.f/225.f blue:153.f/225.f alpha:1.0],
        NSFontAttributeName : [UIFont systemFontOfSize:18.0]
    };
    model.changeBtnTitle = [[NSAttributedString alloc] initWithString:@"其他手机号码登录" attributes:changeAttributes];
    
    model.changeBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y = frame.origin.y - 45;
        frame.origin.x = 32.f;
        frame.size.width = screenSize.width - 64.f;
        return frame;
    };
    model.backgroundImage = [UIImage imageNamed:@"ali_login_bg"];
    model.backgroundImageContentMode = UIViewContentModeScaleAspectFill;
    model.checkBoxImageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    model.checkBoxVerticalCenter = NO;
    if ([self isBlankString:registerPrivacyUrl]) {
        registerPrivacyUrl = @"REGISTER";
    }
    if ([self isBlankString:protectPrivacyUrl]) {
        protectPrivacyUrl = @"PROTECT";
    }
    if ([self isBlankString:registerTitle]) {
        registerTitle = @"《注册协议》";
    }
    if ([self isBlankString:protectTitle]) {
        protectTitle = @"《隐私保护政策》";
    }
    model.privacyOne = @[protectTitle, protectPrivacyUrl];
    model.privacyTwo = @[registerTitle, registerPrivacyUrl];
    model.privacyOperatorPreText = @"《";
    model.privacyOperatorSufText = @"》";
    model.privacyPreText = @"登录";
    model.privacySufText = @"并授权乐学喵教育获得本机号码";
    model.privacyAlignment = NSTextAlignmentCenter;
    
    model.privacyColors = @[[UIColor colorWithRed:60.f/255.f green:60.f/255.f blue:60.f/255.f alpha:1.0],loginColor];
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
    animation.values = @[@0,@(-10),@10,@(-10),@5,@(-5),@0];
    animation.keyTimes = @[@0,@(1/6.0),@(2/6.0),@(3/6.0),@(4/6.0),@(5/6.0),@1];
    animation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    animation.duration = 0.5;
    
    model.checkboxAnimation = animation;
    
    model.privacyNavBackImage = [UIImage imageNamed:@"AppNavBack"];
    
    
//    UILabel *tipLabel = [[UILabel alloc] init];
//    tipLabel.text = @"未注册的用户验证通过后将自动注册";
//    tipLabel.font = [UIFont systemFontOfSize:12.0];
//    tipLabel.textAlignment = NSTextAlignmentCenter;
//    tipLabel.textColor = [UIColor colorWithRed:153.f/255.f green:153.f/255.f blue:153.f/255.f alpha:1.0];

    
    BottomThirdView *thirdView = [BottomThirdView shareThirdView];
    thirdView.bounds = CGRectMake(0, 0, 300, 130);
    thirdView.wechatActionBlock = ^{
        if (actionBlock) {
            actionBlock(PNSOtherActionTypeWechat);
        }
    };
    thirdView.qqActionBlock = ^{
        if (actionBlock) {
            actionBlock(PNSOtherActionTypeQQ);
        }
    };
//    thirdView.passwordActionBlock = ^{
//        if (actionBlock) {
//            actionBlock(PNSOtherActionTypePassword);
//        }
//    };
    model.customViewBlock = ^(UIView * _Nonnull superCustomView) {
        [superCustomView addSubview:thirdView];
    };
    model.customViewLayoutBlock = ^(CGSize screenSize, CGRect contentViewFrame, CGRect navFrame, CGRect titleBarFrame, CGRect logoFrame, CGRect sloganFrame, CGRect numberFrame, CGRect loginFrame, CGRect changeBtnFrame, CGRect privacyFrame) {
//        tipLabel.frame = CGRectMake(CGRectGetMinX(loginFrame),
//                                   CGRectGetMaxY(loginFrame) + 25,
//                                   CGRectGetWidth(loginFrame),
//                                   30);
        thirdView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 300) * 0.5,
                                   CGRectGetMinY(privacyFrame) - 130,
                                   300,
                                   130);
    };
     
    return model;
}

///底部弹窗
+ (TXCustomModel *)buildSheetAlertModelWithLogoImageName:(NSString *)logoImageName registerPrivacyUrl:(NSString *)registerPrivacyUrl protectPrivacyUrl:(NSString *)protectPrivacyUrl checkBoxImage:(NSString *)checkBoxImage sloganText:(NSString *)sloganText loginBtnText:(NSString *)loginBtnText changeBtnTitle:(NSString *)changeBtnTitle loginBtnBgImgs:(NSArray *)loginBtnBgImgs{
    TXCustomModel *model = [[TXCustomModel alloc] init];
    model.supportedInterfaceOrientations = UIInterfaceOrientationMaskPortrait;
    model.alertCornerRadiusArray = @[@10, @0, @0, @10];
    model.alertBlurViewAlpha = 0.5;
    model.alertTitleBarColor = [UIColor whiteColor];
    NSDictionary *attributes = @{
        NSForegroundColorAttributeName : [UIColor colorWithRed:153.f/225.f green:153.f/225.f blue:153.f/225.f alpha:1.0],
        NSFontAttributeName : [UIFont systemFontOfSize:12.0]
    };
    model.alertTitle = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];
    model.alertCloseImage = [UIImage imageNamed:@"login_close"];
    if ([self isBlankString:logoImageName]) {
        logoImageName = @"default_logo";
    }
    model.logoImage = [UIImage imageNamed:logoImageName];
    model.alertCloseItemIsHidden = NO;
    if ([self isBlankString:registerPrivacyUrl]) {
        registerPrivacyUrl = @"REGISTER";
    }
    if ([self isBlankString:protectPrivacyUrl]) {
        protectPrivacyUrl = @"PROTECT";
    }
    model.privacyOne = @[@"《注册协议》", registerPrivacyUrl];
    model.privacyTwo = @[@"《隐私保护政策》", protectPrivacyUrl];
    UIImage *unselectImage = [UIImage dh_imageWithColor:[UIColor whiteColor] size:CGSizeMake(1, 1.f)];
    UIImage *selectImage = [UIImage dh_imageWithColor:[UIColor whiteColor] size:CGSizeMake(1, 1.f)];
    model.checkBoxImages = @[unselectImage,selectImage];
    model.checkBoxIsChecked = YES;
    model.checkBoxIsHidden = YES;
    model.privacyOperatorPreText = @"《";
    model.privacyOperatorSufText = @"》";
    model.privacyPreText = @"点击“登录”即同意";
    model.privacySufText = @"并使用本机号码登录";
    model.privacyAlignment = NSTextAlignmentCenter;
    //255,93,43
    model.privacyColors = @[[UIColor colorWithRed:153.f/225.f green:153.f/225.f blue:153.f/225.f alpha:1.0],[UIColor colorWithRed:255.f/225.f green:93.f/225.f blue:43.f/225.f alpha:1.0],[UIColor colorWithRed:255.f/225.f green:93.f/225.f blue:43.f/225.f alpha:1.0]];
    model.privacyNavBackImage = [UIImage imageNamed:@"appBack"];
     
    NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc]init];
    paragrapStyle.alignment = NSTextAlignmentCenter;//文字居中属性
    NSString *tipTitle = @"我们会对您的信息严格保密";
    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:tipTitle];
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:153.f/225.f green:153.f/225.f blue:153.f/225.f alpha:1.0] range:NSMakeRange(0, tipTitle.length)];
    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, tipTitle.length)];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    if ([self isBlankString:checkBoxImage]) {
        checkBoxImage = @"checkBoxImages";
    }
    attch.image = [UIImage imageNamed:checkBoxImage];
    // 创建带有图片的富文本
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attch]];
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
    [attriStr insertAttributedString:string atIndex:0];
    
    [attriStr addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, attriStr.length)];
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.attributedText = attriStr;
    
    model.customViewBlock = ^(UIView * _Nonnull superCustomView) {
        [superCustomView addSubview:tipLabel];
    };
    model.customViewLayoutBlock = ^(CGSize screenSize, CGRect contentViewFrame, CGRect navFrame, CGRect titleBarFrame, CGRect logoFrame, CGRect sloganFrame, CGRect numberFrame, CGRect loginFrame, CGRect changeBtnFrame, CGRect privacyFrame) {
        tipLabel.frame = CGRectMake(CGRectGetMinX(loginFrame),
                                   CGRectGetMinY(privacyFrame) - 20,
                                   CGRectGetWidth(loginFrame),
                                   20);
    };
    model.contentViewFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.size.width = superViewSize.width;
        frame.size.height =  385 + [self safeAreaInsetsBottom];
        frame.origin.x = 0;
        frame.origin.y = superViewSize.height - frame.size.height;
        return frame;
    };
    model.logoFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.size.width = 55;
        frame.size.height = 55;
        frame.origin.y = 0;
        frame.origin.x = (superViewSize.width - 55) * 0.5;
        return frame;
    };
    if ([self isBlankString:sloganText]) {
        sloganText = @"本机号码一键登录";
    }
    model.sloganText = [[NSAttributedString alloc] initWithString:sloganText attributes:attributes];
    model.sloganFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y =  55 + 15;
        return frame;
    };
    model.numberColor = [UIColor colorWithRed:51.f/225.f green:51.f/225.f blue:51.f/225.f alpha:1.0];
    model.numberFont = [UIFont boldSystemFontOfSize:18.f];
    model.numberFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y = 55 + 20 + 18;
        return frame;
    };
    NSDictionary *loginAttributes = @{
        NSForegroundColorAttributeName : [UIColor whiteColor],
        NSFontAttributeName : [UIFont systemFontOfSize:16.0]
    };
    if ([self isBlankString:loginBtnText]) {
        if ([self isBlankArr:loginBtnBgImgs]) {
            loginBtnText = @"本机号码一键登录";
        }else{
            loginBtnText = @"";
        }
    }
    model.loginBtnText = [[NSAttributedString alloc] initWithString:loginBtnText attributes:loginAttributes];
    UIImage *loginImage = [UIImage dh_imageWithColor:[UIColor colorWithRed:253/225.f green:90.f/225.f blue:39.f/225.f alpha:1.0] size:CGSizeMake([UIScreen mainScreen].bounds.size.width - 70.f, 44.f)];
    loginImage = [loginImage dh_getCornerRadius:22.f];
    if ([self isBlankArr:loginBtnBgImgs]) {
        loginBtnBgImgs = @[loginImage,loginImage,loginImage];
    }else{
        loginBtnBgImgs = @[[UIImage imageNamed:[loginBtnBgImgs firstObject]],[UIImage imageNamed:[loginBtnBgImgs firstObject]],[UIImage imageNamed:[loginBtnBgImgs firstObject]]];
    }
    model.loginBtnBgImgs = loginBtnBgImgs;
    model.loginBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y = 55 + 10 + 18 + 35 + 30;
        frame.size.height = 44.f;
        frame.origin.x = (superViewSize.width - 300) * 0.5;
        frame.size.width = 300;
        return frame;
    };
    
    NSDictionary *changeAttributes = @{
      NSForegroundColorAttributeName : [UIColor colorWithRed:102/225.f green:102.f/225.f blue:102.f/225.f alpha:1.0],NSFontAttributeName : [UIFont systemFontOfSize:12.0]
        };
    model.changeBtnIsHidden = NO;
    if ([self isBlankString:changeBtnTitle]) {
        changeBtnTitle = @"其他方式登录";
    }
    model.changeBtnTitle = [[NSAttributedString alloc] initWithString:changeBtnTitle attributes:changeAttributes];
    model.changeBtnFrameBlock = ^CGRect(CGSize screenSize, CGSize superViewSize, CGRect frame) {
        frame.origin.y = 55 + 10 + 18 + 35 + 30 + 15 + 44;
        return frame;
    };
    return model;
}

+ (UIImage *)getImageWithColor:(UIColor *)color {
    
    CGSize size = CGSizeMake(1, 1);
    CGRect rect = (CGRect){CGPointZero, size};
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, color.CGColor);
    CGContextFillRect(ctx, rect);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
