//
//  ChooseShopViewController.m
//  vanke
//
//  Created by Z on 16/4/19.
//  Copyright © 2016年 gomore. All rights reserved.
//

#import "ChooseShopViewController.h"
#import "UIImage+Helper.h"
#import "ICRHTTPController.h"
#import "LoginShopsInstance.h"

#define kCellId @"searchCell"
@interface ChooseShopViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *searchText;
@property (nonatomic, strong) NSMutableArray *arrData;
@property (nonatomic, strong) NSArray *results;
@property (nonatomic, strong) VankeShopModel *shop;

@property (nonatomic, assign) BOOL isChoose;

@end

@implementation ChooseShopViewController

- (void)viewDidLoad {

    [super viewDidLoad];
//    self.arrData = [LoginShopsInstance shareInstance].arrShops;
    
    [self httpRequestGetShops];
    
    self.title = @"选择商铺";
    [self setUPSearchBar];
    [self setUpTableView];
    // Do any additional setup after loading the view.
}


- (void)httpRequestGetShops {

    if ([[VankeCommonModel sharedInstance] curUserIsTenant]) {
        self.results = [[LoginShopsInstance shareInstance].arrShops mutableCopy];
        [self.tableView reloadData];
        return;
    }
    
    
    NSString *url = [NSString stringWithFormat:@"shop/query?projectIdEquals=%@",self.projectId];
    NSString *encodeUrlStr = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    WS(weakSelf);
    [httpCtrl getUrl:encodeUrlStr params:nil success:^(id data) {
        [weakSelf.arrData removeAllObjects];
        for (NSDictionary *dic in data[@"data"]) {
            VankeShopModel *shop = [VankeShopModel modelObjectWithDictionary:dic];
            [weakSelf.arrData addObject:shop];
        }
        
        weakSelf.results = [NSArray arrayWithArray:weakSelf.arrData];
        [weakSelf.tableView reloadData];
    } failure:^(id data) {
        
    }];
}


- (void)setUPSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    self.searchBar.backgroundImage = [UIImage imageWithColor:[UIColor colorWithRed:0.953 green:0.439 blue:0.063 alpha:1.000]];
    self.searchBar.tintColor = [UIColor whiteColor];
    self.searchBar.placeholder = @"请输入商铺名称或代码";
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
}

#pragma mark =========== searbar delegate ===========
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.view endEditing:YES];
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    self.results = [NSArray arrayWithArray:self.arrData];
    [self.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.searchText = searchText;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"name contains [cd] %@ OR code contains [cd] %@", searchText, searchText];
    self.results = [self.arrData filteredArrayUsingPredicate:pred];
    [self.tableView reloadData];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self searchShopName:self.searchText];
    [self.view endEditing:YES];
}

- (void)searchShopName:(NSString *)name {
    NSDictionary *param = @{@"codeOrNameLike":name,
                            @"projectIdEquals":@""};
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl getUrl:@"rest/shop/" params:param success:^(id data){
        
    } failure:^(id data){
        
    }];
    
}

- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchBar.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - self.searchBar.bottom - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellId];
    [self.view addSubview:self.tableView];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    VankeShopModel *shop = self.results[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@【%@】", shop.name, shop.code];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.chooseBlock(self.results[indexPath.row]);
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSMutableArray *)arrData {
    if (!_arrData) {
        _arrData = [NSMutableArray array];
    }
    return _arrData;
}

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