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

#import "CommodityManagementViewController.h"
#import "CommodityManagementTopView.h"
#import "UITableView+Category.h"
#import "CommodityTableViewCell.h"
#import "CommotityRequestModel.h"
#import "CommodityListModel/CommotityListModel.h"
#import "ManagementViewController.h"
#import "Conditions.h"
#import "CommodityDetailViewController.h"
#import "JavenSortView.h"
#import "AddCommodityViewController.h"


#define kCellID @"commodityCell"
#define kPageSize @999
#define kCellId @"CommodityTableViewCell.h"
@interface CommodityManagementViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) CommodityManagementTopView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrItemDatas;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *field; //排序的字段
@property (nonatomic, copy) NSString *direction;  //排序的顺序 升序或降序
@property (nonatomic, copy) NSString *searchText;  //正在搜索的字段
@property (nonatomic, copy) NSString *condition;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) UIBarButtonItem *rightItem;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *searchTitleView;

@property (nonatomic, assign) BOOL isLeft;//判断排序判断选中了左边还是右边
@property (nonatomic, assign) NSInteger row;//判断排序判断选中了哪一行




@end

@implementation CommodityManagementViewController

//跳转添加商品在CommodityManagementTopView里面跳转，注意看一下
- (void)viewDidLoad {
    [super viewDidLoad];
    self.condition = @"shop online only";
    self.searchText = @"";
    self.field = @"";
    self.direction = @"desc";
    [self setUpNavigationbar];
    [self setUpViews];
    [self setUpSearchBar];
    
    kButtonAddAction(self.topView.buttonAddCommodity, addCommodityAction)
    kButtonAddAction(self.topView.buttonManageCommodity, manageManentAction)

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self resetReloadData];
}

- (void)setUpSearchBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth - 100, 35)];//allocate titleView
    UIColor *color = self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.backgroundColor = kRandomColor;
    self.searchBar.delegate = self;
    self.searchBar.frame = CGRectMake(0, 0, 0, 35);
    self.searchBar.centerX = titleView.centerX;
    self.searchBar.backgroundImage = [UIImage imageWithColor:color];
    [titleView addSubview:self.searchBar];
    
    self.searchTitleView = titleView;
}

- (void)cancelSearchAction {
    self.searchText = @"";
    self.condition = @"shop online only";
    self.searchBar.width = 0;
    self.searchBar.centerX = (kWidth - 100) / 2;
    self.navigationItem.titleView = self.titleView;
    self.navigationItem.rightBarButtonItem = self.rightItem;
}


- (void)setUpNavigationbar {
    self.navigationItem.title = @"商品管理";
    self.titleView = self.navigationItem.titleView;
    self.rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"searchIcon"] style:UIBarButtonItemStyleDone target:self action:@selector(searchAct)];
    self.rightItem.tintColor = kTextColorDarkGray;
    self.navigationItem.rightBarButtonItem = self.rightItem;
}


- (void)setUpViews {
    [self.view addSubview:self.topView];
    [self.view addSubview:self.sorView];
    
    //设置现在默认选中的排序方式
    [self.sorView defaultSelectISLeft:YES row:0];

    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).bottomEqualToView(self.view);
}


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

}

//改变排序条件之后重新请求数据
- (void)resetReloadData {
    [self.arrItemDatas removeAllObjects];
    [self setUpData];
    
}

- (void)rightSelectCondition:(NSInteger)row {
    self.isLeft = NO;
    self.row = 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 = @"commission";
            self.direction = @"desc";
        }
            break;
        case 3:
        {
            self.field = @" spec price";
            self.direction = @"desc";
            
        }
            break;
            
        default:
            break;
    }
    
    [self resetReloadData];
}



- (NSMutableArray *)arrItemDatas {
    if (!_arrItemDatas) {
        _arrItemDatas = [NSMutableArray array];
    }
    return _arrItemDatas;
}

- (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.arrItemDatas addObject:model];
        }
        
        [weakSelf.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


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



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

- (void)searchAct {
    [self.sorView hide];
    CLog(@"search");
    WS(weakSelf)
    self.navigationItem.titleView = self.searchTitleView;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.searchBar.width = kWidth - 100;
        weakSelf.searchBar.centerX = (kWidth - 100) / 2;
    } completion:^(BOOL finished) {
        [weakSelf.searchBar becomeFirstResponder];

    }] ;
    
    UIBarButtonItem *cancelSearch = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelSearchAction)];
    self.navigationItem.rightBarButtonItem = cancelSearch;
}

//添加商品
- (void)addCommodityAction {
    [self.sorView hide];
    AddCommodityViewController *addVC = [[AddCommodityViewController alloc] init];
    addVC.hidesBottomBarWhenPushed = YES;
    addVC.isShowNavigationBar = YES;
    
    [self.navigationController pushViewController:addVC animated:YES];
    
    CLog(@"a");
}

//商品管理
- (void)manageManentAction {
    ManagementViewController *manageVC = [[ManagementViewController alloc] init];
    [self.sorView hide];
    manageVC.isShowNavigationBar = YES;
    manageVC.arrCellData = [self.arrItemDatas mutableCopy];
    manageVC.isLeft = self.isLeft;
    manageVC.row = self.row;
    
    [self.navigationController pushViewController:manageVC animated:YES];
    
    CLog(@"m");
}


- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar endEditing:YES];

    [super viewWillDisappear:animated];
    [self.sorView hide];
}



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

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

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommodityDetailViewController *detailVC = [[CommodityDetailViewController alloc] init];
    detailVC.model = self.arrItemDatas[indexPath.row];

    CommodityTableViewCell *cell = (CommodityTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    detailVC.image = cell.imgView.image;
    [self.navigationController pushViewController:detailVC animated:YES];
}



#pragma mark =========== searchBar Delegate ===========

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    CLog(@"点击搜索");
    self.condition = @"goodsData name like";
    [self.navigationController.navigationBar endEditing:YES];
    
    [self resetReloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.searchText = searchText;
}

#pragma mark =========== lazy loading ===========
- (JavenSortView *)sorView {
    if (!_sorView) {
        _sorView = [JavenSortView sortViewLeftTitles:@[@"销售中",@"未上架"] rightTitles:@[@"最新排序",@"销量排序",@"佣金排序",@"售价排序"]];
        _sorView.frame = CGRectMake(0, _topView.bottom - 50, kWidth, 49);
        
    }
    return _sorView;
}

- (CommodityManagementTopView *)topView {
    if (!_topView) {
        _topView = [CommodityManagementTopView viewWithNibName:@"CommodityManagementTopView"];
        _topView.frame = CGRectMake(0, 0, kWidth, 64 + 64);
//        _topView.arrDatas = self.arrItemDatas;
       
    }
    return _topView;
}


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