//
//  CustomerViewController.m
//  ALand
//
//  Created by Z on 16/4/28.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "CustomerViewController.h"
#import "CustomerTopView.h"
#import "UITableView+Category.h"
#import "OrderDetailTableViewCell.h"
#import "CustomerDetailSectionHeader.h"
#import "JavenOrderModel.h"
#import "JavenGoodsDetails.h"
#import "CommotityListModel.h"
#import "CommodityDetailViewController.h"
#import "OrderDetailViewController.h"
#import "CommodityDetailTopView.h"
#import "MJRefresh.h"

#define kCellID @"cellId"
#define kPageSize 10
#define kTopHeight 291

@interface CustomerViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
@property (nonatomic, strong) CustomerTopView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrDatas;
@property (nonatomic, strong) CommodityDetailTopView *aTopBackView;
@property (nonatomic, assign) NSInteger page;


@end

@implementation CustomerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpTableView];
    [self setUpData];
    
    [self.view addSubview:self.aTopBackView];
    self.aTopBackView.buttonHome.hidden = YES;
    self.aTopBackView.alpha = 0;
    kButtonAddAction(self.aTopBackView.buttonBack, popAction);
    // Do any additional setup after loading the view from its nib.
}

- (NSMutableArray *)arrDatas {
    if (!_arrDatas) {
        _arrDatas = [NSMutableArray array];
    }
    return _arrDatas;
}

- (void)setUpData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"order/query" parameters:[self getParams] success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

        if (kIsResponseSuccess(responseObject)) {
            for (NSDictionary *dic in responseObject[@"queryResult"]) {
                JavenOrderModel *model = [JavenOrderModel modelObjectWithDictionary:dic];
                [weakSelf.arrDatas addObject:model];
            }
            
        }else{
            [MBProgressHUD Javen_showError:responseObject[@"message"] onView:weakSelf.view delay:0.7 complete:nil];
        }
        
        if ([(NSArray *)responseObject[@"queryResult"] count] < kPageSize) {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

    }];
}


- (NSDictionary *)getParams {
    NSDictionary *myDictionary = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                        @"parameters" : @[kDomain]},
                                                                      @{@"operation" : @"reseller uuid equals",
                                                                        @"parameters" : @[[UserInfo shareInstance].uuid]},
                                                                      @{@"operation" : @"consumer uuid equals",
                                                                        @"parameters" : @[self.customer.consumer.uuid]}],
                                                    @"orders" : @[@{@"field" : @"createInfo.time",
                                                                    @"direction" : @"desc"}],
                                                    @"pageSize" : @(kPageSize),
                                                    @"page" : @(self.page),
                                                    @"probePages" : @0},
                                   @"fetchParts" : @[@"string"]};
    return myDictionary;
}

- (void)setUpTableView {
    self.tableView = [UITableView groupedTableViewWithTarget:self cellNibName:@"OrderDetailTableViewCell" cellId:kCellID];
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.topEqualToView(self.view).leftEqualToView(self.view).rightEqualToView(self.view).bottomEqualToView(self.view);
    
    
    self.topView = [CustomerTopView viewWithNibName:@"CustomerTopView"];
    self.topView.labelCount.text = [NSString stringWithFormat:@"%.0f", self.customer.orderCount];
    self.topView.labelTotalIncome.text = [NSString stringWithFormat:@"%.2f", self.customer.commissionTotal];
    self.topView.labelPhoneNumber.text = self.customer.consumer.mobilephone;
    kButtonAddAction(self.topView.buttonBac, popAction);
    
    self.tableView.contentInset = UIEdgeInsetsMake(kTopHeight, 0, 0, 0);
    self.tableView.contentOffset = CGPointMake(0, -kTopHeight);
    WS(weakSelf)
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page += 1;
        [weakSelf setUpData];
    }];
    [self.tableView addSubview:self.topView];
    
}

- (void)viewDidLayoutSubviews {
    self.topView.frame = CGRectMake(0, -kTopHeight, kWidth, kTopHeight);
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CustomerDetailSectionHeader *header = [CustomerDetailSectionHeader viewWithNibName:@"CustomerDetailSectionHeader"];
    header.width = kWidth;
    [header viewWithModel:self.arrDatas[section]];
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrDatas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.arrDatas[section] goodsDetails] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID forIndexPath:indexPath];
    [cell cellWithModel:[self.arrDatas[indexPath.section] goodsDetails][indexPath.row]];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
    orderDetailVC.isShowNavigationBar = YES;
    orderDetailVC.model = self.arrDatas[indexPath.section];
    [self.navigationController pushViewController:orderDetailVC animated:YES];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CLog(@"%f",scrollView.contentOffset.y);
    NSInteger position = -kTopHeight + 64;
    if (scrollView.contentOffset.y > position) {
        self.aTopBackView.alpha = (scrollView.contentOffset.y - position) * 1.0 / 64 > 1 ? 1 : (scrollView.contentOffset.y - position) * 1.0 / 64.0;

    }else{
        self.aTopBackView.alpha = 0;
    }
}


- (CommodityDetailTopView *)aTopBackView {
    if (!_aTopBackView) {
        _aTopBackView = [CommodityDetailTopView viewWithNibName:@"CommodityDetailTopView"];
        _aTopBackView.frame = CGRectMake(0, 0, kWidth, 86);
    }
    return _aTopBackView;
}

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