//
//  RDSBaseViewController.m
//  SmartLightForBigFish
//
//  Created by coderYK on 2017/8/7.
//  Copyright © 2017年 RD-iOS. All rights reserved.
//

#import "RDSBaseViewController.h"
#import "NSString+verify.h"
#import "NSString+hanzi.h"
#import "RDSNavPushHelper.h"
#import "UIImage+Extension.h"


@interface RDSBaseViewController ()

@property (nonatomic, copy) void(^contactGetResultBlock)(NSString *result); // ** 联系方式获取的回调*/
@property (nonatomic, strong) UIBarButtonItem *space;
@property (nonatomic, copy) NSString *orgMsg;
@property (nonatomic, assign) BOOL isCheckingOnline;// 检查VCC是否在线
@property (nonatomic, assign) UInt16 checkingAddr;
@end

@implementation RDSBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RDSViewBgColor;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.navigationController.navigationBar.frame = CGRectMake(0,kSTATUSBAR_HEIGHT, self.navigationController.navigationBar.frame.size.width,44);
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}



- (BOOL)isActive{
    
    
//    __block BOOL result = NO;
//    dispatch_sync(dispatch_get_main_queue(), ^{
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);// 主线程中异步转同步 防止卡死
//        // 需要在主线程执行的代码
//        result = (self.isViewLoaded && self.view.window);
//        dispatch_semaphore_signal(sema);
//
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    });
    
    return YES;
}



#pragma mark - Nav
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (self.navigationController != nil) {
        [self.navigationController pushViewController:viewController animated:animated];
    }
    else{
        [self.tabBarController.navigationController pushViewController:viewController animated:animated];
    }
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated{
    
    if (self.navigationController != nil) {
        return [self.navigationController popViewControllerAnimated:animated];
    }
    else{
        return [self.tabBarController.navigationController popViewControllerAnimated:animated];
    }
}

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (self.navigationController != nil) {
        return [self.navigationController popToViewController:viewController animated:animated];
    }
    else{
        return [self.tabBarController.navigationController popToViewController:viewController animated:animated];
    }
}

- (void)popToRootViewControllerAnimated:(BOOL)animated{
    if (self.navigationController != nil) {
        [self.navigationController popToRootViewControllerAnimated:animated];
    }
    else{
        [self.tabBarController.navigationController popToRootViewControllerAnimated:animated];
    }
}

- (void)rds_centerPushViewController:(UIViewController *)viewController {
    
    [RDSNavPushHelper sharedInstance].viewControllerToPush = viewController;
    //    [self.sideMenuViewController hideMenuViewController];
}

#pragma mark -

- (void)updateNavigationBarColor:(UIColor *)color {

    // 重置背景和阴影颜色
    //navigation标题文字颜色
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor whiteColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:22]};
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];
//        [barApp configureWithOpaqueBackground];
        barApp.backgroundColor = color;
        barApp.shadowColor = UIColor.clearColor;
        barApp.titleTextAttributes = dic;
        self.navigationController.navigationBar.scrollEdgeAppearance = barApp;
        self.navigationController.navigationBar.standardAppearance = barApp;
    }else{
        //背景色
        self.navigationController.navigationBar.barTintColor = color;
        self.navigationController.navigationBar.titleTextAttributes = dic;
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    }
    //不透明
    self.navigationController.navigationBar.translucent = NO;
    //navigation控件颜色
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)clearColorNavBar{
    //navigation标题文字颜色
    NSDictionary *dic = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                          NSFontAttributeName:[UIFont systemFontOfSize:24]};
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];
        barApp.backgroundColor = [UIColor clearColor];
        barApp.titleTextAttributes = dic;
        barApp.backgroundEffect = nil;
        barApp.shadowColor = nil;
        self.navigationController.navigationBar.scrollEdgeAppearance = nil;
        self.navigationController.navigationBar.standardAppearance = barApp;
    }else{
        self.navigationController.navigationBar.titleTextAttributes = dic;
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    }
    //透明
    self.navigationController.navigationBar.translucent = YES;
    //navigation控件颜色
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

// 圆角边框
- (void)rds_setupArcBorderView:(UIView *)view {
    
    [self rds_setupArcBorderView:view withCornerRadius:5];
}

- (void)rds_setupArcBorderView:(UIView *)view withCornerRadius:(CGFloat)radius {
    
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
    view.layer.borderWidth = 0.6;
    view.layer.borderColor = [UIColor lightGrayColor].CGColor;
}

- (void)rds_setupArcView:(UIView *)view {
    
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
}

- (BOOL)getPhoneNo:(NSString *)string {
    
    BOOL isPhoneNo = NO;
    if ([string hasPrefix:@"+"]) {
        string = [string substringFromIndex:3];
    }
    
    string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
    if ([string isPhoneNum]) {
        isPhoneNo = YES;
        BLOCK_SAFE_RUN(_contactGetResultBlock, string)
    } else {
        [RDSHudShower showErrorWithStatus:@"手机号码格式不正确"];
        isPhoneNo = NO;
        BLOCK_SAFE_RUN(_contactGetResultBlock, nil)
    }
    return isPhoneNo;
}

- (UIButton *)rds_addSaveBtnOnNavBarWithAction:(SEL)action {
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:RDSThemeColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    saveBtn.frame = CGRectMake(0, 0, 44, 30);
    [saveBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:saveBtn]];
    return saveBtn;
}

- (void)rds_addAddBtnOnNavBarWithAction:(SEL)action {
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //addBtn.tintColor = [UIColor darkTextColor];
    [addBtn setImage:[[UIImage imageNamed:@"icon_add"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(0, 0, 44, 30);
    //addBtn.layer.cornerRadius = 5;
    //addBtn.layer.borderWidth = 1;
    //addBtn.layer.borderColor = [UIColor grayColor].CGColor;
    [addBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:addBtn]];
}

- (UIBarButtonItem *)rds_barButtonItemWithImage:(NSString *)imageName andAction:(SEL)action {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tintColor = [UIColor whiteColor];//RDS_DARK_TEXT_COLOR;
    UIImage *btnImg = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [btn setImage:btnImg forState:UIControlStateNormal];
    [btn setImage:btnImg forState:UIControlStateHighlighted];
    [btn sizeToFit];
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return barItem;
}

- (void)rds_alertMessage:(NSString *)message {
    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:message
                                                                message:@""
                                                         preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
    }];
    
    [ac addAction:okAction];
    
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)rds_alertMessage:(NSString *)message doneAction:(void(^)(void))doneActionBlock {
    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示"
                                                                message:message
                                                         preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
        if (doneActionBlock) {
            doneActionBlock();
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        
    }];
    
    [ac addAction:okAction];           // A
    [ac addAction:cancelAction];       // B
    
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)rds_alertInputTitle:(NSString *)title msg:(NSString *)msg placeholder:(NSString *)placeholder doneAction:(void(^)(NSString *name))doneActionBlock{
    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:title
                                                                message:msg
                                                         preferredStyle:UIAlertControllerStyleAlert];
    _orgMsg = msg;
    // 添加文本框
    [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = placeholder;
        //textField.text = placeholder;
        [textField addTarget:self action:@selector(p_alertInputDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        //textField.keyboardType = UIKeyboardTypeASCIICapable;
        
//        if ([title isEqualToString:@"身高"] || [title isEqualToString:@"体重"]) {
//            textField.keyboardType = UIKeyboardTypeNumberPad;
//        }
    }];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        NSString *string = ac.textFields.firstObject.text;
        if (doneActionBlock) {
            doneActionBlock(string);
        }
    }];
    
    okAction.enabled = YES;
    [ac addAction:cancelAction];
    [ac addAction:okAction];
    
    // 修改按钮字体颜色
    [cancelAction setValue:RDSBlackColor forKey:@"_titleTextColor"];
//    [okAction setValue:RDSThemeColor forKey:@"_titleTextColor"];
    
    
    // 修改标题字体颜色
    if(!kNULLString(title)){
        NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:title];
        [titleAtt addAttribute:NSForegroundColorAttributeName value:kDarkTextColor range:NSMakeRange(0, title.length)];
        [titleAtt addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(0, title.length)];
        [ac setValue:titleAtt forKey:@"attributedTitle"];
    }
    
    
    
    // 修改msg字体颜色
    if (!kNULLString(msg)) {
        NSMutableAttributedString *msgAtt = [[NSMutableAttributedString alloc] initWithString:msg];
        [msgAtt addAttribute:NSForegroundColorAttributeName value:kDarkTextColor range:NSMakeRange(0, msg.length)];
        [msgAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, msg.length)];
        [ac setValue:msgAtt forKey:@"attributedMessage"];
    }
    
    
    
    
    // 3.显示控制器
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)p_alertInputDidChange:(UITextField *)sender{
    
    UIAlertController *ac = (UIAlertController *)self.presentedViewController;
    if (ac) {
        UIAlertAction *okAction = ac.actions.lastObject;
        NSString *string = ac.textFields.firstObject.text;
        NSString *msg = _orgMsg;
        NSUInteger length = [string rds_countStringByteLength];
        
        if ([ac.title isEqualToString:@"身高"]) {
            
            NSString *str = string;
            if (str.intValue < 20) {
                okAction.enabled = NO;
                ac.message = @"";
            }else if (str.intValue > 300){
                okAction.enabled = NO;
                ac.message = @"";
            }
            else{
                okAction.enabled = YES;
                ac.message = @"";
            }
            return;
        }
        else if ([ac.title isEqualToString:@"体重"]){
            NSString *str = string;
            if (str.intValue < 2) {
                okAction.enabled = NO;
                ac.message = @"";
            }else if (str.intValue > 300){
                okAction.enabled = NO;
                ac.message = @"";
            }
            else{
                okAction.enabled = YES;
                ac.message = @"";
            }
            return;
        }
        
        if (length >0 && length <= 20) {
            okAction.enabled = YES;
            ac.message = msg;
        }
        else if (length == 0){
            okAction.enabled = YES;
            ac.message = msg;
        }
        else if (length > 20){
            okAction.enabled = YES;
            ac.message = _orgMsg;//@"名称字数超过限制（10个中文字符或20个英文字符）";
            ac.textFields.firstObject.text = [string substringToIndex:length-1];
        }
    }
}


- (void)rds_alertTimePickerTitle:(NSString *)title date:(NSDate *)date doneAction:(void (^)(NSDate *))doneActionBlock{
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeTime;
    if (@available(iOS 13.4, *)) {
        datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
    } else {
        // Fallback on earlier versions
    }
    
    // 设置当前显示时间
    [datePicker setDate:date animated:YES];
    
    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n"
                                                                message:nil
                                                         preferredStyle:UIAlertControllerStyleAlert];
    
    [ac.view addSubview:datePicker];
    
    // 居中
    [datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ac.view);
        make.centerY.equalTo(ac.view).with.offset(-22);
    }];
    
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"DONE" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"HH:mm"];
        NSString *dateString = [dateFormat stringFromDate:datePicker.date];
        NSLog(@"%@",dateString);
        
        if (doneActionBlock) {
            doneActionBlock(datePicker.date);
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"CANCEL" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        
    }];
    
    [ac addAction:okAction];
    [ac addAction:cancelAction];
    
    [self presentViewController:ac animated:YES completion:nil];
    
}

- (void)rds_showControllerOnWindow {
    
    //    RDSSideMenuViewController *rootVC = (RDSSideMenuViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    //    [rootVC.contentViewController addChildViewController:self];
    [[UIApplication sharedApplication].keyWindow addSubview:self.view];
}

- (void)rds_dismissControllerOnWindow {
    
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (NSString *)rds_getHexNameFromString:(NSString *)name withByte:(NSUInteger)byte {
    
    NSString *hexName = [self rds_stringTohexString:name];
    int offset = (int)(byte*2 - hexName.length);
    for (int i = 0; i < offset; i++) {
        hexName = [NSString stringWithFormat:@"%@0",hexName];
    }
    return hexName;
}

- (NSString *)rds_stringTohexString:(NSString *)string {
    
    NSMutableString *strM = [NSMutableString string];
    for (int i=0; i<string.length; i++) {
        NSString *code = [NSString stringWithFormat:@"%02x", [string characterAtIndex:i]];
        [strM appendString:code];
    }
    return strM;
}

- (void)rds_showJuHuaOnWindow {
    
    if (self.juHua == nil) {
        UIActivityIndicatorView *juHua = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.juHua = juHua;
        self.juHua.hidesWhenStopped = YES;
        [[UIApplication sharedApplication].keyWindow addSubview:self.juHua];
        self.juHua.center = [UIApplication sharedApplication].keyWindow.center;
    }
    [self.juHua startAnimating];
}

- (NSArray<UIBarButtonItem *> *)rds_barItemsWithImage:(UIImage *)image target:(id)target andSelector:(SEL)selector needAdjustSpace:(BOOL)need {
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    //    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setBackgroundImage:image forState:UIControlStateNormal];
    //    [button sizeToFit];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    if (need) {
        return @[self.space, item];
    }
    return @[item];
}

- (UIBarButtonItem *)space {
    
    if (_space == nil) {
        _space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                               target:nil action:nil];
        _space.width = isIOS11? -10 : -5;
    }
    return _space;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
