//
//  GMTabBarController.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/5.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "GMTabBarController.h"
#import "GMHomeController.h"
#import "GMGroupController.h"
#import "GMNavigationController.h"
#import "GMMessageController.h"
#import "ALRankContainerViewController.h"
#import "GMMeController.h"
#import "UIImage+Image.h"
#import "GMTabBar.h"
#import "GMTabBarIconManager.h"
#import "GMLaunchManager.h"
#import "ALFaceFittingAPI.h"
#import "AppDelegate.h"
#import "AppDelegate+ViewControl.h"

@interface GMTabBarController ()<UITabBarControllerDelegate>
{
    //游客模式不选中最后一个tabbar
    NSInteger _clickNum;
    //当前点击的tabbar
    NSInteger _selectNum;
}
@property (nonatomic, strong) GMMeController *meVc;
/** 刚进来的时候不需要选中 */
@property (nonatomic, assign) BOOL isNeedSelect;

@end

@implementation GMTabBarController
@synthesize viewControllers;
// 只会调用一次
//+ (void)load//ItemColor:(NSString *)color// normalColor:(NSString *)normalColor
//{
//    // 获取哪个类中UITabBarItem
//    UITabBarItem *item = [UITabBarItem appearanceWhenContainedIn:self, nil];
//    // 设置按钮选中标题的颜色:富文本:描述一个文字颜色,字体,阴影,空心,图文混排
//    // 创建一个描述文本属性的字典
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSForegroundColorAttributeName] = [UIColor blackColor];
//    [item setTitleTextAttributes:attrs forState:UIControlStateSelected];
//
//    // 设置字体尺寸:只有设置正常状态下,才会有效果
//    NSMutableDictionary *attrsNor = [NSMutableDictionary dictionary];
//    attrsNor[NSFontAttributeName] = [UIFont systemFontOfSize:20];
//    [item setTitleTextAttributes:attrsNor forState:UIControlStateNormal];
//}

#pragma mark - 生命周期方法

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 添加一点点延时，以保证SDK可以正常处理J
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[GMLoginManager shareInstance] appOpenJpushRegistration];
        });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.needLogPV = NO;
    self.delegate = self;
    // Do any additional setup after loading the view.
    // 1 添加子控制器(5个子控制器) -> 自定义控制器 -> 划分项目文件结构
    [self setupAllChildViewController];
    
    // 2 设置tabBar上按钮内容 -> 由对应的子控制器的tabBarItem属性
    [self setupAllTitleButton];
    
    // 3.自定义tabBar
    [self setupTabBar];

    [self changeToControllerAtIndex:0];
    //防止第一次选走tabbar的方法的时候还没有调用layoutSubView方法
    self.isNeedSelect = YES;
    //登录的操作
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelectMethod) name:LOGIN_SUCCESS_NOTIFICATION object:nil];
    
//    if (![GMLoginManager shareInstance].showLoginViewIfNeeded)
//        [ALFaceFittingAPI fetchFaceFittingDataWithCompletion:nil];
    
//    [self loadItemColor:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeMethod) name:@"genghuanIcon" object:nil];
    
    //如果tabbar有数组存储就更新
//    if ([GMLaunchManager shareManager].appConfigObject.tabs)
//    {
//        [self changeMethod];
//    }
}
#pragma mark - View Controllers

- (void)changeSelectMethod
{
    if ((_selectNum != _clickNum) && [GMLoginManager shareInstance].isVisitor == NO) {
        _selectNum = _clickNum;
        [self selectTab:_selectNum];
    }
}

- (void)changeMethod
{
    [self loadCachedTabBarUIData];
}

- (void)loadCachedTabBarUIData {
    [self updateTabInfoImages];
    [self updateTabInfoTitleColors];
}
// 首先判断本地是否下载完整的服务端配置的icons,然后根据icon的url是否为空去替换对应的tabbar的本地图片
// 不替换的图片也是用空字符串占位,以便动态配置任意位置的tabbar的icon
- (void)updateTabInfoImages {
    if ([GMTabBarIconManager hasTotalTabbarIconsFromDisk]) {
        [[GMTabBarIconManager localTabBarIcons] enumerateObjectsUsingBlock:^(GMTabIconConfigObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.iconNormal isNonEmpty] && [obj.iconPressed isNonEmpty]) {
                NSLog(@"%@",NSStringFromCGSize(obj.normalImage.size));
                self.childViewControllers[idx].tabBarItem.image = obj.normalImage;
                self.childViewControllers[idx].tabBarItem.selectedImage = obj.pressedImage;
            }
        }];
    }
}
//UIViewController *group = self.childViewControllers[1];
//group.tabBarItem.title = @"小组";
//group.tabBarItem.tag = 1000 +1;
//group.tabBarItem.image = [UIImage imageNamed:@"menu_order"];
//group.tabBarItem.selectedImage = [UIImage imageOriginalWithName:@"menu_order_pr"];

// 服务器配置的tababar的16进制颜色,替换策略和icon一致
- (void)updateTabInfoTitleColors {
    if (GMTabBarIconManager.tabbarConfig) {
        [GMTabBarIconManager.tabbarConfig enumerateObjectsUsingBlock:^(GMTabIconConfigObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.colourNormal isNonEmpty]) {
                
            }
            if ([obj.colourPressed isNonEmpty]) {
//                [self loadItemColor:obj.colourPressed];
            }
        }];
    }
}

#pragma mark - 自定义tabBar
- (void)setupTabBar
{
    GMTabBar *tabBar = [[GMTabBar alloc] init];
    tabBar.backgroundColor = UIColor.whiteColor;
    [self setValue:tabBar forKey:@"tabBar"];
}

- (void)selectTab:(NSInteger)pageIndex {
    [AppDelegate.navigation popToRootViewControllerAnimated:NO];
    [self changeToControllerAtIndex:pageIndex];
}


- (void)changeToControllerAtIndex:(NSInteger)index {
    // 当选中tab时，小红点消失
    self.current = self.childViewControllers[index];
    self.pageName = self.current.pageName;

    [self setSelectedIndex:index > self.tabBar.items.count ? 0 : index];
    //最后一个个人中心控制器有些特殊，不登录不能选择，所以要做一些特殊处理，防止最后一个tabbar被选中
    if (self.isNeedSelect == YES && (_clickNum == _selectNum)) {
        _clickNum = index;
        _selectNum = index;
        GMTabBar *tabBar = [self valueForKey:@"tabBar"];
        [tabBar setTabbarButton:index > self.tabBar.items.count ? 0 : index];
    }
}
/*
 Changing the delegate of a tab bar 【managed by a tab bar controller】 is not allowed.
 被UITabBarController所管理的UITabBar的delegate是不允许修改的
 */

#pragma mark - 添加所有子控制器
- (void)setupAllChildViewController
{
    // 首页
    GMHomeController *hoemVc = [[GMHomeController alloc] init];
    [self addChildViewController:hoemVc];

    // 小组
    GMGroupController *topicVc = [[GMGroupController alloc] init];
    [self addChildViewController:topicVc];
    
    //Pick
    ALRankContainerViewController *rankList = [[ALRankContainerViewController alloc] init];
    [self addChildViewController:rankList];

    // 发帖
    GMMessageController *messageVc = [[GMMessageController alloc] init];
    [self addChildViewController:messageVc];

    // 我
    // 加载箭头指向控制器
    GMMeController *meVc = [[GMMeController alloc] initWithUserId:[GMLoginManager shareInstance].user.userId];
    meVc.isHideNavBar = YES;
    self.meVc = meVc;
    [self addChildViewController:meVc];
}

// 设置tabBar上所有按钮内容
- (void)setupAllTitleButton
{
    // 0:nav
    UIViewController *home = self.childViewControllers[0];
    home.tabBarItem.tag = 1000;
    // 1:小组
    UIViewController *group = self.childViewControllers[1];
    group.tabBarItem.tag = 1000 +1;
    //榜单
    UIViewController *rankList = self.childViewControllers[2];
    rankList.tabBarItem.tag = 1000 +2;
    // 3.消息
    UIViewController *message = self.childViewControllers[3];
    message.tabBarItem.tag = 1000 +3;
    // 4.我
    UINavigationController *me = self.childViewControllers[4];
    me.tabBarItem.tag = 1000 +4;
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger index = item.tag -1000;
    _clickNum = index;
    //是游客模式
    //游客模式不选中最后一个tabbar
    
    if ([GMLoginManager shareInstance].isVisitor && index == 4)
    {
    }
    else
    {
        _selectNum = index;
    }
    
    [self changeToControllerAtIndex:index];

    switch (index) {
        case 0:
            [Phobos track:@"main_click_tab" attributes:@{@"tab":@"home"}];
            break;
        case 1:
            [Phobos track:@"main_click_tab" attributes:@{@"tab":@"group"}];
            break;
        case 2:
            [Phobos track:@"main_click_tab" attributes:@{@"tab":@"pick"}];
            break;
        case 3:
            [Phobos track:@"main_click_tab" attributes:@{@"tab":@"message"}];
            break;
        case 4:
            [Phobos track:@"main_click_tab" attributes:@{@"tab":@"personal"}];
            break;
        default:
            break;
    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[GMMeController class]] && [GMLoginManager shareInstance].isVisitor) {
        [[GMLoginManager shareInstance] showLoginViewIfNeeded];
        [self selectTab:_selectNum];
        return NO;
    }
    else
    {
        return YES;
    }
}

@end
