//
//  ICRPatrolPlanViewController.m
//  XFFruit
//
//  Created by Xummer on 4/11/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRPatrolPlanViewController.h"

#import "ICRPatrolPlanCellContentView.h"
#import "ICRPatrolDetailViewController.h"
#import "ICRPatrolResultViewController.h"
#import "ICRPatrolAllStoreViewController.h"

#import "ICRStore.h"
#import "ICRPatrolPlan.h"

typedef NS_ENUM(NSUInteger, PatrolSegmentsType) {
    kPatrolSegUnFinished = 0,
    kPatrolSegFinished,
};

#define PATROL_PLAN_CELL_HEIGHT     130

static NSString *PatrolPlanCellIdentifier = @"PatrolPlanCell";

@interface ICRPatrolPlanViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate,
    IBTScrollViewRefreshDelegate
>
{
    BOOL m_bIsInHome;
}

@property (strong, nonatomic) IBTRefreshTableView *m_tableView;
@property (strong, nonatomic) IBTSegmentContainer *m_segContainer;
@property (weak,   nonatomic) IBTSegmentedControl *m_segmentControl;
@property (strong, nonatomic) NSArray *m_arrData;
@property (strong, nonatomic) NSArray *m_arrAllData;
@property (strong, nonatomic) ICRStore *m_store;

@end

@implementation ICRPatrolPlanViewController

#pragma mark - Life Cycle
- (instancetype)initWithStore:(id)storeData isHomeShow:(BOOL)bShowInHome {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([storeData isKindOfClass:[ICRStore class]]) {
        self.m_store = storeData;
    }
    else if ([storeData isKindOfClass:[NSNumber class]]) {
        // NSUInteger uiStoreID = [storeData unsignedIntegerValue];
        // TODO get Store with |uiStoreID|
    }
    
    m_bIsInHome = bShowInHome;
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = [IBTCommon localizableString:@"PatrolPlan"];
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doGetMyPatrolFromUpdateTime:0 position:0 size:20 success:NULL failure:NULL];
    
    [self initSegmentConatinerFromOriginY:0];
    
    [self initTableView];
    
    [self fetchPatrolList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self fetchDataMore:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Setter
- (void)setM_arrAllData:(NSArray *)arrAllData {
    if ([_m_arrAllData isEqualToArray:arrAllData]) {
        return;
    }
    
    _m_arrAllData = arrAllData;
    
    [self updateDisplayDataWithType:self.m_segmentControl.selectedSegmentIndex];
}

#pragma mark - Private Method
- (void)initTableView {
    CGFloat dy = CGRectGetMaxY(_m_segContainer.frame);
    CGRect frame = self.view.bounds;
    frame.origin.y = dy;
    frame.size.height -= CGRectGetMinY(frame);
    
    self.m_tableView =
    [[IBTRefreshTableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class]
         forCellReuseIdentifier:PatrolPlanCellIdentifier];
    [_m_tableView autoresizingWithStrechFullSize];
    _m_tableView.dataSource = self;
    _m_tableView.delegate = self;
    _m_tableView.refreshDelegate = self;
    [_m_tableView addRefreshControlWithText:[IBTCommon localizableString:@""]];
    [_m_tableView addLoadMoreFootWithText:[IBTCommon localizableString:@"Load more"]];

    [self.view addSubview:_m_tableView];
}

- (void)initSegmentConatinerFromOriginY:(CGFloat)y {
    
    if (_m_segContainer) {
        return;
    }
    
    NSArray *arrSegments =
    @[ [IBTCommon localizableString:@"Unfinished"],
       [IBTCommon localizableString:@"Finished"], ];
    self.m_segContainer = [[IBTSegmentContainer alloc] initWithItems:arrSegments];
    self.m_segmentControl = _m_segContainer.segmentControl;
    _m_segmentControl.selectedSegmentIndex = 0;
    _m_segContainer.frame = (CGRect){
        .origin.x = 0,
        .origin.y = y,
        .size.width = CGRectGetWidth(self.view.bounds),
        .size.height = IBT_SEGMENT_CONTAINER_DEFUALT_HEIGHT
    };
    [self.view addSubview:_m_segContainer];
    
    [_m_segmentControl addTarget:self action:@selector(onSegmentsTapped:)
                forControlEvents:UIControlEventValueChanged];
}

#pragma mark - Action
- (void)onSegmentsTapped:(id)sender {
    UISegmentedControl *segmentedCtrl = sender;
    [self updateDisplayDataWithType:segmentedCtrl.selectedSegmentIndex];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [_m_arrData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:PatrolPlanCellIdentifier forIndexPath:indexPath];
    
    [self configureCell:cell forRowAtIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    id data = _m_arrData[ indexPath.row ];
    
    UIView *contentView = cell.contentView;
    
    ICRPatrolPlanCellContentView *view = [contentView viewWithClass:[ICRPatrolPlanCellContentView class]];
    
    if (!view) {
        view = [[ICRPatrolPlanCellContentView alloc] initWithFrame:contentView.bounds];
        view.m_bHiddenNumLabel = m_bIsInHome;
        [view autoresizingWithStrechFullSize];
        [contentView addSubview:view];
    }
    
    [view updateValueLabelWithData:data];
}

#pragma mark - UITableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return m_bIsInHome ? PATROL_PLAN_CELL_HEIGHT : 109;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ICRPatrolPlan *plan = _m_arrData[ indexPath.row ];
    if (m_bIsInHome) {
        ICRPatrolAllStoreViewController *pVC =
        [[ICRPatrolAllStoreViewController alloc] initWithPatrolPlan:plan];
        [self PushViewController:pVC animated:YES];
    }
    else {
        
        switch (_m_segmentControl.selectedSegmentIndex) {
            case kPatrolSegUnFinished:
            {
                ICRPatrolDetailViewController *patrolDetailVC = [[ICRPatrolDetailViewController alloc] initWithPatrolPlan:plan storeID:_m_store.storyID];
                [self PushViewController:patrolDetailVC animated:YES];
            }
                break;
            case kPatrolSegFinished:
            {
                ICRPatrolResultViewController *patrolDetailVC = [[ICRPatrolResultViewController alloc] initWithPatrolPlan:plan storeID:_m_store.storyID];
                [self PushViewController:patrolDetailVC animated:YES];
            }
                break;
            default:
                break;
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _m_tableView) {
        [_m_tableView tableViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    if (scrollView == _m_tableView) {
        [_m_tableView tableviewDidEndDragging:scrollView];
    }
}

#pragma mark - IBTScrollViewRefreshDelegate

- (void)startRefreshData:(UIScrollView *)scrollView {
    [self fetchDataMore:NO];
}

- (void)endRefreshData:(UIScrollView *)scrollView {
    
}

- (void)startLoadMoreData:(UIScrollView *)scrollView {
    [self fetchDataMore:YES];
}

- (void)endLoadMoreData:(UIScrollView *)scrollView {
    
}

#pragma mark - Data Update

- (void)fetchPatrolList {
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ DESC", [ICRPatrolPlan TableName], @"beginDate"];
        NSLog(@"sql====>>>>>%@" ,sql);
        return [db executeQuery:sql];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        if (strongSelf.m_store) {
            NSMutableArray *arrMatched = [NSMutableArray array];
            for (ICRPatrolPlan *plan in fetchedObjects) {
                for (NSDictionary *inspector in plan.inspectors) {
                    NSString *mStoreID = inspector[@"store"][@"uuid"];
                    if ([mStoreID isEqualToString: strongSelf.m_store.storyID]) {
                        [arrMatched addObject:plan];
                        break;
                    }
                }
            }
            self.m_arrAllData = arrMatched.count > 0 ? arrMatched : nil;
        }
        else {
            strongSelf.m_arrAllData = fetchedObjects;
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRPatrolPlan class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

- (void)updateDisplayDataWithType:(PatrolSegmentsType)eType {
    
    if (_m_store) {

        NSMutableArray *arrMatched = [NSMutableArray array];
        for (ICRPatrolPlan *plan in _m_arrAllData) {

            for (NSDictionary *inspectors in plan.inspectors) {
            NSInteger iStatus = [inspectors[@"state"] integerValue];
            if (iStatus == eType) {
                [arrMatched addObject:plan];
                break;
            }
        }
                self.m_arrData = arrMatched.count > 0 ? arrMatched : nil;
    }}else {
        NSString *filter = nil;
        NSArray *args = nil;
                for (ICRPatrolPlan *plan in _m_arrAllData) {
                CLog(@"plan.state == %lu",(unsigned long)plan.state);
            }
        switch (eType) {
            case kPatrolSegUnFinished:
            {
                filter = @"(%K IN %@)";
                args = @[ @"state", @[ @( kICRPatrolPlanStatusCreated ),
                                        @( kICRPatrolPlanStatusCommited ),
                                        @( kICRPatrolPlanStatusExeted ) ]];
            }
                break;
            case kPatrolSegFinished:
            {
                filter = @"(%K IN %@)";
                args = @[ @"state", @[ @( kICRPatrolPlanStatusFinished ),
                                        @( kICRPatrolPlanStatusCanceld ) ],
                          ];
            }
                break;
                
            default:
                break;
        }
        
        if (filter) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:filter argumentArray:args];
            self.m_arrData = [_m_arrAllData filteredArrayUsingPredicate:predicate];
        }
        else {
            self.m_arrData = nil;
        }
    }
    [self.m_tableView reloadData];
}

#pragma mark - Get Data

- (void)fetchDataMore:(BOOL)more {
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchPatrolList];
        if (!more) {
            [_m_tableView endRefreshWithState:kRefreshStateFinished];
        }
        else {
            [_m_tableView endLoadMoreWithState:kLoadStateFinished];
        }
        
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
        if (!more) {
            [_m_tableView endRefreshWithState:kRefreshStateFailed];
        }
        else {
            [_m_tableView endLoadMoreWithState:kLoadStateFailed];
        }
        
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    ICRPatrolPlan *data = [_m_arrData lastObject];
    
    [httpCtrl doGetMyPatrolFromUpdateTime:more ? data.createInfo[@"time"] : nil
                                 position:0
                                     size:20
                                  success:succ
                                  failure:fail];
}

@end
