//
//  SaleInputHistoryViewController.m
//  RealEstateManagement
//
//  Created by Javen on 2016/10/12.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "CalculateHelper.h"
#import "HistoryTopView.h"
#import "MMViewController.h"
#import "SaleInputHistoryViewController.h"
#import "SaleInputHistory.h"
@interface SaleInputHistoryViewController ()
@property (weak, nonatomic) IBOutlet HistoryTopView *topView;
@property (nonatomic, strong) MMViewController *sheetVC;
@property (nonatomic, strong) UIImageView *imageNoData;
@property (nonatomic, strong) NSMutableArray *arrData;

@end

@implementation SaleInputHistoryViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"历史查询";
    WS(weakSelf);
    [self.topView setBlockQuery:^{
        [weakSelf httpHistoryData];
    }];
    [self updateUI];
    [self configNoDataPic];
    // Do any additional setup after loading the view.
}

- (void)viewDidLayoutSubviews
{
    self.imageNoData.frame = CGRectMake(0, self.topView.bottom + 20, 150, 150);
    self.imageNoData.centerX = self.view.centerX;
    self.imageNoData.centerY = self.sheetVC.view.centerY + self.topView.bottom;
}
- (void)updateUI {
    if (self.contract == nil) {
        self.topView.labelShopName.text = @"请选择合同";
        return;
    }
    self.topView.labelShopName.text = self.contract.name;
}

- (void)httpHistoryData
{
    NSString *startDate = [NSString stringWithFormat:@"%@ 00:00:00", self.topView.startDate.text];
    NSString *endDate = [NSString stringWithFormat:@"%@ 00:00:00", self.topView.endDate.text];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.contract.uuid, @"contract", [NSDictionary dictionaryWithObjectsAndKeys:startDate, @"beginDate", endDate, @"endDate", nil], @"dateRange", nil];
    [MBProgressHUD j_loading];
    WS(weakSelf);
    [ZJHttpManager POST:@"hdmall/salesinput/getSalesTotal" parameters:params complete:^(id responseObject, NSError *error) {
        [MBProgressHUD j_hideLoadingView];
        if (kIsResponse) {
            [weakSelf configDataArray:responseObject[@"data"]];
        } else {
            kFalseHttpTips;
        }
    }];
    
    
}

- (void)configNoDataPic
{
    if (self.contract == nil) {
        self.sheetVC.view.hidden = YES;
        self.imageNoData.hidden = NO;
    }

    if (self.arrData.count > 0) {
        self.sheetVC.view.hidden = NO;
        self.imageNoData.hidden = YES;
    } else {
        self.sheetVC.view.hidden = YES;
        self.imageNoData.hidden = NO;
    }
}

/**
 *  跳转选择商铺界面
 */
- (IBAction)actionChooseShop:(UIButton *)sender
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择合同" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    
    for (UserInfo_contracts *contract in AppGlobal.user.contracts) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:contract.name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.contract = [HMSaleInputDetail_contract modelWithDic:contract.toDictionary];
            self.topView.labelShopName.text = contract.name;
        }];
        [alert addAction:action];
    }
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (void)configDataArray:(NSArray *)arr
{
    NSMutableArray *arrData = [NSMutableArray array];
    self.arrData = arrData;
    for (NSDictionary *dict in arr) {
        SaleInputHistory *model = [SaleInputHistory modelWithDic:dict];
        [arrData addObject:model];
    }

    NSMutableArray *totalData = [NSMutableArray array];
    //第一行的数据
    NSMutableArray *data = [NSMutableArray array];
    /**
     *  支付方式
     */
    NSMutableArray *payments = [NSMutableArray array];
    [data addObject:@"日期"];
    [data addObject:@"金额(元)"];
    for (SaleInputHistory *model in arrData) {
        for (NSInteger i = 0; i < model.details.count; i++) {
            SaleInputHistory_details *payment = model.details[i];
            if (![data containsObject:payment.payment.name]) {
                [data addObject:payment.payment.name];
                [payments addObject:payment.payment.name];
            }
        }
    }
//    [data addObject:@"附件"];
    [totalData addObject:data];

    //把所有支付金额分类归纳
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (SaleInputHistory *model in arrData) {
        for (SaleInputHistory_details *payment in model.details) {
            NSMutableArray *array = [dict objectForKey:payment.payment.name];
            if (array) {
                [array addObject:payment.total];
            } else {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:payment.total];
                [dict setObject:array forKey:payment.payment.name];
            }
        }
    }

    //中间的数据
    for (NSInteger i = 0; i < arrData.count; i++) {
        SaleInputHistory *historyModel = arrData[i];
        NSMutableArray *arrCenter = [NSMutableArray array];
        [arrCenter addObject:historyModel.date];
        [arrCenter addObject:[NSString stringWithFormat:@"%.2f", historyModel.total.doubleValue]];
        for (NSInteger j = 0; j < payments.count; j++) {
            NSString *paymentName = payments[j];
            BOOL isHas = NO;
            for (SaleInputHistory_details *payment in historyModel.details) {
                if ([paymentName isEqualToString:payment.payment.name]) {
                    [arrCenter addObject:[CalculateHelper getMoneyStringFrom:payment.total]];
                    isHas = YES;
                }
            }

            if (!isHas) {
                [arrCenter addObject:@"0.00"];
            }
        }
//        [arrCenter addObject:@"查看附件"];
        [totalData addObject:arrCenter];
    }

    //最后一行的数据
    NSMutableArray *bottomRow = [NSMutableArray array];
    [bottomRow addObject:@"总计"];
    NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:@"0"];
    for (SaleInputHistory *model in arrData) {
        total = [CalculateHelper add:total num2:model.total];
    }
    [bottomRow addObject:[CalculateHelper getMoneyStringFrom:total]];

    for (NSInteger i = 0; i < payments.count; i++) {
        NSString *paymentName = payments[i];
        NSMutableArray *arrPaymentNumber = [dict objectForKey:paymentName];
        NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:@"0"];
        for (NSNumber *obj in arrPaymentNumber) {
            number = [CalculateHelper add:number num2:obj];
        }
        [bottomRow addObject:[CalculateHelper getMoneyStringFrom:number]];
    }

//    [bottomRow addObject:@"附件"];

    NSInteger totalRowCount = totalData.count;
    if (totalRowCount < 9) {
        for (NSInteger i = totalRowCount; i < 9; i++) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSString *str in bottomRow) {
                [arr addObject:@""];
            }
            [totalData addObject:arr];
        }
    }
    [totalData addObject:bottomRow];

    self.sheetVC.tableData = totalData;
    [self.sheetVC reloadData];
    [self configNoDataPic];
}

- (UIImageView *)imageNoData
{
    if (!_imageNoData) {
        _imageNoData = [[UIImageView alloc] init];
        _imageNoData.center = self.view.center;
        _imageNoData.contentMode = UIViewContentModeScaleAspectFit;
        _imageNoData.image = [UIImage imageNamed:@"list_nodata"];
        [self.view addSubview:_imageNoData];
    }
    return _imageNoData;
}

- (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.
    if ([segue.identifier isEqualToString:@"MMViewController"]) {
        self.sheetVC = segue.destinationViewController;
    }
}

/*
*/

@end