//
//  GTORepairViewController.m
//  total
//
//  Created by freecui on 15/10/29.
//  Copyright © 2015年 free. All rights reserved.
//

#import "GTORepairListViewController.h"
#import "GTORepairListCellContentView.h"
#import "GTORepair.h"
#import "SortMaskView.h"
#import "MJRefresh.h"
#import "GTORepairBoltView.h"
#import "QueryOrderNew.h"
#import "GTORepairDetailViewController.h"


#define TopMargin 44
#define TableHeight 140
#define LeftMargin 20
#define BtnWidth 60
#define BtnHeight 24
#define BtnSize 16

typedef enum : NSUInteger {
    SortTag = 3000,
    BoltTag
    
} BtnTag;
static NSString *cellID = @"repairListCell";
@interface GTORepairListViewController ()<UITableViewDataSource,UITableViewDelegate,SortMaskViewDelegate,GTORepairBoltViewDelegate>
{
    UIView *_maskView;
    UIButton *currentBtn;
    SortMaskView *_sortView;
   GTORepairBoltView  *_boltView;
    UIBarButtonItem  *_sureBtn;
    UIButton *_sortBtn;
    UIButton *_boltBtn;
    BOOL _isRefresh;
    BOOL _isLoadMore;
    NSInteger _currentPage;
}

@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSString *titleLike;
@property (nonatomic,strong)NSString *state;
@property (nonatomic,strong)NSString *billLike;
@property (nonatomic,strong)NSString *orderDirection;//asc(升序)，desc(降序)
@property (strong, nonatomic) NSString *areaLike;
@property (strong, nonatomic) NSString *stationNameLike;
@end

@implementation GTORepairListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"报修单列表";
    self.view.backgroundColor  = XXFBgColor;
    [self initData];
    [self createBackBtn];
    [self createTableView];
    [self createRefresh];
    [self getData];
    
}

- (void)initData{
    self.dataArr = [NSMutableArray array];
}
- (void)getData{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchtPuchaseList:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    
    NSMutableArray *orderArr =[NSMutableArray array];
    if (self.orderDirection.length > 0 && ![self.orderDirection isEqualToString:@"none"]) {
        QueryOrderNew *order = [QueryOrderNew new];
        order.field = @"lastModifyInfo";
        order.direction = self.orderDirection;
        [orderArr addObject:[order dictForCommit]];
    }
    if (orderArr.count == 0) {
        QueryOrderNew *order = [QueryOrderNew new];
        order.field = @"billnumber";
        order.direction = @"desc";
        [orderArr addObject:[order dictForCommit]];
        
    }
    
    id billObject = [NSNull null];
    if (self.billLike.length > 0) {
        billObject = self.billLike;
        if (self.orderDirection.length > 0 && ![self.orderDirection isEqualToString:@"none"]) {
            QueryOrderNew *order = [QueryOrderNew new];
            order.field = @"billNumber";
            order.direction = self.orderDirection;
            [orderArr addObject:[order dictForCommit]];
        }
    }
    id stateObject = [NSNull null];
    if (self.state.length > 0 && ![self.state isEqualToString:@"none"]) {
        stateObject = self.state;
        if (self.orderDirection.length > 0 && ![self.orderDirection isEqualToString:@"none"]) {
            QueryOrderNew *order = [QueryOrderNew new];
            order.field = @"state";
            order.direction = self.orderDirection;
            [orderArr addObject:[order dictForCommit]];
        }
    }
    id titleObject = [NSNull null];
    if (self.titleLike.length > 0) {
        titleObject = self.titleLike;
    }
    
    id areaObject = [NSNull null];
    if (self.areaLike.length > 0) {
        areaObject = self.areaLike;
    }
    
    id stationObject = [NSNull null];
    if (self.stationNameLike.length > 0) {
        stationObject = self.stationNameLike;
    }
    NSDictionary *dict = @{
                           @"engineerUuid": [ICRUserUtil sharedInstance].f_user_uuid,
                           @"billNumberLike":billObject,
                           @"state":stateObject,
                           @"titleLike":titleObject,
                           @"storeAreaNameLike":areaObject,
                           @"storeNameLike":stationObject,
                           @"queryOrders":orderArr,
                           @"pageNumber":@(_currentPage),
                           @"pageSize":@(20)};
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getRepairListWithData:dict success:succ failure:fail];
    
}
- (void)fetchtPuchaseList:(id)data{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            if (_currentPage == 0) {
                if (self.dataArr.count > 0) {
                    [self.dataArr removeAllObjects];
                }
            }
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            for (NSDictionary *dictRepair in recodesArr) {
                GTORepair *repair = [GTORepair DBObject];
                [repair praseFromJsonDict:dictRepair];
 
                [self.dataArr addObject:repair];
            }
            NSDictionary *pageDict = data[ @"data" ][ @"paging" ];
            NSInteger pageCount = [pageDict[@"pageCount"] integerValue];
            [self.tableView reloadData];
            [self endRefreshing];
            if (pageCount <= _currentPage) {
                [self.tableView.footer noticeNoMoreData];
            }
            if (_currentPage == 0 && self.dataArr.count > 0) {
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }else{
            [IBTLoadingView showTips:message];
        }
    }else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
    
    
}
- (void)createRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_isRefresh) {
            return ;
        }
        _isRefresh = YES;
        _currentPage = 0;
        [self getData];
    }];
    self.tableView.header.lastUpdatedTimeKey = GTO_REPAIR_UPDATEDATE;
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_isLoadMore) {
            return ;
        }
        _isLoadMore = YES;
        _currentPage ++;
        [self getData];
    } ];
}
#pragma mark - 结束刷新
- (void)endRefreshing{
    _isLoadMore = NO;
    _isRefresh = NO;
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
}
- (void)createTableView
{
    _sureBtn = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureClick)];
    self.navigationItem.rightBarButtonItem = _sureBtn;
    
    _sortBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(LeftMargin, 10, BtnWidth, BtnHeight) target:self sel:@selector(sortClick:) tag:SortTag image:@"black_arrow_down_with_text" title:nil titleColor:GXF_DETAIL_COLOR isCorner:NO corner:0 bgColor:nil];
    _sortBtn.titleLabel.font = FontSize(BtnSize);
    [self.view addSubview:_sortBtn];
    
    _boltBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(ScreenSize.width-BtnWidth - LeftMargin,10,BtnWidth, BtnHeight) target:self sel:@selector(sortClick:) tag:BoltTag image:@"black_filter_with_text" title:nil titleColor:GXF_DETAIL_COLOR isCorner:NO corner:0 bgColor:nil];
    _boltBtn.titleLabel.font = FontSize(BtnSize);
    [self.view addSubview:_boltBtn];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, TopMargin,ScreenSize.width, ScreenSize.height - 64 - TopMargin)) style:(UITableViewStylePlain)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    _maskView = [[UIView alloc]initWithFrame:CGRectMake(0, TopMargin, ScreenSize.width, ScreenSize.height - 64- TopMargin)];
    _maskView.backgroundColor = RGBA(0, 0, 0, 0.5);
    _maskView.hidden = YES;
    [self.view addSubview:_maskView];
}
#pragma mark -按钮事件
- (void)sortClick:(UIButton *)btn{
    _maskView.backgroundColor = RGBA(0, 0, 0, 0.5);
    _maskView.hidden = NO;
    if (btn.tag == SortTag) {
        if(_boltView){
            [self hiddenBoltMaskView:NO];
        }
        if (currentBtn == btn) {
            [btn setImage:[UIImage imageNamed:@"black_arrow_down_with_text"] forState:UIControlStateNormal];
            [self hiddenSortMaskView:YES];
            currentBtn = nil;
        }else{
            [btn setImage:[UIImage imageNamed:@"select_arrow_up_text"] forState:UIControlStateNormal];
            if (_sortView == nil) {
                _sortView = [[SortMaskView alloc]initWithFrame:CGRectMake(0, -105, ScreenSize.width, 150) withOrderDirection:self.orderDirection];
                _sortView.dataArr = [[NSMutableArray alloc]initWithObjects:@"默认排序",@"按时间逆序",@"按时间顺序",nil];
                _sortView.delegate = self;
                [_maskView addSubview:_sortView];
                [UIView animateWithDuration:0.25 animations:^{
                    CGRect sortFrame = _sortView.frame;
                    sortFrame.origin.y = 0;
                    _sortView.frame = sortFrame;
                }];
            }
            currentBtn = btn;
        }
    }else if(btn.tag == BoltTag){
        if (_sortView) {
            [self hiddenSortMaskView:NO];
        }
        if (currentBtn == btn) {
            [btn setImage:[UIImage imageNamed:@"black_filter_with_text"] forState:UIControlStateNormal];
            [self hiddenBoltMaskView:YES];
            currentBtn = nil;
            
        }else{
            [btn setImage:[UIImage imageNamed:@"selected-filter_with_text"] forState:UIControlStateNormal];
            if (_boltView == nil) {
                CGRect rect = CGRectMake(0, -105, ScreenSize.width, 274) ;
                _boltView = [[GTORepairBoltView alloc]initRepairBoltViewWithFrame:rect state:self.state title:self.titleLike bill:self.billLike area:self.areaLike station:self.stationNameLike];

                
                _boltView.backgroundColor = XXFBgColor;
                _boltView.delegate = self;
                //initial(未提交)submitted(已提交)rejected(已拒绝)approved(已审批)shipping(发运中)finished(已完成)
                _boltView.dataArr = [[NSMutableArray alloc]initWithObjects:@"全部",@"未提交",@"待处理",@"处理中" ,@"已申请",@"已结束",nil];
                [_maskView addSubview:_boltView];
                [UIView animateWithDuration:0.25 animations:^{
                    CGRect sortFrame = _boltView.frame;
                    sortFrame.origin.y = 0;
                    _boltView.frame = sortFrame;
                }];
                currentBtn = btn;
            }
        }
    }
}

- (void)hiddenSortMaskView:(BOOL)isHide{
    currentBtn = nil;
    [self checkSortBtnColor];
    if (isHide == NO) {
        [_sortView removeFromSuperview];
        _sortView = nil;
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            CGRect sortFrame = _sortView.frame;
            sortFrame.origin.y = -105;
            _sortView.frame = sortFrame;
            _maskView.backgroundColor = RGBA(0, 0, 0, 0);
        }completion:^(BOOL finished) {
            [_sortView removeFromSuperview];
            _sortView = nil;
            _maskView.hidden = YES;
        }];
    }
}
- (void)hiddenBoltMaskView:(BOOL)isHide{
    currentBtn = nil;
    [self checkBoltBtnColor];
    if (isHide == NO) {
        [_boltView removeFromSuperview];
        _boltView = nil;
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            CGRect sortFrame = _boltView.frame;
            sortFrame.origin.y = -105;
            _boltView.frame = sortFrame;
            _maskView.backgroundColor = RGBA(0, 0, 0, 0);
        }completion:^(BOOL finished) {
            [_boltView removeFromSuperview];
            _boltView = nil;
            _maskView.hidden = YES;
        }];
    }
}

//检测排序的颜色
- (void)checkSortBtnColor{
    if (self.orderDirection.length > 0) {
        [_sortBtn setImage:[UIImage imageNamed:@"select_arrow_up_text"] forState:UIControlStateNormal];
    }else{
        [_sortBtn setImage:[UIImage imageNamed:@"black_arrow_down_with_text"] forState:UIControlStateNormal];
        
    }
}
- (void)checkBoltBtnColor{
    if (self.state.length > 0 || self.titleLike.length > 0 || self.billLike.length > 0 )//|| self.vendorLike.length > 0) {
    {
        [_boltBtn setImage:[UIImage imageNamed:@"selected-filter_with_text"] forState:UIControlStateNormal];
    }else{
        [_boltBtn setImage:[UIImage imageNamed:@"black_filter_with_text"] forState:UIControlStateNormal];
        
    }
}
#pragma mark - 确定
- (void)sureClick{
    
    [_boltView.titleFiled resignFirstResponder];
    [_boltView.billFiled resignFirstResponder];
   // [_boltView.vendorFiled resignFirstResponder];
    
    _currentPage = 0;
    
    //请求
    [self getData];
    
    //还原数据
    if (_sortView) {
        [self hiddenSortMaskView:YES];
    }
    if (_boltView) {
        [self hiddenBoltMaskView:YES];
    }
}

#pragma mark - sortDelegate
- (void)getSortValueSelectRow:(NSString *)state{
    if (state.length > 0) {
        self.orderDirection = state;
        CLog(@"%@",state);
    }
}
#pragma mark - boltDelegate
- (void)getBoltValueSelectRow:(NSString *)state{
    self.state = state;
    CLog(@"%@",state);
}
- (void)getTitleLike:(NSString *)titleLike {
    self.titleLike = titleLike;
    CLog(@"%@",titleLike);

}
- (void)getBillNumber:(NSString *)billNumber {
    self.billLike = billNumber;
    CLog(@"%@",billNumber);
}

- (void)getAreaLike:(NSString *)area {
    self.areaLike = area;
}

- (void)getStationNameLime:(NSString *)stationName {
    self.stationNameLike = stationName;
}

//- (void)getvendorLike:(NSString *)vendorLike{
//    self.vendorLike = vendorLike;
//    CLog(@"%@",vendorLike);
//}
- (void)clearBoltInformation{
    //清空所有条件
    if (self.billLike.length > 0) {
        self.billLike = @"";
    }
    if (self.titleLike.length > 0) {
        self.titleLike = @"";
    }
    if (self.state.length > 0) {
        self.state = @"";
    }
    self.areaLike = nil;
    self.stationNameLike = nil;
//    if (self.vendorLike.length > 0) {
//        self.vendorLike = @"";
//    }
}

#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    [self configureCell:cell forRowAtIndexPath:indexPath];
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *contentView = cell.contentView;
    
    GTORepairListCellContentView *view = [contentView viewWithClass:[GTORepairListCellContentView class]];
    
    if (!view) {
        view = [[GTORepairListCellContentView alloc] initWithFrame:contentView.bounds];
        [view autoresizingWithStrechFullSize];
        [contentView addSubview:view];
    }
    GTORepair *repair = _dataArr[indexPath.section];
    [view updateWithRepair:repair];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GTORepair *repair = _dataArr[indexPath.section];
    
    GTORepairDetailViewController *repairDeVC = [[GTORepairDetailViewController alloc]initWithRepairUuid:repair.uuid];
    
    [self PushViewController:repairDeVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return TableHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
     return section == 0 ? 1 : 10;
}
- (void)createBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    btn.frame  = CGRectMake(0, 0, 12, 20);
    [btn addTarget:self action:@selector(backRV) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
}
- (void)backRV{
    [self PopToRootViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
////    if ([ICRUserUtil sharedInstance].needFresh && self.tableView != nil) {
////        [self.tableView.header beginRefreshing];
////    }
//    if (self.tableView != nil) {
//        [self.tableView.header beginRefreshing];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
