//
//  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"
#import "SaleInputPicCollectionViewController.h"
#import "CalculateHelper.h"
#define klineCount 19 //列数
#define kListWidth 100 //一个表格的宽度
#define kListHeight 40
#define kBottomHeight 50 //表格最底部的那行的宽度
@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;
@property (nonatomic, strong) NSArray *arrRecords;
@property (nonatomic, strong) UIImageView *imageNoData;


@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];
    self.imageNoData.hidden = NO;
    // 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)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 10) {
        self.topView.frame = CGRectMake(0 , 64, SCREEN_WIDTH, 150);
        self.view.height = SCREEN_HEIGHT + 30;
        self.imageNoData.centerY = self.view.height/2 + 100;
        self.scrollView.frame = CGRectMake(0, self.topView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - self.topView.height - 64 - 30);
    }
}

- (UIImageView *)imageNoData {
    if (!_imageNoData) {
        _imageNoData = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
        _imageNoData.center = self.view.center;
        _imageNoData.centerY = self.view.centerY + 10;
        _imageNoData.contentMode = UIViewContentModeScaleToFill;
        _imageNoData.image = [UIImage imageNamed:@"no_data@3x"];
        [self.view addSubview:_imageNoData];
    }
    return _imageNoData;
}

- (void)chooseShopAction {
    if ([[VankeCommonModel sharedInstance] curUserIsTenant]) {
        return;
    }
    
    ChooseShopViewController *chooseVC = [[ChooseShopViewController alloc] init];
    chooseVC.projectId = self.projectid;
    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);
    if ([array[0] count] <= 1 ) {
        self.imageNoData.hidden = NO;
    }else{
        self.imageNoData.hidden = YES;
    }
    //双层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];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
            label.userInteractionEnabled = YES;
            [label addGestureRecognizer:tap];
            label.tag = j - 1;
            if (i == 0) {
                label.tag = 3000 + j;
            }else if(i == 2){//金额
                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 lightGrayColor];
        labelBottom.font = [UIFont systemFontOfSize:19];
        labelBottom.textAlignment = NSTextAlignmentCenter;
        labelBottom.numberOfLines = 2;
        labelBottom.tag = 2000 + i;
        [self.scrollView addSubview:labelBottom];
        if (i != 0) {
            
            [self.scrollView insertSubview:labelBottom belowSubview:[self.scrollView viewWithTag:2000 + i -1]];//防止前面的别挡住
            
            if (i==2) {
                labelBottom.textColor = [UIColor redColor];
            }else{
                labelBottom.textColor = [UIColor whiteColor];
            }
        }else{
            [self.scrollView addSubview:labelBottom];
        }
        
        
    }
}

- (void)tap:(UITapGestureRecognizer *)tap {
    CLog(@"%d",tap.view.tag);
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"SalesInPut" bundle:nil];
    SaleInputPicCollectionViewController *picVC = [storyBoard instantiateViewControllerWithIdentifier:@"SaleInputPicCollectionViewController"];
    NSInteger row ;
    if (tap.view.tag > 2999) {
        row = tap.view.tag - 3001;
    }else{
        row = tap.view.tag;
    }
    picVC.title = self.arrRecords[row][@"salesDate"];
    picVC.attachmentUuid = self.arrRecords[row][@"attachmentUuid"];
    NSArray *attachments = self.arrRecords[row][@"attachments"];
    [self.navigationController pushViewController:picVC animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (int i = 0; i < 20; 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 < 20; 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{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

        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};
        CLog(@"》》%@",params.JSONString);
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        [httpCtrl getUrl:@"salesinput/query" params:params success:^(id data) {
            NSDictionary *dic = data;
            CLog(@"》》%@",dic.JSONString);
            NSMutableArray *arrData = [NSMutableArray array];
            
            NSMutableArray *arrDate = [NSMutableArray array];//日期
            [arrDate addObject:@"日期"];
            NSMutableArray *arrBills = [NSMutableArray array];//笔数
            [arrBills addObject:@"笔数"];
            NSMutableArray *arrAmount = [NSMutableArray array];//金额
            [arrAmount addObject:@"金额(元)"];
            
            // 日期金额笔数这三项是固定在前面，所以在前面先写，后面的是动态的。
            weakSelf.arrRecords = dic[@"data"][@"records"];
            NSMutableArray *payment = [NSMutableArray array];
            for (NSDictionary *obj in dic[@"data"][@"records"]) {
                [arrDate addObject:obj[@"salesDate"]];
                [arrAmount addObject:[CalculateHelper getMoneyStringFrom:obj[@"amount"]]];
                [arrBills addObject:[CalculateHelper getMoneyStringFrom:obj[@"transactions"] Lenth:0 isSeparate:NO]];
                
                NSMutableArray *arr = [NSMutableArray array];
                for (NSDictionary *dic in obj[@"payments"]) {
                    [arr addObject:dic];
                }
                [payment addObject:arr];
            }
            
            [arrData addObject:arrDate];
            [arrData addObject:arrBills];
            [arrData addObject:arrAmount];
            
            NSMutableArray *paytype = [NSMutableArray array];
            if (payment.count > 0) {
                for (NSDictionary *dic in payment[0]) {
                    NSMutableArray *apay = [NSMutableArray array];
                    [apay addObject:dic[@"paymentName"]];
                    [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:[CalculateHelper getMoneyStringFrom:dic[@"amount"]]];
                }
                
            }
            
            [arrData addObjectsFromArray:paytype];
            
            NSMutableArray *arrBottom = [NSMutableArray array];
            for (int i = 0; i < arrData.count; i++) {
                if (i == 0) {
                    [arrBottom addObject:@"总计"];
                }else{
                    
                    NSDecimalNumber *count = [NSDecimalNumber decimalNumberWithString:@"0"];
                    for (int j = 0; j < [arrData[i] count]; j++) {
                        if (j != 0) {
                            NSString *number = arrData[i][j];
                            count = [CalculateHelper calculateNum1:count num2:number type:CalculateTypeAdd];
                        }
                    }
                    
                    NSString *result;
                    if (i == 1) {
                        result = [CalculateHelper getMoneyStringFrom:count Lenth:0 isSeparate:NO];
                    }else{
                        result = [CalculateHelper getMoneyStringFrom:count Lenth:2 isSeparate:NO];

                    }
                    [arrBottom addObject:result];
                    
                }
            }
            
            //添加附件那一行
            NSMutableArray *arrAttachment = [NSMutableArray array];
            for (int i = 0; i < [arrData[0] count]; i++) {
                if (i == 0) {
                    [arrAttachment addObject:@"附件"];
                }else{
                    [arrAttachment addObject:@"点击查看"];
                }
            }
            [arrData addObject:arrAttachment];
            [arrBottom addObject:@""];
            [weakSelf setUpScrollViewWithDataArr:arrData bottomArr:arrBottom];
            [hud hide:YES];
            NSLog(@"d");
            
        } failure:^(id data) {
            [hud hide:YES];
        }];
    }
    
}




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