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

#import "StatementDetailViewController.h"
#import "StatementDetailCell.h"
#import "StatementDetailModel.h"
#import "SRMonthPicker.h"
#import "UIScrollView+EmptyDataSet.h"
#import "CalculateHelper.h"
#import "StatementDetailItems.h"
@interface StatementDetailViewController ()<UITableViewDelegate, UITableViewDataSource,SRMonthPickerDelegate, UITextFieldDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) StatementDetailModel *detailModel;
/** 应缴 */
@property (weak, nonatomic) IBOutlet UILabel *labelShoudPay;
/** 已缴 */
@property (weak, nonatomic) IBOutlet UILabel *labelPaid;
/** 未缴 */
@property (weak, nonatomic) IBOutlet UILabel *labelUnpaid;
/** year start */
@property (weak, nonatomic) IBOutlet UILabel *labelYearStart;
/** month start */
@property (weak, nonatomic) IBOutlet UILabel *labelMonthStart;
/** year start */
@property (weak, nonatomic) IBOutlet UILabel *labelYearEnd;
/** month end */
@property (weak, nonatomic) IBOutlet UILabel *labelMontEnd;
/** textfield start */
@property (weak, nonatomic) IBOutlet UITextField *textFieldStart;
/** textfield end */
@property (weak, nonatomic) IBOutlet UITextField *textFieldEnd;
/** 缴款率 */
@property (weak, nonatomic) IBOutlet UILabel *labelPaidRate;
@property (weak, nonatomic) IBOutlet UIButton *btnIsShowClear;
@property (nonatomic, strong) NSMutableArray *arrUnClear;




@end

@implementation StatementDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.btnIsShowClear.selected = YES;
    self.title = self.record.shopName;
    NSDate *selectStart = [self getDateFromString:self.startDate];
    NSDate *selectEnd = [self getDateFromString:self.endDate];
    [self setStart:selectStart];
    [self setEnd:selectEnd];
    self.textFieldStart.delegate = self;
    self.textFieldEnd.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.tableFooterView = [UIView new];
    [self setUpDatePicker];
    [self setUpData];
    
    for (StatementDetailItems *items in self.detailModel.items) {
        if (items.unpaid != 0) {
            [self.arrUnClear addObject:items];
        }
    }
}


/** 设置开始时间 */
- (void)setStart:(NSDate *)date {
    self.labelYearStart.text = date.yearString;
    self.labelMonthStart.text = date.monthString;
}

/** 设置结束时间 */
- (void)setEnd:(NSDate *)date {
    self.labelYearEnd.text = date.yearString;
    self.labelMontEnd.text = date.monthString;
}

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

#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.textFieldStart isFirstResponder]) {
        self.startDate = strDate;
        self.labelYearStart.text = year;
        self.labelMonthStart.text = month;
    }else{
        self.endDate = strDate;
        self.labelYearEnd.text = year;
        self.labelMontEnd.text = month;
    }
}

- (void)setUpData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSString *url = [NSString stringWithFormat:@"statement?contract=%@&beginSettle=%@&endSettle=%@",self.record.contract,self.startDate, self.endDate];
    WS(weakSelf);
    [[ICRHTTPController sharedController] getUrl:url params:nil success:^(id data) {
        NSDictionary *dic = data;
        weakSelf.detailModel = [StatementDetailModel modelObjectWithDictionary:dic[@"data"]];
        
        weakSelf.labelShoudPay.text = [NSString stringWithFormat:@"%.2f", weakSelf.detailModel.amount];
        weakSelf.labelPaid.text = [NSString stringWithFormat:@"%.2f",weakSelf.detailModel.paid];
        weakSelf.labelUnpaid.text = [NSString stringWithFormat:@"%.2f",weakSelf.detailModel.unpaid];
        
        //缴款率
        NSString *paidRate = [CalculateHelper getPercent:[NSNumber numberWithDouble:weakSelf.detailModel.paid] num:[NSNumber numberWithDouble:weakSelf.detailModel.amount]];
        weakSelf.labelPaidRate.text = paidRate;
        
        [self.arrUnClear removeAllObjects];
        for (StatementDetailItems *items in weakSelf.detailModel.items) {
            if (items.unpaid != 0) {
                [self.arrUnClear addObject:items];
            }
        }
        
        [weakSelf.tableView reloadData];
        [weakSelf calculateTop];
        [hud hide:YES];
        CLog(@"%@", dic.JSONString);
    } failure:^(id data) {
        
    }];
}

/** 计算顶部 */
- (void)calculateTop {
    NSDecimalNumber *totalPaid = nil;
    NSDecimalNumber *totalUpPaid = nil;
    NSDecimalNumber *totalAmount = nil;
    if(!self.btnIsShowClear.isSelected){
        for (int i = 0; i < self.arrUnClear.count; i++) {
            StatementRecords *record = self.arrUnClear[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{
        
        self.labelShoudPay.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.detailModel.amount] Lenth:2 isSeparate:YES];
        self.labelPaid.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.detailModel.paid] Lenth:2 isSeparate:YES];
        self.labelUnpaid.text = [CalculateHelper getMoneyStringFrom:[NSNumber numberWithDouble:self.detailModel.unpaid] Lenth:2 isSeparate:YES];
        self.labelPaidRate.text = [CalculateHelper getPercent:[NSNumber numberWithDouble:self.detailModel.paid] num:[NSNumber numberWithDouble:self.detailModel.amount]];
        return;
    }
    
    
    self.labelShoudPay.text = [CalculateHelper getMoneyStringFrom:totalAmount Lenth:2 isSeparate:YES];
    self.labelPaid.text = [CalculateHelper getMoneyStringFrom:totalPaid Lenth:2 isSeparate:YES];
    self.labelUnpaid.text = [CalculateHelper getMoneyStringFrom:totalUpPaid Lenth:2 isSeparate:YES];
    self.labelPaidRate.text = [CalculateHelper getPercent:totalPaid num:totalAmount];
    
}


#pragma mark - tableView DataSource
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.btnIsShowClear.isSelected) {
        return self.detailModel.items.count;
    }else{
        return self.arrUnClear.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StatementDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StatementDetailCell" forIndexPath:indexPath];
    [cell setUpCellWithModelArray:self.btnIsShowClear.isSelected ? self.detailModel.items : self.arrUnClear index:indexPath];
    return cell;
}

- (NSDate *)getDateFromString:(NSString *)string {
    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyyMM"];
    return [f dateFromString:string];
}

- (IBAction)actionClear:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [self.tableView reloadData];
    [self calculateTop];
}
#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 = 0.25;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -100;
}
- (NSMutableArray *)arrUnClear {
    if (!_arrUnClear) {
        _arrUnClear = [NSMutableArray array];
    }
    return _arrUnClear;
}
#pragma mark - textfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self setUpData];
}

- (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
