//
//  GTOPioneeringListViewController.m
//  total
//
//  Created by freecui on 15/10/13.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOPioneeringListViewController.h"
#import "GTOPatrolTemplate.h"
#import "GTOPioneeringListCellContent.h"
#import "MJRefresh.h"
#import "SortMaskView.h"
#import "GTOPioneeringBoltView.h"
#import "GTONewAddPioneeringViewController.h"
#import "QueryOrderNew.h"
#import "GTOPioneering.h"
#import "GTOEditPioneeringViewController.h"

#import "GTOPioneeringSurveyItem.h"
#import "GTOAnswer.h"
#import "GTOQResultViewController.h"
#import "GTOAlertInfoPioneeringViewController.h"
#import "GTOQuestionManager.h"
#import "GXFBottomView.h"
#import "ICRPostAttachment.h"
#define TopMargin 44
#define TableHeight 120
#define LeftMargin 20
#define BtnWidth 60
#define BtnHeight 24
#define BtnSize 16

#define HexColor(colorStr)      [UIColor colorWithHexString:colorStr]
#define GXF_DETAIL_COLOR       [UIColor colorWithHexString:@"888888"]// HexColor(@"888888")

#define PATROL_PLAN_CELL_HEIGHT     120
typedef enum : NSUInteger {
    SortTag = 3000,
    BoltTag
    
} BtnTag;
static NSString *cellID = @"pioneeringListCell";
@interface GTOPioneeringListViewController ()
<UITableViewDataSource,UITableViewDelegate,IBTScrollViewRefreshDelegate,SortMaskViewDelegate,GTOPioneeringBoltViewDelegate,GTOAlertInfoPioneeringViewControllerDelegate,GXFBottomViewDelegate>
{
    UIView *_maskView;
    UIButton *currentBtn;
    SortMaskView *_sortView;
    GTOPioneeringBoltView  *_boltView;
   
    UIButton *_sortBtn;
    UIButton *_boltBtn;
    BOOL _isRefresh;
    BOOL _isLoadMore;
    NSInteger _currentPage;
}
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSString *state;
@property (nonatomic,strong)NSString *titleLike;
@property (nonatomic,strong)NSString *nameLike;
@property (nonatomic,strong)NSString *orderDirection;//asc(升序)，desc(降序)
@property (nonatomic, strong) GTOPioneering *d_currentPioneering;
@property (nonatomic, assign) BOOL d_isClosed; //点击弹框的“关闭”按钮
@property (nonatomic, strong) GTOAlertInfoPioneeringViewController *alertInfoVC;

@end

@implementation GTOPioneeringListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"拓站列表";
    self.view.backgroundColor  = XXFBgColor;
    
    [self initData];
    [self createBackBtn];
    [self createTableView];
//    [self createRefresh];
//    [self getData];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self createRefresh];
    [self getData];
//    if (_d_currentPioneering && [_d_currentPioneering.state isEqualToString:GTO_PIONEERING_STATE_INITIAL]) {
//        [self p_addAlerInfoPioneeringView];
//    }
}
- (void)initData{
    self.dataArr = [NSMutableArray array];
}

- (void)createTableView
{
     BOOL createPermission = [GTOCommonTools hasPermissionWithPermissionId:500503];
    if (createPermission) {
        UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPioneeringClicked)];
        self.navigationItem.rightBarButtonItem = rightBarBtn;
    }

    _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.tableFooterView = [UIView new];
    [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 - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_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
{
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    
    UIView *contentView = cell.contentView;
    
    GTOPioneeringListCellContent *view = [contentView viewWithClass:[GTOPioneeringListCellContent class]];
    
    if (!view) {
        view = [[GTOPioneeringListCellContent alloc] initWithFrame:contentView.bounds];
        //view.m_bHiddenNumLabel = m_bIsInHome;
        [view autoresizingWithStrechFullSize];
        [contentView addSubview:view];
    }
    GTOPioneering *pioneering = _dataArr[indexPath.section];
    [view updateWithPioneering:pioneering];
    
}
#pragma mark - UITableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return PATROL_PLAN_CELL_HEIGHT;//m_bIsInHome ? PATROL_PLAN_CELL_HEIGHT : 109;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 1 : 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.d_currentPioneering = _dataArr[indexPath.section];
    [self p_httpGetPioneeringItems];
//    GTOEditPioneeringViewController *editPionVC = [[GTOEditPioneeringViewController alloc]initWithPioneering:_dataArr[indexPath.section]];
//
//    [self PushViewController:editPionVC animated:NO];
    
    
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
     UITableViewCellEditingStyleNone,
     UITableViewCellEditingStyleDelete,
     UITableViewCellEditingStyleInsert
     */
    GTOPioneering *licence = _dataArr[indexPath.section];
    if ([licence.state isEqualToString:GTO_LICENCE_STATE_INITIAL]) {
        return UITableViewCellEditingStyleDelete;
    }
    
    // return UITableViewCellEditingStyleDelete;
    return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        GTOPioneering *pioneering = _dataArr[indexPath.section];
        [self p_deletePioneeringWithPioneering:pioneering ];
        
        [_dataArr removeObjectAtIndex:indexPath.section];
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    }
}
- (void)p_httpGetPioneeringItems {
    __weak typeof(self) weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf p_savePioneeringItemsWithData:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    
    [httpC getPioneeringItemsWithPioneeringUuid:_d_currentPioneering.uuid success:succ failure:fail];
}
- (void)p_savePioneeringItemsWithData: (id)data {
    [IBTLoadingView hideHUDWithText:nil];
    NSInteger intSucc = [data[@"success"] integerValue];
    if (intSucc == 1) {
        
    }
    NSArray *arrItems = [data[@"data"] objectForKey:@"items"];
    NSMutableArray *muArrQuestions = [NSMutableArray array];
    NSMutableArray *muArrCategory = [NSMutableArray array];
    for(NSDictionary *dictItem in arrItems) {
        
        GTOPioneeringSurveyItem *item = [GTOPioneeringSurveyItem DBObject];
        [item praseFromJsonDict:dictItem];
        GTOQuestion *question = [GTOQuestion DBObject];
        [question praseFromJsonDict:dictItem];
        question.pioneeringUuid = _d_currentPioneering.uuid;
        [question saveToDBWithHandleData:NULL complete:NULL fail:NULL];
        CLog(@"%@",question.uuid);
        [muArrQuestions addObject:[question dictForCommit]];
        
        GTOAnswer *answer = [GTOAnswer DBObject];
        [answer praseFromJsonDict:dictItem];
        
        NSUInteger count = 0;//记录是否被回答：根据答案有无
        if(answer.resultScore) count++;
        if(answer.resultContent) count++;
        if(answer.resultRemark) count++;
        if(answer.resultDetails.count) count++;
        if (count > 0 ) {
            answer.resultAttachmentUrls = item.resultAttachmentUrls;
            answer.resultAttachmentId = item.resultAttachmentId;
            answer.bIsAnswered = YES;
            answer.questionUuid = item.uuid;
            answer.pioneeringUuid = _d_currentPioneering.uuid;
            if(answer.resultAttachmentUrls.count > 0) answer.bIsDownLoadImgs = YES;
            for(NSDictionary *dict in answer.resultAttachmentUrls){
                ICRPostAttachment *postAttachment = [ICRPostAttachment DBObject];
                [postAttachment praseFromJsonDict:dict];
                postAttachment.is_localPhoto = NO;
                postAttachment.is_delete = NO;
                postAttachment.addTime = [[NSDate date] httpParameterString];
                postAttachment.pioneeringUuid = _d_currentPioneering.uuid;
                postAttachment.questionUuid = answer.questionUuid;
                postAttachment.entityType = GTO_ENTITYTYPE_PIONEER_ANSWER;
                postAttachment.entityUuid = answer.resultAttachmentId;
                [postAttachment saveToDBWithHandleData:NULL complete:NULL fail:NULL];
            }
//            ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
//            [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
//                NSString *strSql = [NSString stringWithFormat:@"UPDATE IF FROM %@ WHERE %@=?",[GTOLicence TableName],@"uuid" ];
//                [db executeUpdate:strSql,licence.uuid];
//            }];
            [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
        }
        
        [muArrCategory addObject:item.category];
        
    }
    _d_currentPioneering.questions = muArrQuestions;
    //GTODisplayResult
    NSSet *setCategory = [NSSet setWithArray:muArrCategory];
    NSMutableArray *muArrDisplayRs = [NSMutableArray array];
    for(NSString *category in setCategory) {
        NSMutableArray *muArrQuestions = [NSMutableArray array];
        for(NSDictionary *dictQ in _d_currentPioneering.questions) {
            GTOQuestion *question = [GTOQuestion DBObject];
            [question praseFromJsonDict:dictQ];
            if ([question.category isEqualToString:category]) {
                [muArrQuestions addObject:dictQ];
            }
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        displayR.arrQuestions = muArrQuestions;
        displayR.category = category;
        displayR.isDisplay = NO;
        [muArrDisplayRs addObject:[displayR dictForCommit]];
    }
    
    
    _d_currentPioneering.arrDisplayResults = muArrDisplayRs;
    [_d_currentPioneering saveToDBWithHandleData:NULL
                                 complete:^{
                                     [self fetchResult];
//                                     if ([_d_currentPioneering.state isEqualToString:GTO_PIONEERING_STATE_INITIAL]) {
////                                         [self p_addAlerInfoPioneeringView];

//                                     } else {
//                                         [self fetchResult];
//                                     }
//
                                 }
                                     fail:^(NSError *error) {
                                         
                                         [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                     }];

}

//本地删除
- (void)localDelete {

//    //本地删除
//    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
//    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
//        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOPioneering TableName],@"uuid" ];
//        [db executeUpdate:strSql,_d_pioneering.uuid];
//    }];
//    
//    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
//        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOAnswer TableName],@"pioneeringUuid" ];
//        [db executeUpdate:strSql,_d_pioneering.uuid];
//    }];
}
- (void)p_deletePioneeringWithPioneering:(GTOPioneering *)pioneering {
    [IBTLoadingView showProgressLabel:@"正在保存"];
    // [IBTLoadingView hideHUDWithText:nil];
    void (^success)(id data) = ^(id data) {
//        CLog(@"%@", data);
        
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void (^failure)(id ) = ^(id data) {
//        CLog(@"%@", data);
        [IBTLoadingView showTextOnly:@"删除失败" inView:self.view];
        
        
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doPioneeringRemoveWithPioneeringUuid:pioneering.uuid version:pioneering.version success:success failure:failure];
    
    //本地删除
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELET * FROM %@ WHERE %@=?",[GTOPioneering TableName],@"uuid" ];
        [db executeUpdate:strSql,pioneering.uuid];
    }];
}

- (void)getData{
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    // [ICRUserUtil sharedInstance].needFresh = NO;
    __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];
    };
    
    //排序条件
    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 = @"lastModifyInfo";
        order.direction = @"desc";
        [orderArr addObject:[order dictForCommit]];
    }
    
    //筛选条件
    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 nameObject = [NSNull null];
    if (self.nameLike.length > 0) {
        nameObject = self.nameLike;
    }
    NSDictionary *dict = @{@"nameLike":nameObject,//这里应该是pioneer_uuid;//拓站人uuid
                           @"state":stateObject,
                           @"titleLike":titleObject,
                           @"beginDateFrom":[NSNull null],//开始时间起始于 ??@"2014-10-07 00:00:00",//
                           @"beginDateTo":[NSNull null],// @"2015-10-04 16:27:18",//开始时间结束于 ???
                           @"queryOrders": orderArr,
                           @"pageNumber":@(_currentPage),
                           @"pageSize":@(10)};
    [[ICRHTTPController sharedController] getPioneeringListWithData: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 *dictPioneering in recodesArr) {
                GTOPioneering *pioneering = [GTOPioneering DBObject];
                [pioneering praseFromJsonDict:dictPioneering];
                pioneering.isHttpData = YES;
                [pioneering saveToDBWithHandleData:NULL complete:NULL fail:NULL];
                CLog(@"lastmodify = %@",pioneering.lastModify_time);
                 [self.dataArr addObject:pioneering];
            }
            //[self.dataArr addObjectsFromArray:]
            NSDictionary *pageDict = data[ @"data" ][ @"paging" ];
            NSInteger pageCount = [pageDict[@"pageCount"] integerValue];
            [self.tableView reloadData];
            [self endRefreshing];
            if (pageCount <= _currentPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            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.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_isRefresh) {
            return ;
        }
        _isRefresh = YES;
        _currentPage = 0;
        [self getData];
    }];
    self.tableView.mj_header.lastUpdatedTimeKey = GTO_REPAIR_UPDATEDATE;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_isLoadMore) {
            return ;
        }
        _isLoadMore = YES;
        _currentPage ++;
        [self getData];
    } ];
}
#pragma mark - 结束刷新
- (void)endRefreshing{
    _isLoadMore = NO;
    _isRefresh = NO;
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#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 = [[GTOPioneeringBoltView alloc]initWithFrame:rect state:self.state titleLike:self.titleLike];
                _boltView.backgroundColor = XXFBgColor;
                _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;
            }
        }
    }
}
- (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) {
        
        [_boltBtn setImage:[UIImage imageNamed:@"selected-filter_with_text"] forState:UIControlStateNormal];
    }else{
        [_boltBtn setImage:[UIImage imageNamed:@"black_filter_with_text"] forState:UIControlStateNormal];
        
    }
}

#pragma rightItem
- (void)addPioneeringClicked {
    GTONewAddPioneeringViewController *pionerringVC = [[GTONewAddPioneeringViewController alloc]init];
    //[self PresentModalViewController:pi animated:<#(BOOL)#>]

    [self PushViewController:pionerringVC animated:NO];
}
#pragma mark - 确定  筛选跟排序条件确定
- (void)sureClick{
    
    [_boltView.titleFiled 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);
    }
    [self sureClick];

}
#pragma mark - boltDelegate
- (void)getBoltValueSelectRow:(NSString *)state{
    self.state = state;
}
- (void)getTitleLike:(NSString *)titleLike {
    self.titleLike = titleLike;
}

- (void)getNameLike:(NSString *)nameLike
{
    self.nameLike = nameLike;
}

- (void)clearBoltInformation{
    //清空所有条件
    if (self.titleLike.length > 0) {
        self.titleLike = @"";
    }
    if (self.nameLike.length > 0) {
        self.nameLike = @"";
    }
}



- (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(backClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
    

}
- (void)sureBoltInformation {
    [self sureClick];
}
- (void)backClicked {
    [self PopViewControllerAnimated:YES];
}

- (void)p_addAlerInfoPioneeringView {
    GTOAlertInfoPioneeringViewController *alertInfoVC = [[GTOAlertInfoPioneeringViewController alloc]initWithPioneering:_d_currentPioneering];
    self.alertInfoVC = alertInfoVC;
    alertInfoVC.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_alertInfoVC.view];
}
//找到对应的答案并跳转结果页面
- (void)fetchResult {    //答案的个数
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? ORDER BY %@", [GTOAnswer TableName], @"pioneeringUuid",@"questionUuid" ];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_currentPioneering.uuid];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        NSMutableArray *muArrDisplayRs = [NSMutableArray array];
        for (int count = 0; count < _d_currentPioneering.arrDisplayResults.count; count ++) {
            // NSInteger finiseNumber = 0;
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_currentPioneering.arrDisplayResults[count]];
            //displayR.answerNumber = 0;
            NSMutableArray *muArrAnswers = [NSMutableArray array];
            for (GTOAnswer *answer in fetchedObjects) {
               // [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
                if([answer.category isEqualToString:displayR.category])
                    [muArrAnswers addObject:[answer dictForCommit]];
            }
//            for (int i = 0; i < fetchedObjects.count; i++) {
//                GTOAnswer *answer = fetchedObjects[i];
//                
//            }
            displayR.arrAnswers = muArrAnswers;
            
            [muArrDisplayRs addObject:[displayR dictForCommit]];
        }
        _d_currentPioneering.arrDisplayResults = muArrDisplayRs;
        [_d_currentPioneering saveToDBWithHandleData:nil complete:^{
            GTOQResultViewController *resultVC = [[GTOQResultViewController alloc]initWithPioneering:_d_currentPioneering];
            [self PushViewController:resultVC animated:YES];
        } fail:nil];
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

#pragma GTOAlertInfoPioneeringViewControllerDelegate
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering closeClickedWithBtton:(UIButton *)btn {
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering seeResultClickedWithBtton:(UIButton *)btn {
    GTOQResultViewController *resultVC = [[GTOQResultViewController alloc]initWithPioneering:_d_currentPioneering];
    
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
    [self PushViewController:resultVC animated:YES];
}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering nextClickedWithBtton:(UIButton *)btn {
     BOOL isAllFinished = YES;
    for(NSDictionary *dict in _d_currentPioneering.arrDisplayResults) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dict];
        if (displayR.arrAnswers.count < displayR.arrQuestions.count) {
            GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
            mgr.d_category = displayR.category;
            [mgr openQuestionVCFromViewControler:self withPioneering:_d_currentPioneering];
            [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
               isAllFinished = NO;
            break;
        }
    }
    
    if (isAllFinished) {
        NSDictionary *dictR = [_d_currentPioneering.arrDisplayResults lastObject];
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictR];
        GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
        mgr.d_category = displayR.category;
        [mgr openQuestionVCFromViewControler:self withPioneering:_d_currentPioneering];
        [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
    }

}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_currentPioneering.arrDisplayResults[indexPath.row]];
    mgr.d_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
    [mgr openQuestionVCFromViewControler:self withPioneering:_d_currentPioneering];
    [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
}





@end
