//
//  HistoryViewController.m
//  vanke
//
//  Created by Z on 16/4/18.
//  Copyright © 2016年 gomore. All rights reserved.
//

#import "HistoryViewController.h"
#import "HistoryTopView.h"
#import "ICRHTTPController.h"
#import "VankeConfig.h"
#import "ICRAppMacro.h"
#import "ChooseShopViewController.h"


#define klineCount 19 //列数
#define kListWidth 100 //一个表格的宽度
#define kListHeight 40
#define kBottomHeight 55 //表格最底部的那行的宽度
@interface HistoryViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *bottomTitles;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) HistoryTopView *topView;
@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"历史";
    self.titles = @[@"日期",@"金额(元)",@"现金",@"刷卡",@"优惠券"];
    self.bottomTitles = @[@"总计",@"18800",@"1880",@"998",@"300"];

    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpTopView];
    [self setUPScrollView];
    [self setUpData];
    // Do any additional setup after loading the view.
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.topView.labelShopName.text = [NSString stringWithFormat:@"%@【%@】", self.shop.name, self.shop.code];
    
    if (self.shop == nil) {
        self.topView.labelShopName.text = @"";
    }else{
       self.topView.labelShopName.text = [NSString stringWithFormat:@"%@【%@】", self.shop.name, self.shop.code];
    }
}

- (void)dealloc {
    
}

- (void)chooseShopAction {
    ChooseShopViewController *chooseVC = [[ChooseShopViewController alloc] init];
    WS(weakSelf);
    chooseVC.chooseBlock = ^(VankeShopModel *shop){
        weakSelf.shop = shop;
        
        [weakSelf setUpData];
    };
    
    [self.navigationController pushViewController:chooseVC animated:YES];
}
- (void)setUPScrollView {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 150, SCREEN_WIDTH, SCREEN_HEIGHT - 150 - 64)];
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
}

- (void)setUpScrollViewWithDataArr:(NSArray *)array bottomArr:(NSArray *)bottomArr{
    [self.scrollView removeAllSubviews];
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.scrollView.contentSize = CGSizeMake(kListWidth * array.count, kListHeight * [array[0] count] + kBottomHeight);
    //双层for循环，i待代表列数，j代表行数
    for (int i = 0; i < array.count; i++) {
        for (int j = 1; j < [array[i] count]; j++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kListWidth * i, kListHeight +  kListHeight * (j - 1), kListWidth, kListHeight)];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = array[i][j];
            [self.scrollView insertSubview:label atIndex:0];//防止前面的别挡住
            label.backgroundColor = [UIColor colorWithRed:1.000 green:0.976 blue:0.953 alpha:1.000];
            
            if (i == 0) {
                label.tag = 3000 + j;
            }else if(i == 1){//金额
                label.textColor = [UIColor redColor];
            }
        }
        
        //顶部的浮动视图
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kListWidth * i, 0, kListWidth, 44)];
        label.tag = 1000 + i;
        label.text = array[i][0];
        label.font = [UIFont systemFontOfSize:19];
        label.textAlignment = NSTextAlignmentCenter;
        if (i != 0) {
            [self.scrollView insertSubview:label belowSubview:[self.scrollView viewWithTag:1000 + i -1]];//防止前面的被挡住
        }else{
            [self.scrollView addSubview:label];
        }
        label.backgroundColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor colorWithRed:1.000 green:0.976 blue:0.953 alpha:1.000];
        
        //底部浮动的视图
        UILabel *labelBottom = [[UILabel alloc] initWithFrame:CGRectMake(kListWidth * i, self.scrollView.contentOffset.y + self.scrollView.height - kBottomHeight, kListWidth, kBottomHeight)];
        labelBottom.text = bottomArr[i];
        labelBottom.backgroundColor = [UIColor grayColor];
        labelBottom.font = [UIFont systemFontOfSize:26];
        labelBottom.textAlignment = NSTextAlignmentCenter;
        labelBottom.tag = 2000 + i;
        [self.scrollView addSubview:labelBottom];
        if (i != 0) {
            
            [self.scrollView insertSubview:labelBottom belowSubview:[self.scrollView viewWithTag:2000 + i -1]];//防止前面的别挡住
            
            if (i==1) {
                labelBottom.textColor = [UIColor redColor];
            }else{
                labelBottom.textColor = [UIColor whiteColor];
            }
        }else{
            [self.scrollView addSubview:labelBottom];
        }
        
        
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (int i = 0; i < self.titles.count; i++) {
        UILabel *label = (UILabel *)[scrollView viewWithTag:1000 + i];
        label.y = scrollView.contentOffset.y;
        UILabel *labelBottom = (UILabel *)[scrollView viewWithTag:2000 + i];
        labelBottom.y = self.scrollView.contentOffset.y + self.scrollView.height - kBottomHeight;
        
        if (i == 0) {
            label.x = scrollView.contentOffset.x;
            labelBottom.x = scrollView.contentOffset.x;
        }
        
    }
    
    for (int i = 0; i < klineCount; i++) {
        UILabel *label = (UILabel *)[scrollView viewWithTag:3000 + i];
        label.x = scrollView.contentOffset.x;
    }
    
}

- (void)setUpTopView {
    HistoryTopView *topView = [self viewWithNibName:@"HistoryTopView"];
    topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 + 64);
    self.topView = topView;
    self.topView.userInteractionEnabled = YES;
    [topView.buttonChooseShop addTarget:self action:@selector(chooseShopAction) forControlEvents:UIControlEventTouchUpInside];
    [topView.buttonStartDate addTarget:self action:@selector(startDateAction) forControlEvents:UIControlEventTouchUpInside];
    [topView.buttonEndDate addTarget:self action:@selector(endDateAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topView.buttonQuery addTarget:self action:@selector(queryAction) forControlEvents:UIControlEventTouchUpInside];
    [self setUpDatePicker];

    [self.view addSubview:topView];
}



- (void)setUpDatePicker {
    UIDatePicker *startDatePicker = [[UIDatePicker alloc] init];
    startDatePicker.date = [NSDate date];
    startDatePicker.tag = 1100;
    startDatePicker.datePickerMode = UIDatePickerModeDate;
    [startDatePicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    self.topView.startDate.inputView = startDatePicker;
    
    UIDatePicker *endDatePicker = [[UIDatePicker alloc] init];
    endDatePicker.tag = 1200;
    endDatePicker.date = [NSDate date];
    endDatePicker.datePickerMode = UIDatePickerModeDate;
    [endDatePicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    self.topView.endDate.inputView = endDatePicker;
}


- (void)oneDatePickerValueChanged:(UIDatePicker *)datePicker {
    NSDate *date = datePicker.date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *strTime = [df stringFromDate:date];
    
    
    switch (datePicker.tag) {
        case 1100:
        {
            self.topView.startDate.text = strTime;
        }
            break;
        case 1200:
        {
            self.topView.endDate.text = strTime;
        }
            break;
        default:
            break;
    }
}

- (void)startDateAction {
    NSLog(@"start");
    [self.topView startDateBecomeFistRespond];
}

- (void)endDateAction {
    NSLog(@"end");
    [self.topView endDateBecomeFistRespond];
}

- (void)queryAction {
    [self setUpData];
}


- (id)viewWithNibName:(NSString *)viewName {
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:viewName owner:nil options:nil];
    return [nibView objectAtIndex:0];
}

- (void)setUpData {
    if (self.shop == nil) {
        
    }else{
        
        WS(weakSelf)
        NSDateFormatter *f = [[NSDateFormatter alloc] init];
        [f setDateFormat:@"yyyy-MM-dd"];
        NSDate *endDate = [f dateFromString:self.topView.endDate.text];
        
        NSDate *tomorrow = [NSDate dateWithTimeInterval:60 * 60 * 24 sinceDate:endDate];
        NSString *endStr = [f stringFromDate:tomorrow];
        
        NSDictionary *params = @{@"shopCodeEquals" : self.shop.code,
                                 @"beginDateEquals" : self.topView.startDate.text,
                                 @"endDateEquals" : self.topView.endDate.text,
                                 @"pageNumber" : @0,
                                 @"pageSize" : @0};
        
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        [httpCtrl getUrl:@"salesinput/query" params:params success:^(id data) {
            NSDictionary *dic = data;
            
            NSMutableArray *arrData = [NSMutableArray array];
            
            NSMutableArray *arrDate = [NSMutableArray array];//日期
            [arrDate addObject:@"日期"];
            NSMutableArray *arrAmount = [NSMutableArray array];//金额
            [arrAmount addObject:@"金额(元)"];
            
            NSMutableArray *payment = [NSMutableArray array];
            for (NSDictionary *obj in dic[@"data"][@"records"]) {
                [arrDate addObject:obj[@"salesDate"]];
                [arrAmount addObject:[NSString stringWithFormat:@"%.0f", [obj[@"amount"] floatValue]]];
                
                NSMutableArray *arr = [NSMutableArray array];
                for (NSDictionary *dic in obj[@"lines"]) {
                    [arr addObject:dic];
                }
                [payment addObject:arr];
            }
            
            [arrData addObject:arrDate];
            [arrData addObject:arrAmount];
            
            NSMutableArray *paytype = [NSMutableArray array];
            if (payment.count > 0) {
                for (NSDictionary *dic in payment[0]) {
                    NSMutableArray *apay = [NSMutableArray array];
                    [apay addObject:dic[@"payment"]];
                    [paytype addObject:apay];
                }
            }
            
            for (NSArray *arr in payment) {
                for (int i = 0;  i < arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    NSMutableArray *apay = paytype[i];
                    [apay addObject:[NSString stringWithFormat:@"%.0f", [dic[@"amount"] floatValue]]];
                }
                
            }
            
            [arrData addObjectsFromArray:paytype];
            
            NSMutableArray *arrBottom = [NSMutableArray array];
            for (int i = 0; i < arrData.count; i++) {
                if (i == 0) {
                    [arrBottom addObject:@"总计"];
                }else{
                    
                    NSInteger count = 0;
                    for (int j = 0; j < [arrData[i] count]; j++) {
                        if (j != 0) {
                            NSString *number = arrData[i][j];
                            NSInteger num = [number integerValue];
                            count = count + num;
                        }
                    }
                    NSString *result = [NSString stringWithFormat:@"%ld", (long)count];
                    [arrBottom addObject:result];
                    
                    
                }
            }
            
            [weakSelf setUpScrollViewWithDataArr:arrData bottomArr:arrBottom];
            
            NSLog(@"d");
        } failure:^(id data) {
            
        }];
    }
    
}


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