//
//  BaseScrollTableViewController.m
//  DingDCommunity
//
//  Created by JianjiYuan on 14-3-7.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "BaseScrollTableViewController.h"

@interface BaseScrollTableViewController ()

@property (nonatomic, strong) NSMutableDictionary *dicItemHasRequested;

@end

@implementation BaseScrollTableViewController

#pragma mark =============  Memery Release  =============

- (void)dealloc
{
    [self disposeProperties];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        [self disposeProperties];
    }
}

- (void)disposeProperties
{
    _swipeView.delegate = nil;
    _swipeView.dataSource = nil;
    self.swipeView = nil;
    self.arrItemTitles = nil;
    
    self.arrItemBgNorImages = nil;
    self.arrItemBgPreImages = nil;
    self.arrItemTitleNorColors = nil;
    self.arrItemTitlePreColors = nil;
    
    self.itemBgImageNormal = nil;
    self.itemBgImageSelected = nil;
    
    self.itemTitleColorNormal = nil;
    self.itemTitleColorSelected = nil;
    
    self.selectedIndexPath = nil;
    
}

#pragma mark =============  Initiation Method  =============

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.useItemTitles = YES;
        self.itemPosition = TitleItemPositionTop;
        
        self.itemBgImageNormal = [UIImage imageNamed:@"navigationbar_background.png"];
        self.itemTitleColorNormal = [UIColor blackColor];
        
        self.itemBgImageSelected = [UIImage imageNamed:@"btn_blue.png"];
        self.itemTitleColorSelected = [UIColor blackColor];
        
        self.leftMarginOfButton = 0;
        self.columnMarginOfButton = 0;
        self.rightMarginOfButton = 0;
        
        self.lastIndexOfItem = 0;
        
        self.heightOfButtons = 44.0f;

    }
    return self;
}

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

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.selectedIndexPath) {
        UITableView *refreshTable = (UITableView *)[self.swipeView itemViewAtIndex:_lastIndexOfItem];
        refreshTable.separatorStyle = UITableViewCellSelectionStyleNone;
        [refreshTable deselectRowAtIndexPath:self.selectedIndexPath animated:YES];
    }
    
    [self reloadTableView];
    
}

- (void)reloadItemTitles
{
    if (self.useItemTitles) {
        
        [self.containerItems autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
        [self.containerItems autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
        [self.containerItems autoSetDimensionsToSize:CGSizeMake(CGRectGetWidth(self.view.frame), _heightOfButtons)];
        
        [self.swipeView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
        [self.swipeView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];

        if (_itemPosition == TitleItemPositionTop) {
            [self.containerItems autoPinToTopLayoutGuideOfViewController:self withInset:0];
            [self.swipeView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.containerItems];
            [self.swipeView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
        }else if (_itemPosition == TitleItemPositionBottom) {
            [self.containerItems autoPinToBottomLayoutGuideOfViewController:self withInset:0];
            [self.swipeView autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.containerItems];
            [self.swipeView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
        }
        
        CGFloat width = CGRectGetWidth(self.view.frame);
        CGFloat buttonWidth = (width-(_leftMarginOfButton+_arrItemTitles.count*_columnMarginOfButton+_rightMarginOfButton))/_arrItemTitles.count;
        
        [self.containerItems.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        for (int i = 0; i < _arrItemTitles.count; i++) {
            
            NSString *title = [_arrItemTitles[i] validDataOfClass:[NSString class]];
            UIButton *btnItem = [UIButton buttonWithType:UIButtonTypeCustom];
            [btnItem setFrame:CGRectMake(_leftMarginOfButton+i*(buttonWidth+_columnMarginOfButton),
                                         0, buttonWidth, _heightOfButtons)];
            btnItem.tag = kButtonItemFirst+i;
            [btnItem setTitle:title forState:UIControlStateNormal];
            btnItem.titleLabel.font = self.titleFontNor?:[UIFont systemFontOfSize:15];
            btnItem.backgroundColor = [UIColor whiteColor];
            
            UIColor *titleColorNor = self.arrItemTitleNorColors.count?self.arrItemTitleNorColors[i]:self.itemTitleColorNormal;
            UIColor *titleColorPre = self.arrItemTitlePreColors.count?self.arrItemTitlePreColors[i]:self.itemTitleColorNormal;
            UIImage *imageBgNor = self.arrItemBgNorImages.count?self.arrItemBgNorImages[i]:self.itemTitleColorNormal;
            UIImage *imageBgPre = self.arrItemBgPreImages.count?self.arrItemBgPreImages[i]:self.itemTitleColorNormal;
            
            btnItem.titleEdgeInsets = _titleInsets;
            btnItem.imageEdgeInsets = _imageInsets;
            [btnItem setTitleColor:titleColorNor forState:UIControlStateNormal];
            [btnItem setTitleColor:titleColorPre forState:UIControlStateSelected];
            [btnItem setBackgroundImage:imageBgNor forState:UIControlStateNormal];
            [btnItem setBackgroundImage:imageBgPre forState:UIControlStateSelected];
            
            [btnItem addTarget:self action:@selector(btnItemClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.containerItems addSubview:btnItem];
            
            if (i == _lastIndexOfItem) {
                [btnItem setSelected:YES];
                btnItem.titleLabel.font = self.TitleFontPre?:[UIFont boldSystemFontOfSize:17];
            }
        }
        
    }
    
}

- (void)reloadTableView
{
    if ([[self.dicItemHasRequested objectForKey:kDataForTableKey(self.lastIndexOfItem)] boolValue]) {
        
        UITableView *tableView = (UITableView *)[self.swipeView itemViewAtIndex:self.lastIndexOfItem];
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [tableView reloadData];
    }else {
        [self.dicItemHasRequested setObject:@YES forKey:kDataForTableKey(self.lastIndexOfItem)];
        [self reRequestTableViewDatas];
//        if (self.lastIndexOfItem !=1) {
//            [self reRequestTableViewDatasForst];
//        }
        [DataMgr getInstance].lastIndexOfItemNum = [NSString stringWithFormat:@"%ld",(long)self.lastIndexOfItem];
        UITableView *tableView = (UITableView *)[self.swipeView itemViewAtIndex:self.lastIndexOfItem];
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [tableView reloadData];
    }
    
}

- (void)reRequestTableViewDatas
{
    DLog(@"Override to Re Request Datas");
}
-(void)reRequestTableViewDatasForst
{
    DLog(@"Override to Re Request Datas first");
}
#pragma mark =============  Action Handler Method  =============

- (void)btnItemClick:(UIButton *)sender
{
    NSInteger indexOfItem = sender.tag-kButtonItemFirst;
    if (indexOfItem == _lastIndexOfItem) {
        return;
    }
    UIButton *btnLast = (UIButton *)[self.view viewWithTag:kButtonItemFirst+_lastIndexOfItem];
    btnLast.titleLabel.font = self.titleFontNor?:[UIFont systemFontOfSize:15];
    [btnLast setSelected:NO];
    
    [sender setSelected:YES];
    sender.titleLabel.font = self.TitleFontPre?:[UIFont boldSystemFontOfSize:17];
    _lastIndexOfItem = indexOfItem;
    
    [_swipeView scrollToItemAtIndex:indexOfItem duration:0.3];
    
    [self performSelector:@selector(reloadTableView) withObject:nil afterDelay:0.3];
}

#pragma mark =============  SwipeView DataSource  =============

- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView
{
    return _numberOfItems;
}

- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    if (view == nil)
    {
        UITableView *tablevContent = [[UITableView alloc] initWithFrame:swipeView.bounds];
        tablevContent.backgroundColor = [UIColor clearColor];
        tablevContent.delegate = self;
        tablevContent.dataSource = self;
        tablevContent.separatorStyle = UITableViewCellSeparatorStyleNone;
        tablevContent.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        view = tablevContent;
    }
    view.tag = index;
    return view;
}

- (CGSize)swipeViewItemSize:(SwipeView *)swipeView
{
    return self.swipeView.bounds.size;
}

#pragma mark =============  SwipeView Delegate  =============

- (void)swipeViewDidEndDecelerating:(SwipeView *)swipeView
{
    NSInteger indexOfItem = swipeView.currentPage;
    
    if (indexOfItem == _lastIndexOfItem) {
        return;
    }
    UIButton *btnLast = (UIButton *)[self.view viewWithTag:kButtonItemFirst+_lastIndexOfItem];
    btnLast.titleLabel.font = self.titleFontNor?:[UIFont systemFontOfSize:15];
    [btnLast setSelected:NO];
    
    UIButton *btnCurrent = (UIButton *)[self.view viewWithTag:kButtonItemFirst+indexOfItem];
    btnCurrent.titleLabel.font = self.TitleFontPre?:[UIFont boldSystemFontOfSize:17];
    [btnCurrent setSelected:YES];
    
    _lastIndexOfItem = indexOfItem;
    
    [self reloadTableView];
            
}

#pragma mark =============  UITableView DataSource  =============

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arrContents = self.dictTableDatas[kDataForTableKey(tableView.tag)];
    return arrContents.count;
}

#pragma mark =============  UITableView Delegate  =============

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    DLog(@"You Click At Section: %d Row: %d",(int)indexPath.section,(int)indexPath.row);
}

#pragma mark =============  Properties Lazy Load  =============

- (SwipeView *)swipeView
{
    if (_swipeView) {
        return _swipeView;
    }
    self.swipeView = [SwipeView  newAutoLayoutView];
    _swipeView.alignment = SwipeViewAlignmentCenter;
    _swipeView.delegate = self;
    _swipeView.dataSource = self;
    _swipeView.pagingEnabled = YES;
    _swipeView.itemsPerPage = 1;
    _swipeView.truncateFinalPage = YES;
    [self.view addSubview:_swipeView];
    return _swipeView;
}

- (UIView *)containerItems
{
    if (!_containerItems) {
        self.containerItems = [UIView newAutoLayoutView];
        [self.view addSubview:_containerItems];
    }
    return _containerItems;
}

- (NSMutableDictionary *)dicItemHasRequested
{
    if (!_dicItemHasRequested) {
        self.dicItemHasRequested = [NSMutableDictionary dictionary];
    }
    return _dicItemHasRequested;
}

- (NSMutableDictionary *)dictTableDatas
{
    if (!_dictTableDatas) {
        self.dictTableDatas = [NSMutableDictionary dictionary];
    }
    return _dictTableDatas;
}

@end
