//
//  ManagementViewController.m
//  ALand
//
//  Created by Z on 16/3/29.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "ManagementViewController.h"
#import "CommodityTableViewCell.h"
#import "UITableView+Category.h"
#import "CommodityMutipleSelectBottomView.h"
#import "NSDate+FormatterAdditions.h"
#import "MBProgressHUD+Javen.h"

#define kPageSize @999

#define kCellId @"CommodityTableViewCell.h"
@interface ManagementViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CommodityMutipleSelectBottomView *bottomView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *field; //排序的字段
@property (nonatomic, copy) NSString *direction;  //排序的顺序 升序或降序
@property (nonatomic, strong) NSMutableArray *deleteArr;
@property (nonatomic, strong) NSMutableDictionary *dicSelectIds;
@end

@implementation ManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.field = @"";
    self.direction = @"desc";
     self.condition = @"";
    self.navigationItem.title = @"批量管理";

    
    [self setUpViews];
    // Do any additional setup after loading the view.
}


- (void)setUpViews
{
    [self.view addSubview:self.sorView];
    [self.sorView defaultSelectISLeft:self.isLeft row:self.row];
    WS(weakSelf)
    self.sorView.leftTableSelect = ^(NSInteger row){
        [weakSelf leftSelectCodtition:row];
        CLog(@"l");
    };
    
    self.sorView.rightTableSelect = ^(NSInteger row){
        [weakSelf rightSelectCondition:row];
        CLog(@"r");
    };
    _tableView = [UITableView plainTableViewWithTarget:self cellNibName:@"CommodityTableViewCell" cellId:kCellId];
    [self.view addSubview:_tableView];
    _tableView.sd_layout.topSpaceToView(self.sorView,0).leftEqualToView(self.view).rightEqualToView(self.view).bottomSpaceToView(self.view, 70);
    _tableView.editing = YES;
    _tableView.allowsMultipleSelectionDuringEditing = YES;
    
    
    
    _bottomView = [CommodityMutipleSelectBottomView viewWithNibName:@"CommodityMutipleSelectBottomView"];
    _bottomView.frame = CGRectMake(0, kHeight - 64 - 70, kWidth, 70 + 64);
    [_bottomView addTarget:self delete:@selector(multipleACtion:) online:@selector(multipleACtion:) offline:@selector(multipleACtion:)];
    [self.view addSubview:_bottomView];
    
    
    [_bottomView.buttonSelectAll addTarget:self action:@selector(selectAll:) forControlEvents:UIControlEventTouchUpInside];
}

- (NSMutableDictionary *)dicSelectIds {
    if (!_dicSelectIds) {
        _dicSelectIds = [NSMutableDictionary dictionary];
    }
    return _dicSelectIds;
}

- (void)leftSelectCodtition:(NSInteger)row {
 
    switch (row) {
        case 0:
        {
            self.condition = @"shop online only";
        }
            break;
        case 1:
        {
            self.condition = @"shop offline only";
        }
            break;
            
        default:
            break;
    }
    
    [self resetReloadData];
    
}

- (void)rightSelectCondition:(NSInteger)row {

    
    switch (row) {
        case 0:
        {
            self.field = @"shop goods create time";
            self.direction = @"desc";
        }
            break;
        case 1:
        {
            self.field = @"salesvolume";
            self.direction = @"desc";
        }
            break;
        case 2:
        {
            self.field = @"brokerageRate";
            self.direction = @"desc";
        }
            break;
        case 3:
        {
            self.field = @" spec price";
            self.direction = @"desc";
            
        }
            break;
            
        default:
            break;
    }
    
    [self resetReloadData];
}


//改变排序条件之后重新请求数据
- (void)resetReloadData {
    [self.sorView defaultSelectISLeft:YES row:0];
    [self.arrCellData removeAllObjects];
    [self setUpData];
    
}



- (void)setUpData {
    
    NSDictionary *params = @{@"defintion" : @{@"probePages" : @0,
                                              @"orders" : @[@{@"field" : self.field,
                                                              @"direction" : self.direction}],
                                              @"conditions" : @[@{@"parameters" : @[[UserInfo shareInstance].domain],
                                                                  @"operation" : @"domain equals",
                                                                  @"parameter" : @{@"operation" : @"string"}},
                                                                @{@"parameters" : @[@[[UserInfo shareInstance].shop.uuid]],
                                                                  @"operation" : @"shop uuid equals",
                                                                  @"parameter" : @{@"operation" : @"sring"}},
                                                                @{@"parameters" : @[@""],
                                                                  @"operation" : self.condition,
                                                                  @"parameter" : @{@"operation" : @"sring"}}],
                                              @"pageSize" : kPageSize,
                                              @"page" : @0},
                             @"fetchParts" : @[@"string"]};
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"goods/query2" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        for (NSDictionary *dic in responseObject[@"queryResult"]) {
            CommotityListModel *model = [CommotityListModel modelObjectWithDictionary:dic];
            [weakSelf.arrCellData addObject:model];
        }
        
        [weakSelf.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

#pragma mark =========== action ===========

- (void)selectAll:(UIButton *)btn {//tag 等于1表示全选
    if (btn.tag == 0) {
        [self.bottomView selectAll];
        for (int i = 0; i < self.arrCellData.count; i ++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
            CommotityListModel *model = self.arrCellData[indexPath.row];
            [self.dicSelectIds setValue:@"" forKey: model.uuid];
            
        }
        
        btn.tag = 1;
    }else{
        [self.bottomView deselectAll];
        for (int i = 0; i < self.arrCellData.count; i ++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
            
            CommotityListModel *model = self.arrCellData[indexPath.row];
            [self.dicSelectIds removeObjectForKey:model.uuid];

        }
        
        btn.tag = 0;
    }
}



#pragma mark =========== tableview delegate ===========

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommodityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    [cell cellWithModel:self.arrCellData[indexPath.row]];
    return cell;
}

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


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CommotityListModel *model = self.arrCellData[indexPath.row];
    [self.dicSelectIds setValue:@"" forKey: model.uuid];
    CLog(@"%@",self.dicSelectIds.allKeys);
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    CommotityListModel *model = self.arrCellData[indexPath.row];
    [self.dicSelectIds removeObjectForKey:model.uuid];
    CLog(@"%@",self.dicSelectIds.allKeys);

}

#pragma mark =========== 删除、上架、下架 ===========
- (void)multipleACtion:(UIButton *)btn
{
    NSString *questUrl;
    switch (btn.tag) {
        case  ActionTypeDelete:
        {
            questUrl = @"shop/removeGoods";
            CLog(@"delete");
        }
            break;
        case ActionTypeOnline:
        {
            questUrl = @"shop/onlineGoods";
            CLog(@"online");
        }
            break;
        case ActionTypeOffline:
        {
            questUrl = @"shop/offlineGoods";
            CLog(@"offline");
        }
            break;
            
        default:
            break;
    }
    
    NSArray *arrGoodsUuid = self.dicSelectIds.allKeys;
    NSDictionary *params = @{@"operCtx" : @{@"time" : [[NSDate date] timeStampNumber],
                                                  @"domain" : [UserInfo shareInstance].domain,
                                                  @"operator" : @{@"id" : [UserInfo shareInstance].uuid,
                                                                  @"fullName" : [UserInfo shareInstance].name}},
                                   @"shopUuid" : [UserInfo shareInstance].shop.uuid,
                                   @"listGoodsUuid" : arrGoodsUuid};
    
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:questUrl parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:weakSelf.view];
        [self.view addSubview:hud];
        
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            imageView.tintColor = kSysWhite;
            hud.customView = imageView;
            hud.mode = MBProgressHUDModeCustomView;
            hud.labelText = @"操作成功！";
            
            [weakSelf.dicSelectIds removeAllObjects];
            [weakSelf resetReloadData];
        }else{
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"未知错误！";
        }
        [hud show:YES];
        [hud hide:YES afterDelay:0.7];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


#pragma mark =========== lazyloading ===========

- (CommodityManagementSortView *)sorView {
    if (!_sorView) {
        _sorView = [[CommodityManagementSortView new] sortView];
        _sorView.frame = CGRectMake(0, 0, kWidth, 49);
    }
    return _sorView;
}

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