//
//  StatementViewController.m
//  RealEstateManagement
//
//  Created by Z on 16/6/29.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "StatementViewController.h"
#import "StatementTableViewCell.h"
#import "NSDate+FormatterAdditions.h"
#import "SRMonthPicker.h"
#import "StatementListParamModel.h"
#import "StatementModel.h"
#import "VankeAppBoard_iPhone.h"
#import "CalculateHelper.h"
#import "StatementDetailViewController.h"
#import "UIScrollView+EmptyDataSet.h"
@interface StatementViewController ()<UITableViewDelegate, UITableViewDataSource, SRMonthPickerDelegate, UISearchBarDelegate, UITextFieldDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 已缴百分比 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalPaidPercent;

/** 共?家商铺 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalShop;
/** 应缴合计 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalShouldPay;
/** 已缴合计 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalPaidIn;
/** 未缴合计 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalUnPaid;
/** 输入框，用于呼出datePicker */
@property (weak, nonatomic) IBOutlet UITextField *textFieldSelectDate;
/** 年 */
@property (weak, nonatomic) IBOutlet UILabel *labelYear;
/** 月 */
@property (weak, nonatomic) IBOutlet UILabel *labelMonth;
/** 输入框 用于呼出datePicker */
@property (weak, nonatomic) IBOutlet UITextField *finishTextField;
/** 截止 年 */
@property (weak, nonatomic) IBOutlet UILabel *labelFinishYear;
/** 截止 月 */
@property (weak, nonatomic) IBOutlet UILabel *labelFinishMonth;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) NSArray *arrFilter;
@property (nonatomic, strong) NSMutableArray *arrUnClear;


@property (weak, nonatomic) IBOutlet UIButton *btnIsClear;
/** 当前选中的日期 */
@property (nonatomic, copy) NSString *startDate;
@property (nonatomic, copy) NSString *endDate;

/** 网络请求参数 */
@property (nonatomic, strong) StatementListParamModel *paramModel;

@property (nonatomic, strong) StatementModel *statementModel;
@end

@implementation StatementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [[VankeAppBoard_iPhone sharedInstance] hideMenu];
    self.btnIsClear.selected = YES;
    [self setDefaults];
    [self setUpDatePicker];
    self.paramModel = [[StatementListParamModel alloc] init];
    self.title = @"商铺对账单";
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.paramModel.pageSize = 9999;
    self.paramModel.pageNumber = 0;
    [self setUpData];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    self.navigationController.navigationBar.backgroundImage = [UIImage imageWithColor:kMainPurpleColor];
}

- (void)setDefaults {
    NSDate *currentDate = [NSDate date];
    self.startDate = [currentDate stringWithFormatter:@"%Y%m"];
    self.endDate = [currentDate stringWithFormatter:@"%Y%m"];
    self.labelYear.text = currentDate.yearString;
    self.labelMonth.text = currentDate.monthString;
    self.labelFinishYear.text = currentDate.yearString;
    self.labelFinishMonth.text = currentDate.monthString;
}

- (void)setUpDatePicker {
    SRMonthPicker *datePicker = [[SRMonthPicker alloc] initWithDate:[NSDate date]];
    datePicker.monthPickerDelegate = self;
    datePicker.yearFirst = YES;
    self.textFieldSelectDate.inputView = datePicker;
    self.finishTextField.inputView = datePicker;
}

/** 显示结清账户 */
- (IBAction)showSettleShop:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [self.tableView reloadData];
    [self calculateTop];
}

/** 计算顶部 */
- (void)calculateTop {
    NSDecimalNumber *totalPaid = nil;
    NSDecimalNumber *totalUpPaid = nil;
    NSDecimalNumber *totalAmount = nil;
    if (self.searchBar.text.length > 0) {
        for (int i = 0; i < self.arrFilter.count; i++) {
            StatementRecords *record = self.arrFilter[i];
            totalPaid = [CalculateHelper calculateNum1:totalPaid num2:[NSNumber numberWithDouble:record.paid] type:CalculateTypeAdd];
            totalUpPaid = [CalculateHelper calculateNum1:totalUpPaid num2:[NSNumber numberWithDouble:record.unpaid] type:CalculateTypeAdd];
            totalAmount = [CalculateHelper calculateNum1:totalAmount num2:[NSNumber numberWithDouble:record.amount] type:CalculateTypeAdd];
        }
    }else if(!self.btnIsClear.isSelected){
        for (int i = 0; i < self.arrUnClear.count; i++) {
            StatementRecords *record = self.arrUnClear[i];
            totalPaid = [CalculateHelper calculateNum1:totalPaid num2:[NSNumber numberWithDouble:record.unpaid] type:CalculateTypeAdd];
            totalUpPaid = [CalculateHelper calculateNum1:totalUpPaid num2:[NSNumber numberWithDouble:record.unpaid] type:CalculateTypeAdd];
            totalAmount = [CalculateHelper calculateNum1:totalAmount num2:[NSNumber numberWithDouble:record.amount] type:CalculateTypeAdd];
        }
        
    }else{
        
        self.labelTotalShouldPay.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.statementModel.amount]];
        self.labelTotalPaidIn.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.statementModel.paidTotal]];
        self.labelTotalUnPaid.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.statementModel.unpaidTotal]];
        self.labelTotalPaidPercent.text = [CalculateHelper getPercent:[NSNumber numberWithDouble:self.statementModel.paidTotal] num:[NSNumber numberWithDouble:self.statementModel.amount]];
        return;
    }
    
    
    self.labelTotalShouldPay.text = [CalculateHelper getMoneyStringFrom:totalAmount];
    self.labelTotalPaidIn.text = [CalculateHelper getMoneyStringFrom:totalPaid];
    self.labelTotalUnPaid.text = [CalculateHelper getMoneyStringFrom:totalUpPaid];
    self.labelTotalPaidPercent.text = [CalculateHelper getPercent:totalPaid num:totalAmount];

}



#pragma mark - SRMonthPickerDelegate
- (void)monthPickerDidChangeDate:(SRMonthPicker *)monthPicker {
    NSString *strDate = [monthPicker.date stringWithFormatter:@"%Y%m"];
    NSString *year = monthPicker.date.yearString;
    NSString *month = monthPicker.date.monthString;
    //判断是开始时间还是结束时间
    if ([self.textFieldSelectDate isFirstResponder]) {
        self.startDate = strDate;
        self.labelYear.text = year;
        self.labelMonth.text = month;
    }else{
        self.endDate = strDate;
        self.labelFinishYear.text = year;
        self.labelFinishMonth.text = month;
    }
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    [self.tableView reloadData];
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"shopName contains [cd] %@ OR shopCode contains [cd] %@", searchText, searchText];
    self.arrFilter = [self.statementModel.records filteredArrayUsingPredicate:pred];
    [self calculateTop];
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [self calculateTop];
    [self.tableView reloadData];
    HIDE_KEYBOARD;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    HIDE_KEYBOARD;
}

/** 网络请求 */
- (void)setUpData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *url = [NSString stringWithFormat:@"statement/query/%@~%@?authorizedOrgIn=%@&pageNumber=%@&pageSize=%@", self.startDate, self.endDate, self.org.code, @0, @9999];
    WS(weakSelf);
    [[ICRHTTPController sharedController] getUrl:url params:nil success:^(id data) {
        NSDictionary *dict = data;
        CLog(@"%@", dict.JSONString);
        [IBTLoadingView showTips:data[@"message"]];
        weakSelf.statementModel = [StatementModel modelObjectWithDictionary:dict[@"data"]];
//        weakSelf.labelTotalShop.text = [NSString stringWithFormat:@"共%@家",[NSNumber numberWithDouble:weakSelf.statementModel.paging.recordCount]];
        
        [weakSelf calculateTop];
        
        [weakSelf.tableView reloadData];
        [weakSelf.arrUnClear removeAllObjects];
        for (StatementRecords *records in weakSelf.statementModel.records) {
            if (records.unpaid != 0) {
                [weakSelf.arrUnClear addObject:records];
            }
        }
        
        [hud hide:YES];
    } failure:^(id data) {
        [hud hide:YES];
    }];

}


#pragma mark - tableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (self.searchBar.text.length > 0) {
        return self.arrFilter.count;
    }else if(!self.btnIsClear.isSelected){
        return self.arrUnClear.count;
    }else{
        return self.statementModel.records.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StatementTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StatementCell" forIndexPath:indexPath];
    if (self.searchBar.text.length > 0) {
        [cell setUpCellWithArray:self.arrFilter index:indexPath];
    }else if(!self.btnIsClear.isSelected){
        [cell setUpCellWithArray:self.arrUnClear index:indexPath];
    }else{
        [cell setUpCellWithArray:self.statementModel.records index:indexPath];
    }
    return cell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    StatementDetailViewController *detailVC = [self controllerWithIdentifier:@"StatementDetailViewController"];
    detailVC.startDate = self.startDate;
    detailVC.endDate = self.endDate;
    if (self.searchBar.text.length > 0) {
        detailVC.record = self.arrFilter[indexPath.row];
    }else if(!self.btnIsClear.isSelected){
        detailVC.record = self.arrUnClear[indexPath.row];
    }else{
        detailVC.record = self.statementModel.records[indexPath.row];
    }
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self setUpData];
}


#pragma mark - empty state
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_data"];
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"transform"];
    
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0)];
    
    animation.duration = 1;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

#pragma mark - lazyloading

- (NSMutableArray *)arrUnClear {
    if (!_arrUnClear) {
        _arrUnClear = [NSMutableArray array];
    }
    return _arrUnClear;
}
- (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
