//
//  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, strong) NSMutableArray *deleteArr;
@property (nonatomic, strong) NSMutableDictionary *dicSelectIds;
@end

@implementation ManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.direction = @"desc";
    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 {
    [self.bottomView deselectAll];
    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 {

    [self.bottomView deselectAll];
    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 = @"commission";
            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 {

    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"goods/query2" parameters:[self getParams] 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) {
        
    }];
}

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



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

- (void)selectAll:(UIButton *)btn {
    
    if (self.dicSelectIds.allKeys.count == self.arrCellData.count) { //全选
        [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];
            
        }
        
    }else{
        [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];
        }
        
    }
}



#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];
    
    [self checkIsAllSelect];
    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);
    [self checkIsAllSelect];

}

#pragma mark =========== 删除、上架、下架 ===========
- (void)multipleACtion:(UIButton *)btn
{
    NSArray *arrGoodsUuid = self.dicSelectIds.allKeys;
    
    if (arrGoodsUuid.count == 0) {
        [MBProgressHUD Javen_showError:@"请至少选择一件商品" onView:self.view delay:0.6 complete:nil];
        return;
    }
    
    
    NSString *questUrl;
    switch (btn.tag) {
        case  ActionTypeDelete:
        {
            questUrl = @"shop/removeGoods";
            CLog(@"delete");
        }
            break;
        case ActionTypeOnline:
        {
            if ([self.condition isEqualToString: @"shop online only"] ) {
                [MBProgressHUD Javen_showError:@"不能重复上架！" onView:self.view delay:0.5 complete:nil];
                return;
            }
            questUrl = @"shop/onlineGoods";
            CLog(@"online");
        }
            break;
        case ActionTypeOffline:
        {
            if (![self.condition isEqualToString: @"shop online only"] ) {
                [MBProgressHUD Javen_showError:@"不能重复下架！" onView:self.view delay:0.5 complete:nil];
                return;
            }
            questUrl = @"shop/offlineGoods";
            CLog(@"offline");
        }
            break;
            
        default:
            break;
    }
    
    NSDictionary *params = @{@"operCtx" : @{@"time" : [[NSDate date] timeStampNumber],
                                            @"domain" : kDomain,
                                            @"operator" : @{@"id" : [UserInfo shareInstance].reseller.uuid,
                                                            @"fullName" : [UserInfo shareInstance].reseller.name}},
                             @"shopUuid" : [UserInfo shareInstance].reseller.shop.uuid,
                             @"listGoodsUuid" : arrGoodsUuid};
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:questUrl parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        [weakSelf unparseData:responseObject];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
}

//解析数据
- (void)unparseData:(NSDictionary *)responseObject {
    
    if ([responseObject[@"code"] isEqualToNumber:@0]) {
        
        [MBProgressHUD Javen_showSuccess:@"操作成功！" onView:self.view delay:0.7 complete:nil];
        [self.dicSelectIds removeAllObjects];
        [self resetReloadData];
    }else{
        [MBProgressHUD Javen_showError:@"未知错误！" onView:self.view delay:0.7 complete:nil];
    }
    
    [self.bottomView deselectAll];
    
}

//检查是否全部选中了
- (void)checkIsAllSelect {
    CLog(@"%lu %lu", (unsigned long)self.dicSelectIds.allKeys.count, (unsigned long)self.arrCellData.count);
    if (self.dicSelectIds.allKeys.count == self.arrCellData.count) {
        [self.bottomView selectAll];
    }else{
        [self.bottomView deselectAll];
    }
}



- (void)popAction {
    [super popAction];
    [self.sorView hide];
}


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

- (JavenSortView *)sorView {
    if (!_sorView) {
        _sorView = [JavenSortView sortViewLeftTitles:@[@"销售中",@"未上架"] rightTitles:@[@"最新排序",@"销量排序",@"佣金排序",@"售价排序"]];
        _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
