

#import "VankeMainBoard_iPhone.h"
#import "VankeFloorListBoard_iPhone.h"
#import "VankeFloorListBoardCell_iPhone.h"
#import "VankeServiceDashBoard_iPhone.h"
#import "VankeAppBoard_iPhone.h"
#import "VankeUtil.h"
#import "GEToast.h"

@interface VankeMainBoard_iPhone ()
@property (strong, nonatomic) VankeServiceDashBoard_iPhone *currDashBoard;
@end

#pragma mark -

@interface VankeMainBoard_iPhone ()
{
    NSInteger _curTopMenuIndex;
    NSMutableDictionary *tabCache;
}
@end

@implementation VankeMainBoard_iPhone

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

DEF_OUTLET( VankeWeatherCell_iPhone, weatherBoard );
DEF_OUTLET( VankeTopMenuBoardCell_iPhone, topMenu );
DEF_OUTLET( BeeUIView, serviceDashBoardView );
DEF_OUTLET( BeeUISearchBar, searchBar);

DEF_MODEL( VankeProjectSummaryModel, summaryModel );

- (void)load
{
    _curTopMenuIndex = -1;
    tabCache = [[NSMutableDictionary alloc] initWithCapacity:3];
    self.summaryModel = [VankeProjectSummaryModel modelWithObserver:self];
}

- (void)unload
{
    self.summaryModel = nil;
    tabCache = nil;
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    self.view.backgroundColor = [UIColor whiteColor];
//    [self addLeftIconToTextField:_txtQuery icon:@"search"];
    [_weatherBoard reloadLocationAndWeather];
    self.view.swipeble = YES;
    self.view.swipeDirection = UISwipeGestureRecognizerDirectionLeft;
    
    //去掉搜索框背景
    float version = [[[ UIDevice currentDevice ] systemVersion ] floatValue ];
    if ([ _searchBar respondsToSelector : @selector (barTintColor)]) {
        float  iosversion7_1 = 7.1 ;
        if (version >= iosversion7_1) {
            //iOS7.1
            [[[[ _searchBar.subviews objectAtIndex : 0 ] subviews] objectAtIndex : 0 ] removeFromSuperview ];
            [ _searchBar setBackgroundColor :[ UIColor clearColor ]];
        } else {
            //iOS7.0
            [ _searchBar setBarTintColor :[ UIColor clearColor ]];
            [ _searchBar setBackgroundColor :[ UIColor clearColor ]];
        }
    } else {
        //iOS7.0 以下
        [[ _searchBar . subviews objectAtIndex : 0 ] removeFromSuperview ];
        [ _searchBar setBackgroundColor :[ UIColor clearColor ]];
    }
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [BeeUIRouter sharedInstance].view.pannable = NO;
    self.navigationBarShown = NO;
    [[VankeAppBoard_iPhone sharedInstance] showMenu];
    [_summaryModel reload];
}

ON_DID_APPEAR( signal )
{
    // 如果没有设置当前tab，则默认为第一页
    if (nil == _currDashBoard) {
        [self showTab: 0];
    }
}

ON_WILL_DISAPPEAR( signal )
{
    [BeeUIRouter sharedInstance].view.pannable = NO;
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( VankeMainBoard_iPhone, searchBar, signal )
{
    if ([signal is:BeeUISearchBar.SEARCH]) {
        [self showListView: CELL_TYPE_FLOOR];
    }
}

#pragma VankeWeatherCell_iPhone

ON_SIGNAL3( VankeWeatherCell_iPhone, btnMask, signal )
{
    [_weatherBoard reloadLocationAndWeather: YES];
}

#pragma VankeTopMenuBoardCell_iPhone

ON_SIGNAL3( VankeTopMenuBoardCell_iPhone, menuCommunity, signal ) {
    [self showTab: 0];
}

ON_SIGNAL3( VankeTopMenuBoardCell_iPhone, menuCenter, signal ) {
    [self showTab: 1];
}

ON_SIGNAL3( VankeTopMenuBoardCell_iPhone, menuSqure, signal ) {
    [self showTab: 2];
}

#pragma mark - VankeServiceSaleCell_iPhone

ON_SIGNAL3( VankeServiceSaleCell_iPhone, mask, signal ) {
    [[VankeAppBoard_iPhone sharedInstance] hideMenu];
    [self showListView: CELL_TYPE_FLOOR];
}

ON_SIGNAL3( VankeServiceSaleCell_iPhone, btnHistoryMask, signal ) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIDatePicker *picker = [[UIDatePicker alloc] init];
    picker.datePickerMode = UIDatePickerModeDate;
    NSDate *yesterday = [[NSDate alloc]initWithTimeIntervalSinceNow:-24*60*60];
    picker.maximumDate = yesterday;
    picker.locale = [NSLocale localeWithLocaleIdentifier:@"zh-Hans"];
    [picker setDatePickerMode:UIDatePickerModeDate];
    [alertController.view addSubview:picker];
    [alertController addAction:({
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (nil != _currDashBoard) {
                NSDateFormatter *df = [[NSDateFormatter alloc] init];
                [df setDateFormat:@"yyyy-MM-dd"];
                
                NSString *dateStr = [df stringFromDate:picker.date];
                _currDashBoard.salesInfo.lblDate.text = dateStr;
                _summaryModel.salesDate = dateStr;
                _summaryModel.passengerDate = dateStr;
                _summaryModel.trafficDate = dateStr;
                _summaryModel.rentalDateEquals = dateStr;
                [_summaryModel reload];
            }
        }];
        action;
    })];
    UIPopoverPresentationController *popoverController = alertController.popoverPresentationController;
    popoverController.sourceView = self.view;
    popoverController.sourceRect = [self.view bounds];
    [self presentViewController:alertController  animated:YES completion:nil];
}

ON_SIGNAL3(VankeServiceBoardCell_iPhone, mask, signal) {
    VankeServiceBoardCell_iPhone *cell = (VankeServiceBoardCell_iPhone *)signal.sourceCell;
    if ([@"昨日客流" eq:[cell name]]) {
        [[VankeAppBoard_iPhone sharedInstance] hideMenu];
        [self showListView: CELL_TYPE_PASSENGER];
    } else {
        [GEToast showWithText:@"正在研发中..." bottomOffset:50.0f duration:1.0f];
    }
}

#pragma mark - VankeProjectSummaryModel

ON_SIGNAL3(VankeProjectSummaryModel, RELOADING, signal) {
    [GEToast showProgress:self.serviceDashBoardView];
}

ON_SIGNAL3(VankeProjectSummaryModel, RELOADED, signal) {
    [GEToast hideProgress];
    
    if (![_summaryModel isOk]) {
        [GEToast showWithText:[_summaryModel getMessage] bottomOffset:20 duration:1.0f];
        return;
    }
    
    if (nil != _currDashBoard) {
        ProjectSummary *data = [[_summaryModel getServerResp] getSummary:_currDashBoard.name];
        if (nil != data) {
            [_currDashBoard setData:data];
        }
    }
}

-(void) addLeftIconToTextField: (BeeUITextField*) textField icon: (NSString*) icon {
    UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:icon]];
    img.frame = CGRectMake(0, 0, 30, 25);
    img.contentMode = UIViewContentModeCenter;
    textField.leftView = img;
    textField.leftViewMode = UITextFieldViewModeAlways;
}

-(void) showTab: (int) tabIndex {
    if (tabIndex == _curTopMenuIndex) {
        return;
    }
    
    CGRect frame = self.serviceDashBoardView.frame;
    if (frame.size.width <= 0) {
        return;
    }
    
    // 修改标签
    [self.topMenu selectTabByIndex:tabIndex];
    
    // 查找或创建新的tab页
    NSString *key = [NSString stringWithFormat:@"%d", tabIndex];
    VankeServiceDashBoard_iPhone *targetTab = (VankeServiceDashBoard_iPhone*) [tabCache objectForKey:key];
    if (nil == targetTab) {
        targetTab = [VankeServiceDashBoard_iPhone dashBoardByIndex:tabIndex];
        [tabCache setObject:targetTab forKey:key];
    }
    
    // 隐藏当前页
    if (self.currDashBoard != nil) {
        [self.currDashBoard removeFromSuperview];
        self.currDashBoard.hidden = YES;
    }
    
    // 显示目标页
    targetTab.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
    targetTab.right = 0.0f;
//    if (tabIndex > _curTopMenuIndex) {
//        targetTab.right = 0.0f;
//    } else {
//        targetTab.left = frame.size.width;
//    }
    
    [UIView animateWithDuration:0.3f // 动画时长
                          delay:0.0 // 动画延迟
                        options:UIViewAnimationOptionCurveLinear // 动画过渡效果
                     animations:^{
                         targetTab.right += frame.size.width;
//                         if (tabIndex > _curTopMenuIndex) {
//                             targetTab.right += frame.size.width;
//                         } else {
//                             targetTab.left -= frame.size.width;
//                         }
                         targetTab.hidden = NO;
                         [self.serviceDashBoardView addSubview:targetTab];
                     }
                        completion:^(BOOL finished) {
                            self.currDashBoard = targetTab;
                            _curTopMenuIndex = tabIndex;
             
                            // 刷新数据
                            [_summaryModel reload];
                        }];
}

-(void) showListView: (CellType) type {
    VankeFloorListBoard_iPhone * board = [VankeFloorListBoard_iPhone boardWithType:type];
    if (nil != _currDashBoard) {
        board.projectCategory = _currDashBoard.name;
        board.theme = _currDashBoard.theme;
        NSString *nameLike = [VankeUtil trim:self.searchBar.text];
        board.projectNameLike = nameLike;
    }
    
    board.salesDate = _summaryModel.salesDate;
    board.passengerDate = _summaryModel.passengerDate;
    [self.stack pushBoard:board animated:YES];
}

#pragma VankeMainBoard_iPhone

ON_SWIPE_LEFT( signal ) {
    if (_curTopMenuIndex < 2) {
        [self showTab:_curTopMenuIndex + 1];
    } else {
        _curTopMenuIndex = -1;
        [self showTab:_curTopMenuIndex + 1];
    }
}

@end
