
//
//  CustomTabbarController.m
//  Lighting
//
//  Created by 曹云霄 on 16/4/27.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "CustomTabbarController.h"
#import "Toolview.h"
#import "AppDelegate.h"
#import "SceneLibraryViewController.h"
#import "ProductLibraryViewController.h"
#import "CustomerManagementViewController.h"
#import "AboutViewController.h"
#import "AllCustomerViewController.h"
#import "CustomerOrderViewController.h"
#import "UserViewController.h"
#import "ChangePasswordViewController.h"
#import "SearchViewController.h"
#import "BaseViewController.h"
#import "QRViewController.h"
#import "ExperienceCentreViewController.h"
#import "RebateViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface CustomTabbarController ()<TabbarButtonClickdelegate,ChangpasswordDelegate,CancelButtondelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSArray *identifierArray;

/**
 *  保存按钮引用
 */
@property (nonatomic,strong) UIButton *Newbutton;

/**
 *  控制器数组
 */
@property (nonatomic,strong) NSArray *vcArray;

/**
 *  工具栏
 */
@property (nonatomic,strong) Toolview *toolview;

@end

@implementation CustomTabbarController

/**
 *  UIStoryboard Identifier数组
 *
 *  @return NSArary
 */
- (NSArray *)identifierArray
{
    if (_identifierArray == nil) {
        
        _identifierArray = [NSArray arrayWithObjects:@"searchvc",@"shopping",@"Client",@"followheart",@"scenelibrary",@"productlibrary",@"customermanager",@"allcustomer",@"customerorder",@"about", nil];
    }
    return _identifierArray;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.selectedViewController beginAppearanceTransition: YES animated: animated];
}

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.selectedViewController endAppearanceTransition];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.selectedViewController beginAppearanceTransition: NO animated: animated];
}

-(void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.selectedViewController endAppearanceTransition];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self uiConfigAction];
    [self addViewcontroller];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.tabBar.frame = CGRectMake(Zero, Zero, ScreenWidth, NavigationHeight);
    self.toolview = [[Toolview alloc]initWithFrame:CGRectMake(Zero, Zero, ScreenWidth, NavigationHeight)];
    self.toolview.delegate = self;
    self.toolview.inputField.delegate = self;
    self.delegate = self;
    [self.tabBar addSubview:self.toolview];
    //显示体验中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShowFollowHeart:) name:@"FollowHeartVC" object:nil];
    //2016年08月26日15:52:28显示我的账户
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMyAccountController:) name:@"ShowMyAccountVC" object:nil];
}


#pragma mark -添加controller到viewControllers
- (void)addViewcontroller
{
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
    SearchViewController *searchVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:0]];
    ShoppingViewController *shoppingVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:1]];
    ClientViewController *clientVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:2]];
    SceneLibraryViewController *sceneVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:4]];
    ProductLibraryViewController *productVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:5]];
    CustomerManagementViewController *customerVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:6]];
    AllCustomerViewController *allcustomerVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:7]];
    CustomerOrderViewController *customerOrderVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:8]];
    AboutViewController *aboutVC = [storyboard instantiateViewControllerWithIdentifier:[self.identifierArray objectAtIndex_opple:9]];
    //2016年08月26日15:13:04新增返利
    RebateViewController *rebateVC = [storyboard instantiateViewControllerWithIdentifier:@"RebateViewController"];
    
    
    UINavigationController *searchNav = [[UINavigationController alloc]initWithRootViewController:searchVC];
    UINavigationController *shoppingNav = [[UINavigationController alloc]initWithRootViewController:shoppingVC];
    UINavigationController *clientNav = [[UINavigationController alloc]initWithRootViewController:clientVC];
    UINavigationController *sceneNav = [[UINavigationController alloc]initWithRootViewController:sceneVC];
    UINavigationController *productNav = [[UINavigationController alloc]initWithRootViewController:productVC];
    UINavigationController *customerNav = [[UINavigationController alloc]initWithRootViewController:customerVC];
    UINavigationController *allcustomerNav = [[UINavigationController alloc]initWithRootViewController:allcustomerVC];
    UINavigationController *cutomerorderNav = [[UINavigationController alloc]initWithRootViewController:customerOrderVC];
    UINavigationController *aboutNav = [[UINavigationController alloc]initWithRootViewController:aboutVC];
    UINavigationController *rebateNav = [[UINavigationController alloc]initWithRootViewController:rebateVC];
    
    self.vcArray = [NSArray arrayWithObjects:rebateNav,aboutNav,cutomerorderNav,allcustomerNav,customerNav,productNav,sceneNav,clientNav,shoppingNav,searchNav, nil];
    self.viewControllers = self.vcArray;
    SHARED_APPDELEGATE.allControllerArray = [NSArray arrayWithObjects:rebateVC,aboutVC,customerOrderVC,allcustomerVC,customerVC,productVC,sceneVC,clientVC,shoppingVC,searchVC, nil];
    self.selectedIndex = 7;
}


#pragma mark -移除系统自带的UITabBarButton
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    for (UIView *view in self.tabBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [view removeFromSuperview];
        }
    }
}


#pragma amrk -TabbarButtonClickdelegate代理
- (void)ButtonClickAction:(NSInteger)Buttontag withButton:(UIButton *)button
{
    [self.toolview.inputField resignFirstResponder];
    [self dismissViewControllerAnimated:NO completion:nil];
    _Newbutton = button;
    switch (Buttontag) {
            
            //右侧视图
        case 100:
            
            [SHARED_APPDELEGATE.mmdrawer toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
            
            break;
            
            //某某用户
        case 101:
            
        {
            UserViewController *userVC = [[UserViewController alloc]init];
            userVC.delegate = self;
            userVC.preferredContentSize = CGSizeMake(260, 230);
            userVC.modalPresentationStyle = UIModalPresentationPopover;
            UIPopoverPresentationController *pop = userVC.popoverPresentationController;
            pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
            pop.sourceView = userVC.view;
            pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
            [self presentViewController:userVC animated:YES completion:nil];
        }
            break;
            
            //我的客户
        case 102:
            
            self.selectedIndex = 7;
            
            break;
            
            //购物车
        case 103:
            
            //必须设置当前客户才能跳转到购物车
            if (![Shoppersmanager manager].currentCustomer) {
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
                hud.labelText = @"必须设置当前客户才能访问购物车";
                hud.margin = 10.f;
                hud.color = [[UIColor blackColor] colorWithAlphaComponent:0.5];
                hud.minSize = CGSizeMake(200, 50);
                hud.animationType = MBProgressHUDAnimationZoom;
                hud.mode = MBProgressHUDModeText;
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:1.0f];
            }else
            {
                
                self.selectedIndex = 8;
            }
            
            break;
            
        default:
            break;
    }
}

#pragma mark -修改密码点击
- (void)changPasswordButtonClick
{
    [self dismissViewControllerAnimated:NO completion:^{
        
        ChangePasswordViewController *changpassword = [[ChangePasswordViewController alloc]init];
        changpassword.delegate = self;
        changpassword.preferredContentSize = CGSizeMake(260, 180);
        changpassword.modalPresentationStyle = UIModalPresentationPopover;
        UIPopoverPresentationController *pop = changpassword.popoverPresentationController;
        pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
        pop.sourceView = changpassword.view;
        pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_Newbutton];
        [self presentViewController:changpassword animated:YES completion:nil];
    }];
}



#pragma mark -取消按钮
- (void)cancelButtonClick
{
    [self dismissViewControllerAnimated:NO completion:^{
        
        UserViewController *userVC = [[UserViewController alloc]init];
        userVC.delegate = self;
        userVC.preferredContentSize = CGSizeMake(260, 230);
        userVC.modalPresentationStyle = UIModalPresentationPopover;
        UIPopoverPresentationController *pop = userVC.popoverPresentationController;
        pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
        pop.sourceView = userVC.view;
        pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_Newbutton];
        [self presentViewController:userVC animated:YES completion:nil];
    }];
}

#pragma mark -二维码扫描
- (void)QrcodeButtonClick
{
    __weak typeof(self) weakSelf = self;
    //判断权限
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(status !=AVAuthorizationStatusAuthorized) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPad的“设置-隐私-相机”选项中，允许欧立方访问你的相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSURL * url = [NSURL URLWithString:@"prefs:root=com.gomore.opple"];
            dispatch_after(0.2, dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication]openURL:url];
            });
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
        
    }else {
        QRViewController *qrVC = [[QRViewController alloc] initWithScanCompleteHandler:^(NSString *url) {
            [self dismissViewControllerAnimated:YES completion:^{
                
                ProductLibraryViewController *product = [SHARED_APPDELEGATE.allControllerArray objectAtIndex_opple:4];
                product.barcode = url;
                self.selectedIndex = 4;
            }];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf presentViewController:qrVC animated:YES completion:nil];
        });
    }
}


#pragma mark -搜索框代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //返回根视图
    [[NSNotificationCenter defaultCenter] postNotificationName:POPROOTCONTROLLER object:nil];
    self.selectedIndex = 9;
    
    return YES;
}


#pragma mark -Search按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //搜索
    if (textField.text.length != 0) {
        
        [textField resignFirstResponder];
        //搜索
        [[NSNotificationCenter defaultCenter] postNotificationName:SEARCHSTRING object:textField.text];
    }
    return YES;
}

#pragma mark -自定义选中
- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [super setSelectedIndex:selectedIndex];
    [self tabBarController:self didSelectViewController:[self.vcArray objectAtIndex_opple:selectedIndex]];
}


#pragma mark -回到最上层
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        
        UINavigationController *navVC = (UINavigationController *)viewController;
        [navVC popToRootViewControllerAnimated:NO];
    }
}


#pragma mark -推出体验中心控制器
- (void)ShowFollowHeart:(NSNotification *)objc
{
    if (![Shoppersmanager manager].currentCustomer) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
        hud.labelText = @"必须设置当前客户才能访问购物车";
        hud.margin = 10.f;
        hud.color = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        hud.minSize = CGSizeMake(200, 50);
        hud.animationType = MBProgressHUDAnimationZoom;
        hud.mode = MBProgressHUDModeText;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1.0f];
        
    }else
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
        ExperienceCentreViewController *ExperienceCenter = [storyboard instantiateViewControllerWithIdentifier:@"ExperienceCentre"];
        ExperienceCenter.modalPresentationStyle = UIModalPresentationOverFullScreen;
        UIPopoverPresentationController *popover = ExperienceCenter.popoverPresentationController;
        popover.sourceView = ExperienceCenter.view;
        [self presentViewController:ExperienceCenter animated:YES completion:nil];
    }
}

#pragma mark - 显示我的账户
- (void)showMyAccountController:(NSNotification *)sender
{
    [self dismissViewControllerAnimated:NO completion:nil];
    self.selectedIndex = 0;
}

@end
