//
//  MainViewController.m
//  Car
//
//  Created by Javen on 2016/12/23.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "MainViewController.h"
#import "HttpCilent.h"
#import "OrderListTableViewCell.h"
#import "OrderListModel.h"
#import "OrderListFilterViewController.h"
#import "OrderDetailViewController.h"
@interface MainViewController ()
@property (strong, nonatomic) OrderListFilterViewController *filterVC;
@property (strong, nonatomic) OrderQueryDefintion *param;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintTop;
@property (weak, nonatomic) IBOutlet UIButton *btnSelectAll;
@property (weak, nonatomic) IBOutlet UIButton *btnCheck;
@property (strong, nonatomic) NSMutableSet *setBillToCheck;
@property (weak, nonatomic) IBOutlet UILabel *labelCount;
@property (weak, nonatomic) IBOutlet UILabel *labelAmount;

/**
 底部的面板
 */
@property (weak, nonatomic) IBOutlet UIView *bottomBoard;
@property (strong, nonatomic) TradeStatisticsResult *total;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self httpRequest];
    self.constraintTop.constant = 0;
    [self.view layoutIfNeeded];
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionNoti:) name:kNotiSelectBill object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    kGlobal.mainVC = self;
}

- (void)httpRequest {
    self.param.pageSize = self.pageSize;
    self.param.pageNumber = self.page;
    NSDictionary *param = [self.param toDictionary];
    [MBProgressHUD j_loading:@"加载中…"];
    WS(weakSelf);
    [kHttp POST:kOrderQueryUrl
        parameters:param
          complete:^(id _Nullable response, NSError *_Nullable error) {
              [MBProgressHUD j_hideLoadingView];

              if (kRsSuccess(response)) {
                  weakSelf.total = [[TradeStatisticsResult alloc] initWithDictionary:response[@"data"][@"total"] error:nil];
                  for (NSDictionary *dict in response[@"data"][@"records"]) {
                      OrderListModel *model = [[OrderListModel alloc] initWithDictionary:dict error:nil];
                      if (weakSelf.btnSelectAll.isSelected) {
                          model.isSelected = YES;
                      }
                      [weakSelf.arrData addObject:model];
                  }
                  weakSelf.bottomBoard.hidden = weakSelf.arrData.count == 0;
                  [weakSelf listTableViewReloadData];

              } else {
                  kShowRsMsg(response);
                  [weakSelf.tableView j_endRefresh];
                  if (self.page > 0) {
                      self.page--;
                  }
              }

          }];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    OrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderListTableViewCell" forIndexPath:indexPath];
    [cell configCellArray:self.arrData indexPath:indexPath isShow:self.btnCheck.isSelected isAll:self.btnSelectAll.selected];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [super tableView:tableView didSelectRowAtIndexPath:indexPath];

//    kDebugIndex(indexPath);
}

- (void)listDidSelect:(id)model {
//    if (self.btnCheck.isSelected) {
//        return;
//    }
    OrderDetailViewController *detailVC = [OrderDetailViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    detailVC.model = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - actions
- (IBAction)actionLeft:(UIBarButtonItem *)sender {
    if (kGlobal.sideSlipVC.isShowLeft) {
        [kGlobal.sideSlipVC showMainView];
    } else {
        [kGlobal.sideSlipVC showLeftView];
    }
}

- (IBAction)actionRight:(id)sender {
    if (self.filterVC.isOpen) {
        [self.filterVC hideFilterView];
    } else {
        self.filterVC.view.frame = self.view.bounds;
        [self.view addSubview:self.filterVC.view];
        [self.filterVC showFilterView];
    }
}
- (IBAction)actionCheck:(UIButton *)sender {

    if (!sender.isSelected) {
        sender.selected = YES;
        [self.tableView reloadData];
        self.constraintTop.constant = 44;
        [UIView animateWithDuration:0.3
                         animations:^{
                             [self.view layoutIfNeeded];
                         }];
    } else {
        if (self.btnSelectAll.isSelected && self.setBillToCheck.count == 0) {
            [self actionCancelCheck:nil];
            return;
        }
        
        if (self.setBillToCheck.count == 0) {
            [MBProgressHUD j_error:@"请选择对账的单据！" complete:nil];
            return;
        }

        [self httpCheckBill];
    }
}

/**
 全选操作

 @param isAll 是否全选
 */
- (void)configSelectData:(BOOL)isAll {
    for (OrderListModel *model in self.arrData) {
        if (![model.checkState isEqualToString:@"checked"]) {
            model.isSelected = isAll;
        }
    }
    [self.tableView reloadData];
}

- (void)setTotal:(TradeStatisticsResult *)total {
    _total = total;
    self.labelCount.text = [NSString stringWithFormat:@"%lld", total.orderCount];
    self.labelAmount.text = [NSString stringWithFormat:@"￥ %.2f", total.totalAmount ? total.totalAmount : 0];
}

- (IBAction)actionSelectAll:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [self configSelectData:sender.isSelected];
}

- (IBAction)actionCancelCheck:(id)sender {
    self.constraintTop.constant = 0;
    [UIView animateWithDuration:0.3
                     animations:^{
                         [self.view layoutIfNeeded];
                     }];
    self.btnCheck.selected = NO;
    [self.tableView reloadData];
}

- (void)actionNoti:(NSNotification *)noti {

    NSLog(@"%@", noti);
    OrderListModel *model = noti.object;
    if (model.isSelected) {
        [self.setBillToCheck addObject:model];
    } else {
        [self.setBillToCheck removeObject:model];
    }

    self.btnSelectAll.selected = [self configIsAll];
}


/**
 判断是否全选
 */
- (BOOL)configIsAll {
    for (OrderListModel *model in self.arrData) {
        if (![model.checkState isEqualToString:@"checked"]) {
            if (!model.isSelected) {
                return NO;
            }
        }
    }
    return YES;
}

- (void)showShadow {
    self.shadow.hidden = NO;
}

- (void)hideShadow {
    self.shadow.hidden = YES;
}

- (void)httpCheckBill {
    CheckOrderRequest *request = [[CheckOrderRequest alloc] init];
    request.userId = kUser.fid;
    NSMutableArray *arr = [NSMutableArray array];
    for (OrderListModel *model in self.setBillToCheck.allObjects) {
        [arr addObject:model.fid];
    }
    request.orderIds = arr;
    WS(weakSelf);
    [kHttp POST:kUrlCheck
        parameters:request.toDictionary
          complete:^(id _Nullable response, NSError *_Nullable error) {
              if (kRsSuccess(response)) {
                  [MBProgressHUD j_success:@"对账成功！" complete:nil];
                  
                  for (OrderListModel *model in weakSelf.setBillToCheck.allObjects) {
                      model.checkState = @"checked";
                  }
                  [weakSelf.setBillToCheck removeAllObjects];
                  [weakSelf.tableView reloadData];
              } else {
                  kShowRsMsg(response);
              }
          }];
}

#pragma mark - lazy
- (OrderListFilterViewController *)filterVC {
    if (!_filterVC) {
        _filterVC = [OrderListFilterViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
        _filterVC.param = self.param;
        WS(weakSelf);
        [_filterVC setBlockSubmit:^{
            [weakSelf.tableView.mj_header beginRefreshing];
        }];
        [self addChildViewController:_filterVC];
    }
    return _filterVC;
}

- (OrderQueryDefintion *)param {
    if (!_param) {
        _param = [[OrderQueryDefintion alloc] init];
        QueryOrder *order = [[QueryOrder alloc] init];
        order.field = @"payTime";
        order.direction = @"desc";
        _param.orders = (NSArray<QueryOrder> *) @[ order ];
        _param.userId = kUser.fid;
        _param.state = @"paid, invalid";
        _param.beginDate = [[[NSDate date] yearMonthDayString] stringByAppendingString:@" 00:00:00"];
        _param.endDate = [[[NSDate date] yearMonthDayString] stringByAppendingString:@" 23:59:59"];
    }
    return _param;
}
//
//- (NSMutableArray *)arrBillIdToCheck {
//    if (!_arrBillIdToCheck) {
//        _arrBillIdToCheck = [NSMutableArray array];
//    }
//
//    return _arrBillIdToCheck;
//}

- (NSMutableSet *)setBillToCheck {
    if (!_setBillToCheck) {
        _setBillToCheck = [NSMutableSet set];
    }
    return _setBillToCheck;
}

- (UIView *)shadow {
    if (!_shadow) {
        _shadow = [[UIView alloc] initWithFrame:self.view.bounds];
        _shadow.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
        [self.view addSubview:_shadow];
        _shadow.hidden = YES;
        _shadow.tag = 11112222;
    }
    return _shadow;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
