//
//  ICRTaskHandleViewController.m
//  XFFruit
//
//  Created by Xummer on 15/5/20.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRTaskHandleViewController.h"
#import "ICRTaskDetailViewController.h"
#import "ICRTaskResultViewController.h"

#import "ICRTaskItemView.h"
#import "ICRTask.h"
#import "ICRStore.h"

static NSString *TaskCellIdentifier = @"TaskCell";


@interface ICRTaskHandleViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate
>

@property (strong, nonatomic) IBTTableView *m_tableView;

@property (strong, nonatomic) NSArray *m_arrData;

@property (strong, nonatomic) ICRStore *m_store;

@end

@implementation ICRTaskHandleViewController

#pragma mark - Life Cycle
- (instancetype)initWithStore:(id)store {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([store isKindOfClass:[ICRStore class]]) {
        self.m_store = store;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"门店任务";
    
    [self initTableView];
    
    [self fetchTaskList];
}

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

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

#pragma mark - Private Method
- (void)initTableView {
    CGRect frame = self.view.bounds;
    
    self.m_tableView =
    [[IBTTableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class]
         forCellReuseIdentifier:TaskCellIdentifier];
    [_m_tableView autoresizingWithStrechFullSize];
    _m_tableView.rowHeight = ICR_TASK_ITEM_HEIGTH;
    _m_tableView.dataSource = self;
    _m_tableView.delegate = self;
    
    [self.view addSubview:_m_tableView];
}

#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
{
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:TaskCellIdentifier 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;
    
    ICRTaskItemView *itemView = [contentView viewWithClass:[ICRTaskItemView class]];
    if (!itemView) {
        itemView = [[ICRTaskItemView alloc] initWithFrame:contentView.bounds];
        [itemView autoresizingWithStrechFullSize];
        [contentView addSubview:itemView];
    }
    
    [itemView updateWithTask:data];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ICRTask *data = _m_arrData[ indexPath.row ];
    if (data.processResult) {
        [self pushToTaskReault:data];
    }
    else if ([data.state isEqualToString:TaskState[ kICRTaskLocalCreated ]] ||
        [data.state isEqualToString:TaskState[ kICRTaskLocalAlloted ]])
    {
        [self pushToTaskDetail:data];
    }
    else if ([data.state isEqualToString:TaskState[ kICRTaskLocalFinished ]])
    {
        [self pushToTaskReault:data];
    }
    }

- (void)pushToTaskDetail:(ICRTask *)task {
    ICRTaskDetailViewController *dVC =
    [[ICRTaskDetailViewController alloc] initWithTaskData:task];
    [self PushViewController:dVC animated:YES];
}

- (void)pushToTaskReault:(ICRTask *)task {
    ICRTaskResultViewController *rVC =
    [[ICRTaskResultViewController alloc] initWithTaskData:task];
    [self PushViewController:rVC animated:YES];
}

#pragma mark - Data Update
- (void)doHttpGetTaskList {
    
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchTaskList];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doGetTaskListFromUpdateTime:0 position:0 size:100
                                  success:succ failure:fail];
}

- (void)fetchTaskList {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE storeCode = ? ORDER BY %@ DESC", [ICRTask TableName], @"requireDate"];
        return [db executeQuery:sql, _m_store.code];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrData = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRTask class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}


@end
