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

#import "GTOLicenceListViewController.h"
#import "GTOLicenceListCellContentView.h"
#import "GTOLicence.h"
#import "SortMaskView.h"
#import "MJRefresh.h"
#import "GTOLicenceBoltView.h"
#import "QueryOrderNew.h"
#import "GTOAlertInfoLicenceViewController.h"
#import "GTOLiceneResultViewController.h"
#import "GTODisplayResult.h"
#import "GTOQuestionManager.h"
#import "GTOPioneeringSurveyItem.h"
#import "ICRPostAttachment.h"
#import "GTOAnswer.h"
#import "GTOQuestion.h"
#define TopMargin 44
#define TableHeight 170
#define LeftMargin 20
#define BtnWidth 60
#define BtnHeight 24
#define BtnSize 16

typedef enum : NSUInteger {
    SortTag = 3000,
    BoltTag
    
} BtnTag;
static NSString *cellID = @"licenceListCell";
@interface GTOLicenceListViewController ()<UITableViewDataSource,UITableViewDelegate,SortMaskViewDelegate,GTOLicenceBoltViewDelegate,GTOAlertInfoLicenceViewControllerDelegate>
{
    UIView *_maskView;
    UIButton *currentBtn;
    SortMaskView *_sortView;
    GTOLicenceBoltView  *_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 *state;
//@property (nonatomic,strong)NSString *repairNumberLike;
@property (nonatomic,strong)NSString *billNumberLike;
@property (nonatomic,strong)NSString *riskGrade;
@property (nonatomic,strong)NSString *orderDirection;//asc(升序)，desc(降序)
@property (nonatomic, strong) GTOAlertInfoLicenceViewController *alertInfoVC;
@property (nonatomic, assign) BOOL d_isClosed; //点击弹框的“关闭”按钮
@property (nonatomic, strong) GTOLicence *d_currentLicence;//当前点击的列表的cell
@end

@implementation GTOLicenceListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"许可证列表";
    self.view.backgroundColor  = XXFBgColor;
    [self initData];
    [self createBackBtn];
    [self createTableView];
    [self createRefresh];
    [self getData];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if (_d_currentLicence && [_d_currentLicence.state isEqualToString:GTO_LICENCE_STATE_INITIAL]) {
//        [self p_addAlerInfoLicenceView];
//    }
}

- (void)initData{
    self.dataArr = [NSMutableArray array];
    //    if (self.assessorVendor.length > 0) {
    //        self.vendorLike = self.assessorVendor;
    //    }
}
- (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 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 stateObject = [NSNull null];
    if (self.state.length > 0 && ![self.state isEqualToString:@"none"]) {
        stateObject = self.state;
    }
    id billNumberObject = [NSNull null];
    if (self.billNumberLike.length > 0) {
        billNumberObject = self.billNumberLike;
    }
//    id repairNumberObject = [NSNull null];
//    if (self.repairNumberLike.length > 0) {
//        repairNumberObject = self.repairNumberLike;
//    }
    id riskGradeObject = [NSNull null];
    if (self.riskGrade.length > 0) {
        riskGradeObject = self.riskGrade;
    }
    

    NSDictionary *dict = @{
                           @"userUuid": [[ICRUserUtil sharedInstance] f_user_uuid],
                           @"billNumberLike":billNumberObject,
                           @"state":stateObject,
                           @"repairUuid":@"",
                           @"repairNumberLike":[NSNull null],//repairNumberObject,
                           @"riskGrade":riskGradeObject,
                           @"queryOrders":orderArr,
                           @"pageNumber":@(_currentPage),
                           @"pageSize":@(20)};
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getLicenceListWithData: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) {
                GTOLicence *licence = [GTOLicence DBObject];
                [licence praseFromJsonDict:dictRepair];
                
                [self.dataArr addObject:licence];
            }
            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];
}
- (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, -274, ScreenSize.width, 274) ;
                _boltView = [[GTOLicenceBoltView alloc]initWithFrame:rect state:self.state  billNumber:self.billNumberLike riskGrade:self.riskGrade];
                
                _boltView.backgroundColor = XXFBgColor;
                _boltView.delegate = self;
                //initial(未提交)submitted(已提交)rejected(已拒绝)approved(已审批)shipping(发运中)finished(已完成)
                _boltView.dataArrState = [[NSMutableArray alloc]initWithObjects:@"全部",@"未提交",@"申请审批",@"待审批",@"审批通过" ,@"审批拒绝",@"已过期",@"已结束",nil];
                    _boltView.dataArrRisk = [[NSMutableArray alloc]initWithObjects:@"全部",GTO_LICENCE_RISK_HIGHT,GTO_LICENCE__RISK_MIDDLE,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 = -274;
            _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.billNumberLike.length > 0 || self.billNumberLike.length > 0 || self.riskGrade.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.repairNumberFiled resignFirstResponder];
    [_boltView.billNumberFiled 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)getBoltRiskValueSelectRow:(NSString *)riskGrade {
    self.riskGrade = riskGrade;
}
- (void)getBillNumber:(NSString *)billNumber {
    self.billNumberLike = billNumber;
}
- (void)getRiskGrade:(NSString *)riskGrade {
    self.riskGrade = riskGrade;
}

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

#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:NO];
    
    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;
    
    GTOLicenceListCellContentView *view = [contentView viewWithClass:[GTOLicenceListCellContentView class]];
    
    if (!view) {
        view = [[GTOLicenceListCellContentView alloc] initWithFrame:contentView.bounds];
        //view.m_bHiddenNumLabel = m_bIsInHome;
        [view autoresizingWithStrechFullSize];
        [contentView addSubview:view];
    }
    GTOLicence *licence = _dataArr[indexPath.section];
    [view updateWithLicence:licence];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //如果是审批拒绝状态，就显示拒绝理由，所以增加一个label的高度
    GTOLicence *licence = _dataArr[indexPath.section];
    return  [licence.state isEqualToString:@"rejected"] ? TableHeight + 20: TableHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 1 : 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GTOLicence *licence = _dataArr[indexPath.section];
    self.d_currentLicence = licence;
    [self p_httpGetLicenceItems];

    
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
     UITableViewCellEditingStyleNone,
     UITableViewCellEditingStyleDelete,
     UITableViewCellEditingStyleInsert
     */
    GTOLicence *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) {

        GTOLicence *licence = _dataArr[indexPath.section];
        [self p_deleteLicenceWithLicence: licence];
        
        [_dataArr removeObjectAtIndex:indexPath.section];
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    }
}
- (void)p_deleteLicenceWithLicence: (GTOLicence *)licence {
    
    
    //后台删除
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if ([data[@"success"] integerValue] == 1) {
            //本地删除 许可证
            ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
            [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
                NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOLicence TableName],@"uuid" ];
                [db executeUpdate:strSql,licence.uuid];
            }];
            
            [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
                NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOQuestion TableName],@"licenceUuid" ];
                [db executeUpdate:strSql,licence.uuid];
            }];
            [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
                NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOAnswer TableName],@"licenceUuid" ];
                [db executeUpdate:strSql,licence.uuid];
            }];

        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC doLicenceRemoveWithLicenceUuid:licence.uuid version:licence.version success:succ failure:fail];
    
}
- (void)p_httpGetLicenceItems {
    __weak typeof(self) weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf p_saveLicenceItemsWithData:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getLicenceItemsWithLicenceUuid:_d_currentLicence.uuid success:succ failure:fail];
}
- (void)p_saveLicenceItemsWithData: (id)data {
    
    NSInteger intSucc = [data[@"success"] integerValue];
    if (intSucc == 1) {
        
    }
    NSArray *arrItems = [data[@"data"] objectForKey:@"items"];
    NSMutableArray *muArrQuestions = [NSMutableArray array];
    NSMutableArray *muArrAnswers = [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.licenceUuid = _d_currentLicence.uuid;
        [question saveToDBWithHandleData:NULL complete:NULL fail:NULL];
//        CLog(@"%@",question.uuid);
        [muArrQuestions addObject:[question dictForCommit]];
        
        
        /*     
         @property (assign, nonatomic) NSUInteger resultScore; //打分结果
         @property (copy, nonatomic) NSString *resultContent;
         @property (copy, nonatomic) NSString *resultRemark;
         @property (copy, nonatomic) NSArray *resultDetails;
         
         @property (copy, nonatomic) NSString *resultAttachmentId;  //结果附件id 没做
         */
        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.licenceUuid = _d_currentLicence.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.licenceUuid = _d_currentLicence.uuid;
                postAttachment.questionUuid = answer.questionUuid;
                postAttachment.entityType = GTO_ENTITYTYPE_PIONEER_ANSWER;
                postAttachment.entityUuid = answer.resultAttachmentId;
                [postAttachment saveToDBWithHandleData:NULL complete:NULL fail:NULL];
            }
            [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
        }

    [muArrCategory addObject:item.category];
        
    }
    _d_currentLicence.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_currentLicence.questions) {
            GTOQuestion *question = [GTOQuestion DBObject];
            [question praseFromJsonDict:dictQ];
            if ([question.category isEqualToString:category]) {
                [muArrQuestions addObject:dictQ];
            }
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        displayR.arrQuestions = muArrQuestions;
        displayR.arrAnswers = muArrAnswers;
        displayR.category = category;
        displayR.isDisplay = NO;
        [muArrDisplayRs addObject:[displayR dictForCommit]];
    }
    
    
    _d_currentLicence.arrDisplayResults = muArrDisplayRs;
    [_d_currentLicence saveToDBWithHandleData:NULL
                                 complete:^{
                                     [self fetchResult];
//                                      if ([_d_currentLicence.state isEqualToString:GTO_LICENCE_STATE_INITIAL]) {
//                                          [self p_addAlerInfoLicenceView];
//                                      } else {
//                                          [self fetchResult];
//                                      }
                                     
                                 }
                                     fail:^(NSError *error) {
                                         
                                         [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                     }];
}
- (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)p_addAlerInfoLicenceView {
    GTOAlertInfoLicenceViewController *alertInfoVC = [[GTOAlertInfoLicenceViewController alloc]initWithLicence:_d_currentLicence ];
    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], @"licenceUuid",@"questionUuid" ];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_currentLicence.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_currentLicence.arrDisplayResults.count; count ++) {
            // NSInteger finiseNumber = 0;
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_currentLicence.arrDisplayResults[count]];
            //displayR.answerNumber = 0;
            NSMutableArray *muArrAnswers = [NSMutableArray array];
            for (GTOAnswer *answer in fetchedObjects) {
                if([answer.category isEqualToString:displayR.category])
                    //displayR.answerNumber++;
                    [muArrAnswers addObject:[answer dictForCommit]];
            }
            displayR.arrAnswers = muArrAnswers;
            
            [muArrDisplayRs addObject:[displayR dictForCommit]];
        }
        _d_currentLicence.arrDisplayResults = muArrDisplayRs;
        [_d_currentLicence saveToDBWithHandleData:nil complete:^{
            GTOLiceneResultViewController *resultVC = [[GTOLiceneResultViewController alloc]initWithLicence:_d_currentLicence];
            //resultVC.
            [self PushViewController:resultVC animated:YES];
        } fail:nil];
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}



#pragma GTOAlertInfoLicenceViewControllerDelegate
- (void)alertInfoLicenceViewController:(GTOAlertInfoLicenceViewController *)alertInfoLicence closeClickedWithBtton:(UIButton *)btn {
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
}
- (void)alertInfoLicenceViewController:(GTOAlertInfoLicenceViewController *)alertInfoLicence seeResultClickedWithBtton:(UIButton *)btn {
    
    GTOLiceneResultViewController *resultVC = [[GTOLiceneResultViewController alloc]initWithLicence:_d_currentLicence];
    
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
    [self PushViewController:resultVC animated:YES];
}
- (void)alertInfoLicenceViewController:(GTOAlertInfoLicenceViewController *)alertInfoLicence nextClickedWithBtton:(UIButton *)btn {
    BOOL isAllFinished = YES;
    for(NSDictionary *dict in _d_currentLicence.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 Licence:_d_currentLicence Pioneering:nil];
            [self alertInfoLicenceViewController:alertInfoLicence closeClickedWithBtton:nil];
              isAllFinished = NO;
            break;
        }
    }
    
    if (isAllFinished) {
        NSDictionary *dictR = [_d_currentLicence.arrDisplayResults lastObject];
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictR];
        GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
        mgr.d_category = displayR.category;
        [mgr openQuestionVCFromViewControler:self Licence:_d_currentLicence Pioneering:nil];
        [self alertInfoLicenceViewController:alertInfoLicence closeClickedWithBtton:nil];
        
    }
    
}
- (void)alertInfoLicenceViewController:(GTOAlertInfoLicenceViewController *)alertInfoLicence didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_currentLicence.arrDisplayResults[indexPath.row]];
    mgr.d_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
    [mgr openQuestionVCFromViewControler:self Licence:_d_currentLicence Pioneering:nil];
    
    [self alertInfoLicenceViewController:alertInfoLicence closeClickedWithBtton:nil];
    
}

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


@end
