//
//  SelectOrderViewController.m
//  total
//
//  Created by 曹云霄 on 16/6/27.
//  Copyright © 2016年 Delevin. All rights reserved.
//

#import "SelectOrderViewController.h"
#import "SelectOrderTableViewCell.h"

#define JIANCHANGDAN @"查看建仓申请"

@interface SelectOrderViewController ()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

/**
 * 上传模型
 */
@property (nonatomic,strong) QueryDefinition2 *queryOrder;

/**
 * 当前页数
 */
@property (nonatomic,assign) NSInteger indexPage;

/**
 * 返回对象
 */
@property (nonatomic,strong) QueryResult *orderResult;

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

/**
 * 记录cell的选中状态
 */
@property (nonatomic,strong) NSMutableArray *recordSelectState;

@end

@implementation SelectOrderViewController

- (QueryDefinition2 *)queryOrder
{
    if (!_queryOrder) {
        
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        _queryOrder = [[QueryDefinition2 alloc]init];
        _queryOrder.pageSize = 10;
        _queryOrder.pageNumber = self.indexPage;
        QueryOrder *queryOrder = [[QueryOrder alloc]init];
        queryOrder.field = @"lastModifiedTime";
        queryOrder.direction = @"desc";
        _queryOrder.orders = (NSArray<QueryOrder> *)@[queryOrder];
        //组织条件
        QueryCondition *userCondition = [[QueryCondition alloc]init];
        if ([self.title isEqualToString:JIANCHANGDAN]) {
            userCondition.parameters = @[user.orguuid];
            userCondition.operation = @"orguuidequals";
        }else {
            
            NSMutableArray *storeuuidArray = [NSMutableArray array];
            for (NSDictionary *dict in user.storeArray) {//登陆用户的油站列表
                [storeuuidArray addObject:dict[@"uuid"]];
            }
            userCondition.parameters = storeuuidArray;
            userCondition.operation = @"storeUuidIn";
        }
        //配油单状态
        QueryCondition *orderState = [[QueryCondition alloc]init];
        orderState.parameters = @[@"submit"];
        orderState.operation = @"stateIn";
        //职位
        QueryCondition *position = [[QueryCondition alloc]init];
        position.parameters = [self.title isEqualToString:JIANCHANGDAN]?nil:@[user.f_user_uuid];
        position.operation = [self.title isEqualToString:JIANCHANGDAN]?nil:([user.position isKindOfClass:[NSNull class]]?nil:@"isStorer");
        if (![user.position isKindOfClass:[NSNull class]] || [self.title isEqualToString:JIANCHANGDAN]) {//user.position有值时忽略组织条件
            _queryOrder.conditions = (NSArray<QueryCondition> *)@[position,userCondition,orderState];
        }else {
            _queryOrder.conditions = (NSArray<QueryCondition> *)@[position,orderState];
        }
        _queryOrder.orders = (NSArray<QueryOrder> *)@[queryOrder];
    }
    return _queryOrder;
}

- (NSMutableArray *)recordSelectState
{
    if (!_recordSelectState) {
        _recordSelectState = [NSMutableArray array];
    }
    return _recordSelectState;
}


- (NSMutableArray *)orderResultArray
{
    if (!_orderResultArray) {
        _orderResultArray = [NSMutableArray array];
    }
    return _orderResultArray;
}


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


#pragma mark 获取配油单列表数据
- (void)getOilOrderDatas:(BOOL)isRemoveall
{
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    NSLog(@"%@",[self.queryOrder toDictionary]);
    __weak typeof(self) weakSelf = self;
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/pickingBill/query?fetchParts=%@",HTTP_REST_API_BASE_URL,[ICRUserUtil sharedInstance].f_user_uuid] withRequestType:ZERO withParameter:[weakSelf.queryOrder toDictionary] withSuccess:^(id returnValue) {
        [GTOCommonTools cancelMJRefreshState:weakSelf.selectOrderTableView];
        weakSelf.selectOrderTableView.emptyDataSetSource = weakSelf;
        weakSelf.selectOrderTableView.emptyDataSetDelegate = weakSelf;
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.orderResult = [[QueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            isRemoveall?[weakSelf.orderResultArray removeAllObjects]:nil;
            isRemoveall?[weakSelf.recordSelectState removeAllObjects]:nil;
            [weakSelf.orderResultArray addObjectsFromArray:weakSelf.orderResult.records];
            for (id objc in weakSelf.orderResult.records) {
                [weakSelf.recordSelectState addObject:@"0"];//默认状态0《未选中》
            }
            [weakSelf.selectOrderTableView reloadData];
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [GTOCommonTools cancelMJRefreshState:self.selectOrderTableView];
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


#pragma mark -UI
- (void)uiConfigAction
{
    self.title = @"选择配油单";
    self.navigationItem.leftBarButtonItem = nil;
    self.selectOrderTableView.delegate = self;
    self.selectOrderTableView.dataSource = self;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureButtonClickAction:)];
}


#pragma mark -添加MJRefresh刷新
- (void)setupMJRefresh
{
    self.selectOrderTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self.selectOrderTableView.mj_footer resetNoMoreData];
        self.indexPage = ZERO;
        [self getOilOrderDatas:YES];
    }];
    [self.selectOrderTableView.mj_header beginRefreshing];
    self.selectOrderTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if ( ++self.indexPage >= self.orderResult.paging.pageCount) {
            [self.selectOrderTableView.mj_footer endRefreshingWithNoMoreData];return;
        }
        [self getOilOrderDatas:NO];
    }];
    self.selectOrderTableView.mj_footer.automaticallyHidden = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectOrderTableViewCell" forIndexPath:indexPath];
    cell.selectBoxButton.tag = indexPath.row;
    cell.selectBoxButton.selected = [self.recordSelectState[indexPath.row] boolValue];
    [cell.selectBoxButton addTarget:self action:@selector(selectBoxButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.dictModel = self.orderResultArray[indexPath.row];
    return cell;
}

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

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

#pragma mark -确定
- (void)sureButtonClickAction:(UIBarButtonItem *)button
{
    if (self.completeSelectBlock) {
        if ([self.recordSelectState containsObject:@"1"]) {
            NSDictionary *dict = self.orderResultArray[[self.recordSelectState indexOfObject:@"1"]];
            WS(weakSelf);
            [self judgeOrderIsEmploy:dict[@"billnumber"] resultBlock:^(BOOL boolValue) {
                if (boolValue) {
                   weakSelf.completeSelectBlock(dict);
                }else{
                   [weakSelf dismissViewControllerAnimated:YES completion:nil];
                }
            }];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

#pragma mark -改变选中状态
- (void)selectBoxButtonClickAction:(UIButton *)button
{
    if ([self.recordSelectState containsObject:@"1"]) {
        for (int i=0; i<self.recordSelectState.count; i++) {
            self.recordSelectState[i] = @"0";
        }
        NSArray *cells = [self.selectOrderTableView visibleCells];
        for (SelectOrderTableViewCell *cell in cells) {
            cell.selectBoxButton.selected = NO;
        }
    }
    BOOL boolValue = [self.recordSelectState[button.tag] boolValue];
    boolValue?(self.recordSelectState[button.tag] = @"0"):(self.recordSelectState[button.tag] = @"1");
    button.selected = !boolValue;
}


#pragma mark -判断配油单是否被使用
- (void)judgeOrderIsEmploy:(NSString *)pickingBillNumber resultBlock:(void(^)(BOOL boolValue))block
{
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/receiveBill/getByPickingBillNumberAndState/%@",HTTP_REST_API_BASE_URL,pickingBillNumber] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {

        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            block(YES);
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [GTOCommonTools cancelMJRefreshState:self.selectOrderTableView];
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return KNODATAIMAGE;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:15.0f], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}








@end
