//
//  SurveyViewController.m
//  XFFurit
//
//  Created by 陈俊俊 on 15/8/1.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "SurveyViewController.h"
#import "SurveyListCell.h"
#import "Survey.h"
#import "SortMaskView.h"
#import "BoltMaskView.h"
#import "SurveyDetailViewController.h"
#import "NewSurveyViewController.h"

#define TopMargin 44
#define TableHeight 120
#define LeftMargin 20
#define BtnWidth 60
#define BtnHeight 24
#define BtnSize 16
typedef enum : NSUInteger {
    SortTag = 3000,
    BoltTag
  
} BtnTag;

@interface SurveyViewController ()<UITableViewDataSource,UITableViewDelegate,BoltMaskViewDelegate,SortMaskViewDelegate>
{
    UIView *_maskView;
    UIButton *currentBtn;
    SortMaskView *_sortView;
    BoltMaskView *_boltView;
    UIBarButtonItem  *_sureBtn;
    UIButton *_sortBtn;
    UIButton *_boltBtn;
}
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSString *billNumberLike;
@property (nonatomic,strong)NSString *state;//未提交=initial已提交=submitted调研中=insurvey已完成=finished
@property (nonatomic,strong)NSString *titleLike;
@property (nonatomic,strong)NSString *orderField;
@property (nonatomic,strong)NSString *orderDirection;//asc(升序)，desc(降序)


@end

@implementation SurveyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"行情调研";
    self.view.backgroundColor  = XXFBgColor;
    [self initData];
    [self createTableView];
    [self getData];
}
- (void)initData{
    self.dataArr = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([ICRUserUtil sharedInstance].needFresh) {
        [self getData];
    }
}

- (void)getData{
    [ICRUserUtil sharedInstance].needFresh = NO;
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchtSurveyList:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    
    id billObject = [NSNull null];
    if (self.billNumberLike.length > 0) {
        billObject = self.billNumberLike;
    }
    id stateObject = [NSNull null];
    if (self.state.length > 0 && ![self.state isEqualToString:@"none"]) {
        stateObject = self.state;
    }
    id titleObject = [NSNull null];
    if (self.titleLike.length > 0) {
        titleObject = self.titleLike;
    }
    id orderObject = [NSNull null];
    if (self.orderDirection.length > 0) {
        orderObject = self.orderDirection;
    }
    
    NSDictionary *dict = @{
                           @"billNumberLike":billObject,
                           @"state":stateObject,
                           @"titleLike":titleObject,
                           @"orderField":[NSNull null],
                           @"orderDirection":orderObject,
//                           @"userUuid":userUtil.userId,
                           @"pageNumber":@(0),
                           @"pageSize":@(20)};
    [[ICRHTTPController sharedController] querySurveyWithBillData:dict success:succ failure:fail];
}
#pragma mark -成功
- (void)fetchtSurveyList:(id)data{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            if (self.dataArr.count > 0) {
                [self.dataArr removeAllObjects];
            }
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            for (NSDictionary *surveyDict in recodesArr) {
                Survey *survey = [[Survey alloc]init];
                [survey setValuesForKeysWithDictionary:surveyDict];
                [self.dataArr addObject:survey];
            }
            [self.tableView reloadData];
        }else{
            [IBTLoadingView showTips:message];
        }
    }else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
}

- (void)createTableView
{
    _sureBtn = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureClick)];
    _sortBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(LeftMargin, 10, BtnWidth, BtnHeight) target:self sel:@selector(sortClick:) tag:SortTag image:@"black_arrow_down_with_text" title:nil titleColor:HexColor(@"888888") 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:HexColor(@"888888") 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.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)sureClick{
    [_boltView.titleFiled resignFirstResponder];
    [_boltView.billFiled resignFirstResponder];
    
    
    //请求
    [self getData];
    //还原数据
    if (_sortView) {
        [self hiddenSortMaskView:YES];
    }
    if (_boltView) {
        [self hiddenBoltMaskView:YES];
    }
    //清空所有条件
    if (self.orderDirection.length > 0) {
        self.orderDirection = @"";
    }
    if (self.billNumberLike.length > 0) {
        self.billNumberLike = @"";
    }
    if (self.titleLike.length > 0) {
        self.titleLike = @"";
    }
    if (self.state.length > 0) {
        self.state = @"";
    }
    self.navigationItem.rightBarButtonItem = nil;
}

#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;
            self.navigationItem.rightBarButtonItem = nil;
        }else{
            [btn setImage:[UIImage imageNamed:@"select_arrow_up_text"] forState:UIControlStateNormal];
            if (_sortView == nil) {
                _sortView = [[SortMaskView alloc]initWithFrame:CGRectMake(0, -105, ScreenSize.width, 105) 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;
                }];
            }
            self.navigationItem.rightBarButtonItem = _sureBtn;
            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;
            self.navigationItem.rightBarButtonItem = nil;

        }else{
            [btn setImage:[UIImage imageNamed:@"selected-filter_with_text"] forState:UIControlStateNormal];
            if (_boltView == nil) {
                _boltView = [[BoltMaskView alloc]initWithFrame:CGRectMake(0, -105, ScreenSize.width, 224) state:self.state title:self.titleLike bill:self.billNumberLike];
                _boltView.backgroundColor = HexColor(@"f8f8f8");
                _boltView.delegate = self;
                _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;
                self.navigationItem.rightBarButtonItem = _sureBtn;

            }
        }
    }
}

- (void)hiddenSortMaskView:(BOOL)isHide{
    currentBtn = nil;
    [_sortBtn setImage:[UIImage imageNamed:@"black_arrow_down_with_text"] forState:UIControlStateNormal];
    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;
    [_boltBtn setImage:[UIImage imageNamed:@"black_filter_with_text"] forState:UIControlStateNormal];
    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;
        }];
    }
}
#pragma mark - sortDelegate
- (void)getSortValueSelectRow:(NSString *)state{
    self.orderDirection = state;
    NSLog(@"%@",state);
}
- (void)getBoltValueSelectRow:(NSString *)state{
    self.state = state;
    NSLog(@"%@",state);
}
- (void)getTitleLike:(NSString *)titleLike{
    self.titleLike = titleLike;
    NSLog(@"%@",titleLike);
}
- (void)getBillNumber:(NSString *)billNumber{
    self.billNumberLike = billNumber;
    NSLog(@"%@",billNumber);
}

#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"SurveyID";
    SurveyListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[SurveyListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (self.dataArr.count > 0) {
        Survey *survey = self.dataArr[indexPath.row];
        [cell setSurvey:survey];

    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Survey *survey = nil;
    if (self.dataArr.count > 0) {
       survey  = self.dataArr[indexPath.row];
    }
    if ([survey.state isEqualToString:@"initial"]) {
        NewSurveyViewController *nvc = [[NewSurveyViewController alloc]init];
        nvc.survey = survey;
        nvc.navTitle = @"修改行情调研单";
        [self PushViewController:nvc animated:YES];
        
    }else if([survey.state isEqualToString:@"submitted"] || [survey.state isEqualToString:@"insurvey"]|| [survey.state isEqualToString:@"finished"]){
        SurveyDetailViewController *svc = [SurveyDetailViewController new];
        svc.survey = survey;
        svc.surveyUuid = survey.uuid;
        [self PushViewController:svc animated:YES];
    }


}



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


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#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
