//
//  MyBillViewController.m
//  ALand
//
//  Created by Z on 16/5/16.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "MyBillViewController.h"
#import "JavenSingleSortView.h"
#import "UITableView+Category.h"
#import "MyBillsTableViewCell.h"
#import "JavenBillModel.h"
#import "MyBillSectionHeader.h"
#import "NoBillHistoryView.h"
#define kCellID @"MyBillsTableViewCell.h"
#define kPageSize @999
#define kHeader @"header"
@interface MyBillViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) id state;
@property (nonatomic, strong) id confirmed;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrDatas;
@property (nonatomic, strong) NSMutableDictionary *dicMonthData;
@property (nonatomic, strong) NSMutableArray *arrSortedData;
@property (nonatomic, strong) NSMutableArray *arrSortedMonths;
@property (nonatomic, strong) NoBillHistoryView *noBillHistoryView;
@property (nonatomic, strong) JavenSingleSortView *sortView;





@end

@implementation MyBillViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.state = [NSNull null];
    self.confirmed = [NSNull null];
    JavenSingleSortView *sortView = [JavenSingleSortView sortViewTitles:@[@"全部账单",@"进账单",@"出账单",@"待确认账单"]];
    self.sortView = sortView;
    sortView.frame = CGRectMake(0, 0, 150, 35);
    self.navigationItem.titleView = sortView;

    sortView.leftTableSelect = ^(NSInteger row){
        [self changeConditions:row];
    };
    [self setUpTableView];
    [self setUpData];

    [self.view addSubview:self.noBillHistoryView];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    // Do any additional setup after loading the view from its nib.
}
- (void)popAction {
    [super popAction];
    [self.sortView hide];
}

- (void)viewWillLayoutSubviews {
    self.noBillHistoryView.frame = CGRectMake(0, 0, kWidth, kHeight);
}

#pragma mark - tableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrSortedMonths.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return  30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MyBillSectionHeader *header = [MyBillSectionHeader viewWithNibName:@"MyBillSectionHeader"];;
    [header setHeaderTitle:self.arrSortedMonths[section]];
    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyBillsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID forIndexPath:indexPath];
    [cell cellWithModel:self.arrSortedData[indexPath.section][indexPath.row]];
    return cell;
}


- (void)setUpTableView {
    self.tableView = [UITableView plainTableViewWithTarget:self cellNibName:@"MyBillsTableViewCell" cellId:kCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"MyBillSectionHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:kHeader];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, 0, kWidth, kHeight - 64);
    [self.view addSubview:self.tableView];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kWidth, 40)];
    label.text = @"如需查看更多记录，请联系客服";
    label.textColor = kTextColorGray;
    self.tableView.tableFooterView = label;
    self.tableView.backgroundColor = kBacroundColor;

}


- (void)changeConditions:(NSInteger)row
{
    self.navigationController.navigationBar.userInteractionEnabled = NO;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
        switch (row) {
            case 0:
            {
                self.state = [NSNull null];
                self.confirmed = @"";

            }
                break;
            case 1://
            {
                self.state = @[@"income"];
                self.confirmed = @"confirmed only";

            }
                break;
            case 2://
            {
                self.state = @[@"refund",@"withdraw"];
                self.confirmed = [NSNull null];

            }
                break;
            case 3://
            {
                self.state = @[@"income"];
                self.confirmed = @"unconfirmed only";

            }
                break;
            
                
            default:
                break;
        }
        [self resetReloadData];

}

- (void)resetReloadData {
    [self.dicMonthData removeAllObjects];
    [self.arrSortedData removeAllObjects];
    [self.arrDatas removeAllObjects];
    [self.arrSortedMonths removeAllObjects];
    [self setUpData];
    
   
}


- (void)setUpData {
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"commission/queryAccountHistory" parameters:[self getParams] success:^(NSURLSessionDataTask *task, id responseObject) {
        if (kIsResponseSuccess(responseObject)) {
            for (NSDictionary *dic in responseObject[@"queryResult"]) {
                JavenBillModel *model = [JavenBillModel modelObjectWithDictionary:dic];
                
                [weakSelf.dicMonthData setObject:model forKey:[model.createInfo.time substringWithRange:NSMakeRange(0, 7)]];
                
                [weakSelf.arrDatas addObject:model];
            }
            
            weakSelf.noBillHistoryView.hidden = !weakSelf.arrDatas.count == 0;
            
            [weakSelf sortModelWithMonth];
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            self.navigationController.navigationBar.userInteractionEnabled = YES;
            
            [weakSelf.tableView reloadData];
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)sortModelWithMonth
{
    NSArray *months = self.dicMonthData.allKeys;
//    NSArray *months = @[@"2016-01",@"2015-03",@"2016-01",@"2016-05"];

    NSArray *sortMonths = [months sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    
    NSInteger count = sortMonths.count > 3 ? 3 : sortMonths.count;
    for (NSInteger  i = 0; i < count; i++) {
        NSMutableArray *array = [NSMutableArray array];
        for (JavenBillModel *model in self.arrDatas) {
            NSString *timeStr = [model.createInfo.time substringWithRange:NSMakeRange(0, 7)];
            if ([timeStr isEqualToString:sortMonths[i]]) {
                CLog(@"%@", model.createInfo.time);
                [array addObject:model];
            }
        }
        [self.arrSortedMonths addObject:sortMonths[i]];
        [self.arrSortedData addObject:array];
    }
    
}

- (NSDictionary *)getParams
{
    NSDictionary *myDictionary = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                        @"parameters" : @[kDomain]},
                                                                      @{@"operation" : @"reseller uuid equals",
                                                                        @"parameters" : @[[UserInfo shareInstance].reseller.uuid]},
                                                                      @{@"operation" : @"action equals",
                                                                        @"parameters" : self.state},
                                                                      @{@"operation" : self.confirmed,
                                                                        @"parameters" : [NSNull null]}
                                                                      ],
                                                    @"orders" : @[@{@"field" : @"createInfo.time",
                                                                    @"direction" : @"desc"}],
                                                    @"pageSize" : kPageSize,
                                                    @"page" : @0,
                                                    @"probePages" : @0},
                                   @"fetchParts" : @[@"string"]};
    return myDictionary;
}


#pragma mark - lazyLoading

- (NSMutableArray *)arrDatas {
    if (!_arrDatas) {
        _arrDatas = [NSMutableArray array];
    }
    return _arrDatas;
}

- (NSMutableDictionary *)dicMonthData {
    if (!_dicMonthData) {
        _dicMonthData = [NSMutableDictionary dictionary];
    }
    return _dicMonthData;
}

- (NSMutableArray *)arrSortedData {
    if (!_arrSortedData) {
        _arrSortedData = [NSMutableArray array];
    }
    return _arrSortedData;
}

- (NSMutableArray *)arrSortedMonths {
    if (!_arrSortedMonths) {
        _arrSortedMonths = [NSMutableArray array];
    }
    return _arrSortedMonths;
}

- (NoBillHistoryView *)noBillHistoryView {
    if (!_noBillHistoryView) {
        _noBillHistoryView = [NoBillHistoryView viewWithNibName:@"NoBillHistoryView"];
        _noBillHistoryView.hidden = YES;
    }
    return _noBillHistoryView;
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
