//
//  SearchViewController.m
//  Palmwms
//
//  Created by 曹云霄 on 16/8/25.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "SearchViewController.h"


#define PAGENUMBER 12
#define QUERYUSER @"queryuser"

@interface SearchViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

/**
 *  输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *userInputTextField;

/**
 *  tableview
 */
@property (weak, nonatomic) IBOutlet UITableView *userTableView;

/**
 *  查询对象
 */
@property (nonatomic,strong) CustomerQueryDefintion *queryModel;

/**
 *  返回对象
 */
@property (nonatomic,strong) CustomerQueryResult *result;

/**
 *  数据源
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 *  记录上一次选择的cell下标
 */
@property (nonatomic,strong) NSIndexPath *selectIndexPath;


@end

@implementation SearchViewController

#pragma mark - lazy
- (CustomerQueryDefintion *)queryModel
{
    if (!_queryModel) {
        _queryModel = [[CustomerQueryDefintion alloc]init];
        //排序
        QueryOrder *order = [[QueryOrder alloc]init];
        order.field = @"id";
        order.direction = QUERYORDERDIRECTION_ASC;
        _queryModel.orders = (NSArray<QueryOrder> *)@[order];
        _queryModel.pageSize = PAGENUMBER;
        _queryModel.pageNumber = PAGENUMBER - PAGENUMBER;
    }
    return _queryModel;
}

- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self setupRefreshing];
}

#pragma mark - UI
- (void)uiConfigAction
{
    [self customBackButton:@selector(backButtonClick)];
    [self.userInputTextField addCorners];
    [self.userInputTextField addLines];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
    imageView.image = LOADIMAGENAME(@"search");
    [leftView addSubview:imageView];
    self.userInputTextField.leftViewMode = UITextFieldViewModeAlways;
    self.userInputTextField.leftView = leftView;
    self.userTableView.tableFooterView = [UIView new];
    [self.userTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:QUERYUSER];
    //确认选择
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"确认" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonClickAction:)];
    rightButton.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightButton;
    self.navigationItem.rightBarButtonItem.enabled = false;
}

#pragma mark - 设置刷新
- (void)setupRefreshing
{
    WS(weakSelf);
    self.userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.userTableView.mj_footer resetNoMoreData];
        [weakSelf queryUserisRemoveAll:YES];
    }];
    [self.userTableView.mj_header beginRefreshing];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
 
        if (weakSelf.result.paging.page >= weakSelf.result.paging.pageCount - 1) {
            [weakSelf.userTableView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf queryUserisRemoveAll:NO];
        }
    }];
    self.userTableView.mj_footer = footer;
    footer.automaticallyHidden = YES;
}

#pragma mark - 查询客户
- (void)queryUserisRemoveAll:(BOOL)boolValue
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding:@"查询中"];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(QUERY) WithRequestType:0 WithParameter:self.queryModel WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf endRefreshingForTableView:weakSelf.userTableView];
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (boolValue) {
                [self.datasArray removeAllObjects];
            }
            CustomerQueryResult *result = [[CustomerQueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            for (Customer *dict in result.records) {
                [self.datasArray addObject:dict];
            }
            [self.userTableView reloadData];
        }else
        {
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf SHOWPrompttext:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:error.localizedDescription];
    }];
}


#pragma mark - <UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:QUERYUSER forIndexPath:indexPath];
    Customer *dict = self.datasArray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"【%@】%@",dict.code,dict.name];
    cell.tintColor = [UIColor redColor];
    cell.accessoryType = (self.selectIndexPath == indexPath)?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
    return cell;
}

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectIndexPath) {
        UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:self.selectIndexPath];
        selectCell.accessoryType = UITableViewCellAccessoryNone;
        self.navigationItem.rightBarButtonItem.enabled = false;
        if (self.selectIndexPath == indexPath) {
            self.selectIndexPath = nil;return;
        }
    }
    //更新记录，选中点击的cell
    self.selectIndexPath = indexPath;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.navigationItem.rightBarButtonItem.enabled = true;
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

#pragma mark - 确认选择
- (void)rightButtonClickAction:(UIBarButtonItem *)item
{
    if (self.selectCustomer) {
        self.selectCustomer(self.datasArray[self.selectIndexPath.row]);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 返回
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.queryModel.codeEqualsOrNameLike = [textField.text length]?textField.text:nil;
    [self.userTableView.mj_header beginRefreshing];
    return YES;
}




@end
