//
//  RDSTabbarController.m
//  HealthPot
//
//  Created by Rayson on 2019/7/10.
//  Copyright © 2019 RDIOT. All rights reserved.
//

#import "RDSTabbarController.h"
#import "UIImage+Extension.h"


#import "RDSHomeVC.h"
#import "RDSRoomVC.h"
#import "RDSFindVC.h"
#import "RDSMyVC.h"

#import "RDSResetDeviceVC.h"
#import "RDSAddView.h"
#import "SPAlertController.h"
#import "PopView.h"

#define TabBarVC              @"vc"                //--tabbar对应的视图控制器
#define TabBarTitle           @"title"             //--tabbar标题
#define TabBarImage           @"image"             //--未选中时tabbar的图片
#define TabBarSelectedImage   @"selectedImage"     //--选中时tabbar的图片
#define TabBarItemBadgeValue  @"badgeValue"        //--未读个数
#define TabBarCount 3                              //--tabbarItem的个数

typedef NS_ENUM(NSInteger,RDSTabType) {
    
    // --这里的顺序，决定了 tabbar 从左到右item的显示顺序
    RDSTabTypeHome,     // 首页
    RDSTabTypeRoom,     // 房间
//    RDSTabTypeAdd,      // 添加（只作占位用）
//    RDSTabTypeFind,     // 资讯
    RDSTabTypeMy,       // 设置
};

@interface RDSTabbarController ()

@property (nonatomic, strong) NSDictionary *configs;
@property (nonatomic, strong) RDSHomeVC *homeVC;
@property (nonatomic, strong) RDSRoomVC *roomVC;
@property (nonatomic, strong) RDSFindVC *findVC;
@property (nonatomic, strong) RDSMyVC *myVC;

@property (nonatomic, strong) RDSAddView *addView;
@property (nonatomic, assign) int curIndex;// 记录当前tabbar item 下标，用于push添加房间页面

@end

@implementation RDSTabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    // 取出tabbar顶部分割线
    if (@available(iOS 13.0, *)) {
        
        UITabBarAppearance *appearance = [UITabBarAppearance new];
        [appearance configureWithOpaqueBackground];
        
        UIColor *color = [UIColor whiteColor];
        appearance.shadowImage = [UIImage rds_imageWithColor:color];
        appearance.backgroundColor = color;
        
        self.tabBar.standardAppearance = appearance;
        /// 这里有点区别。导航栏是iOS13开始。这里是iOS15才有的
        if (@available(iOS 15.0, *)) {
            self.tabBar.scrollEdgeAppearance = self.tabBar.standardAppearance;
        }
    }

    
    [self setUpSubNav];
    // 中间+加号按钮
//    [self addMidButton];
}


- (NSArray*)tabbars{
    
    NSMutableArray *items = [[NSMutableArray alloc] init];
    for (NSInteger tabbar = 0; tabbar < TabBarCount; tabbar++) {
        [items addObject:@(tabbar)];
    }
    return items;
}

- (void)setUpSubNav {
    
    NSMutableArray *vcArray = [[NSMutableArray alloc] init];
    [self.tabbars enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSNumber *tabbar = obj;
        NSDictionary * item =[self vcInfoForTabType:[tabbar integerValue]];
        NSString *vcName = item[TabBarVC];
        NSString *title  = item[TabBarTitle];
        NSString *imageName = item[TabBarImage];
        NSString *imageSelected = item[TabBarSelectedImage];
        Class clazz = NSClassFromString(vcName);
        UIViewController *vc = [[clazz alloc] init];
        if ([vc isKindOfClass:[RDSHomeVC class]]) {
            self.homeVC = (RDSHomeVC *)vc;
        }
        else if ([vc isKindOfClass:[RDSRoomVC class]]){
            self.roomVC = (RDSRoomVC *)vc;
        }
        else if ([vc isKindOfClass:[RDSFindVC class]]){
            self.findVC = (RDSFindVC *)vc;
        }
        else if ([vc isKindOfClass:[RDSMyVC class]]){
            self.myVC = (RDSMyVC *)vc;
        }
        
        vc.hidesBottomBarWhenPushed = NO;
        RDSNavController *nav = [[RDSNavController alloc] initWithRootViewController:vc];
        nav.tabBarItem = [[UITabBarItem alloc] initWithTitle:title
                                                       image:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                               selectedImage:[[UIImage imageNamed:imageSelected] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        
        // 设置TabBar上 字体颜色
        self.tabBar.tintColor = RGB(51, 51, 51);
        
        nav.tabBarItem.tag = idx;
        NSInteger badge = [item[TabBarItemBadgeValue] integerValue];
        if (badge) {
            nav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd",badge];
        }
        
        // 隐藏中间按钮 和发现页面
//        if(idx == 2){
//            nav.tabBarItem.enabled = NO;
//        }
 
        [vcArray addObject:nav];
    }];
    self.viewControllers = [NSArray arrayWithArray:vcArray];
    
}

// 中间按钮
-(void)addMidButton{
        dispatch_async(dispatch_get_main_queue(), ^{
            CGFloat height = 60;//self.tabBar.frame.size.height - [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
            UIButton * shot = [[UIButton alloc] initWithFrame:CGRectMake((self.tabBar.frame.size.width - height)*0.5, -5, height, height)];
            [shot addTarget:self action:@selector(showMidBtn:) forControlEvents:UIControlEventTouchUpInside];
            [shot setBackgroundImage:[UIImage imageNamed:@"icon_tab_add_sel"] forState:UIControlStateNormal];
            shot.layer.cornerRadius = height * 0.5;
            [self.tabBar addSubview:shot];
        });
    }

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
//    if (item.tag != 2) {
//        [self hiddenAddView];
//    }
    _curIndex = (int)item.tag;
}

// 显示添加房间、场景按钮
- (void)showMidBtn:(UIButton *)sender{
    
    if(self.addView.isHidden){
        self.addView.hidden = NO;
        
        // 渐变动画
        [UIView animateWithDuration:0.2 animations:^{
            self.addView.alpha = 1;
        }];
    }
}

- (void)hiddenAddView{
    if(!self.addView.isHidden){
        // 渐变动画
        [UIView animateWithDuration:0.2 animations:^{
            self.addView.alpha = 0;
        } completion:^(BOOL finished) {
            self.addView.hidden = YES;
        }];
    }
}

- (RDSAddView *)addView{
    
    if(_addView == nil){
        CGFloat heihgt = SCREEN_HEIGHT-self.tabBar.rds_height;
        _addView = [RDSAddView rds_loadViewFromNib];
        _addView.frame = CGRectMake(0, 0, SCREEN_WIDTH, heihgt);
        _addView.alpha = 0;
        _addView.hidden = YES;
        [[UIApplication sharedApplication].windows.firstObject addSubview:_addView];
        
        RDS_WEAKSELF(weakSelf)
        _addView.onHideBtnClick = ^{
            [weakSelf hiddenAddView];
        };
        _addView.onRoomBtnClick = ^{
            [weakSelf hiddenAddView];
            
            RDSResetDeviceVC *vc = [[RDSResetDeviceVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [weakSelf.viewControllers[weakSelf.curIndex] pushViewController:vc animated:YES];
        };
        
    }
    return _addView;
}

#pragma mark - VC
- (NSDictionary *)vcInfoForTabType:(RDSTabType)type{
    
    if (_configs == nil)
    {
        _configs = @{
                     @(RDSTabTypeHome) : @{
                             TabBarVC           : @"RDSHomeVC",
                             TabBarTitle        : @"首页",
                             TabBarImage        : @"icon_tab_home",
                             TabBarSelectedImage: @"icon_tab_home_sel",
                             TabBarItemBadgeValue: @(0)
                             },
                     @(RDSTabTypeRoom): @{
                             TabBarVC           : @"RDSRoomVC",
                             TabBarTitle        : @"房间",
                             TabBarImage        : @"icon_tab_room",
                             TabBarSelectedImage: @"icon_tab_room_sel",
                             TabBarItemBadgeValue: @(0)
                             },
//                     @(RDSTabTypeAdd): @{
//                             TabBarVC           : @"UIViewController",
//                             TabBarTitle        : @"",
//                             TabBarImage        : @"icon_tab_clear",
//                             TabBarSelectedImage: @"icon_tab_clear",
//                             TabBarItemBadgeValue: @(0)
//                             },
//                     @(RDSTabTypeFind): @{
//                             TabBarVC           : @"RDSFindVC",
//                             TabBarTitle        : @"发现",
//                             TabBarImage        : @"icon_tab_found",
//                             TabBarSelectedImage: @"icon_tab_found_sel",
//                             TabBarItemBadgeValue: @(0)
//                             },
                     @(RDSTabTypeMy)     : @{
                             TabBarVC           : @"RDSMyVC",
                             TabBarTitle        : @"我的",
                             TabBarImage        : @"icon_tab_me",
                             TabBarSelectedImage: @"icon_tab_me_sel",
                             TabBarItemBadgeValue: @(0)
                             }
                     };
        
    }
    return _configs[@(type)];
}

@end
