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

#import "GTOAlertInfoPioneeringViewController.h"
#import "GTOPioneering.h"
#import "GXFBottomView.h"
#import "GTOCategoryItemView.h"
#import "GTOPioneeingProcess.h"
#import "GTOQuestion.h"
#import "GTOAnswer.h"
static NSString * cellID = @"cellId";
#define CELL_HEIGHT 65
@interface GTOAlertInfoPioneeringViewController ()
<UITableViewDataSource,UITableViewDelegate,GXFBottomViewDelegate,
UITextFieldDelegate>
@property (nonatomic, strong) GTOPioneering *d_pioneering;

//@property (nonatomic, copy) NSArray *d_arrProcesses;
@property (nonatomic, strong) UIView *c_alertInfo;
@property (nonatomic, strong) UITableView *c_tableView;
@end

@implementation GTOAlertInfoPioneeringViewController

- (instancetype)initWithPioneering: (GTOPioneering *)pioneering {
    self = [super init];
    if(!self) return nil;
    self.d_pioneering = pioneering;
    return self;
}
- (instancetype)initWithPioneering: (GTOPioneering *)pioneering
                questionCategories: (NSArray *)categorys
                   categoryProcess: (NSArray *)processes{
    self = [super init];
    if(!self) return nil;
    self.d_pioneering = pioneering;
//    self.d_arrCategorys = categorys;
//    self.d_arrProcesses = processes;
    
    
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  //  [self initData];
  //  [self initSubViews];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initData];
}
- (void)initSubViews {
    CGFloat padding = 0;//整个alertInfo距离阴影部分
    CGFloat topVH = 50;
//    CGFloat alertInfoH = topVH + (17 + GTO_TOP_VERTICAL_PADDING ) * 3 + 1 + _d_arrCategorys.count * CELL_HEIGHT + 90;
    CGFloat alertInfoH = topVH + (17 + GTO_TOP_VERTICAL_PADDING ) * 3 + 1 + _d_pioneering.arrDisplayResults.count * CELL_HEIGHT + 90;
     BOOL overScreen = (ScreenSize.height - alertInfoH) > 0 ? NO : YES; //是否超出屏幕
    self.view.backgroundColor = [UIColor clearColor];
    CGRect rect;
    if (!overScreen) {
        rect = CGRectMake(0,0 , self.view.width, ScreenSize.height - alertInfoH);
    } else {  //超出屏幕时
        rect = CGRectMake(0,0 , self.view.width, 0 );
    }
    UIView *bgView = [[UIView alloc]initWithFrame:rect];
                              bgView.backgroundColor = [UIColor blackColor];
                               bgView.alpha = 0.5;
                              [self.view addSubview:bgView];

    CGFloat alertInfoY ;
    if (overScreen) {
        alertInfoY =  ScreenSize.height ;
    } else {
        alertInfoY =  alertInfoH;
    }
    self.c_alertInfo = [[UIView alloc]initWithFrame:CGRectMake(padding,bgView.height, self.view.width - 2* padding,alertInfoY)];
    self.c_alertInfo.backgroundColor = [UIColor whiteColor];
    UIView *topV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _c_alertInfo.width, topVH)];
    topV.backgroundColor = XXFBgColor;
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 0, _c_alertInfo.width - 80, topV.height)];
    titleLabel.text = _d_pioneering.title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:17];
    UIButton *closeBtn = [[UIButton alloc]initWithFrame:CGRectMake(_c_alertInfo.width - 40,0, 40, topV.height)];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeCliced:) forControlEvents:UIControlEventTouchUpInside];
    [_c_alertInfo addSubview:topV];
    [topV addSubview:titleLabel];
    [topV addSubview:closeBtn];
    
    
    CGFloat leftpadding = GTO_LEFT_PADDING;
    CGFloat lblH = 17;
    UIView *planInfoView = [[UIView alloc]initWithFrame:CGRectMake(-1, topV.bottom, _c_alertInfo.width + 2, (lblH + GTO_TOP_VERTICAL_PADDING ) * 3 + 8)];
    planInfoView.layer.borderColor = [GTO_GRAY_SHALLOW_TINT_COLOR CGColor];
    planInfoView.layer.borderWidth = 0.5;
    
    UIFont *font = [UIFont systemFontOfSize:17];
    IBTUILabel *patrolNameLabel =[ [IBTUILabel alloc]initWithFrame:CGRectMake(leftpadding, GTO_TOP_VERTICAL_PADDING , planInfoView.width, lblH) text:[NSString stringWithFormat:@"%@",_d_pioneering.templateName] font:font tintColor:nil backgroundColor:nil textAlignment:NSTextAlignmentLeft];

    UILabel *timeLabel = [ [IBTUILabel alloc]initWithFrame:CGRectMake(patrolNameLabel.x, patrolNameLabel.bottom + GTO_TOP_VERTICAL_PADDING , patrolNameLabel.width, lblH) text:[NSString stringWithFormat:@"开始时间：%@",_d_pioneering.beginDate] font:font tintColor:nil backgroundColor:nil textAlignment:NSTextAlignmentLeft];

    UILabel *inspectorLabel = [ [IBTUILabel alloc]initWithFrame:CGRectMake(patrolNameLabel.x, timeLabel.bottom + GTO_TOP_VERTICAL_PADDING , planInfoView.width - 60, lblH) text:[NSString stringWithFormat:@"拓站人员: %@",_d_pioneering.pioneer_name] font:font tintColor:nil backgroundColor:nil textAlignment:NSTextAlignmentLeft];

    [_c_alertInfo addSubview:planInfoView];
    [planInfoView addSubview:patrolNameLabel];
    [planInfoView addSubview:timeLabel];
    [planInfoView addSubview:inspectorLabel];
    
//    UITableView *categoryTableV = [[UITableView alloc]initWithFrame:CGRectMake(0, planInfoView.bottom + 10, _c_alertInfo.width, _d_arrCategorys.count * CELL_HEIGHT)];
    ///categoryTableV.tag = kCategoryTableVTag;
    UITableView *categoryTableV = [[UITableView alloc]initWithFrame:CGRectMake(0, planInfoView.bottom + 10, _c_alertInfo.width,_c_alertInfo.height - planInfoView.bottom - 70)];
    [categoryTableV registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    categoryTableV.delegate = self;
    categoryTableV.dataSource = self;
    self.c_tableView = categoryTableV;
    [_c_alertInfo addSubview:_c_tableView];
    
    GXFBottomView *nextV = [[GXFBottomView alloc]initWithFrame:CGRectMake(0, _c_alertInfo.height - 70, _c_alertInfo.width, 40) leftButtonColor:GTO_BLUE_DEEP_COLOR rightButtonColor:GTO_RED_COLOR LeftBtnTitle:@"查看结果" rightBtnTitle:@"开始填写"];
    nextV.backgroundColor = XXFBgColor;
    nextV.delegate = self;
   // nextV.tag = kNextbottomVTag;
    [_c_alertInfo addSubview:nextV];
    [self.view addSubview:_c_alertInfo];
    
 

}
- (void)initData {
//    if (!_d_arrCategorys) {
//        NSUInteger uiQuestionsCount = [_d_pioneering.questions count];
//        
//        NSArray *arrQuestIDs = [_d_pioneering.questions valueForKeyPath:@"uuid"];
//        
//        
//        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//            NSString * sql = [NSString stringWithFormat:@"SELECT DISTINCT category  FROM %@ WHERE %@ IN %@  ORDER BY %@ ASC", [GTOQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
//            NSLog(@"%@",sql);//lineno没有，因为现在后台没有给问题排序
//            //            NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ IN %@  ORDER BY %@ ASC", [GTOQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
//            return [db executeQuery:sql withArgumentsInArray:arrQuestIDs];
//        };
//        
//        __weak typeof(self)weakSelf = self;
//        ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
//            __strong __typeof(weakSelf)strongSelf = weakSelf;
//            NSMutableArray *muArr = [NSMutableArray array];
//            for(GTOQuestion * question in fetchedObjects){
//                [muArr addObject:question.category];
//            }
//            strongSelf.d_arrCategorys = [NSArray arrayWithArray:muArr];
//            
//        };
//        
//        ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//        [dbCtrl runFetchForClass:[GTOQuestion class]
//                      fetchBlock:fetchBlk
//               fetchResultsBlock:fetchResultsBlk];
//    }
//    
//    //    if (!_d_arrProcessNumbers) {
//    //        NSMutableArray *muArr = [NSMutableArray array];
//    //
//    //    }
//    if (!_d_arrProcesses) {
//        NSUInteger uiQuestionsCount = [_d_pioneering.questions count];
//        
//        NSArray *arrQuestIDs = [_d_pioneering.questions valueForKeyPath:@"uuid"];
//        
//        
//        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//            NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ IN %@  ORDER BY %@ ASC", [GTOQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
//            NSLog(@"%@",sql);
//            return [db executeQuery:sql withArgumentsInArray:arrQuestIDs];
//        };
//        
//        __weak typeof(self)weakSelf = self;
//        ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
//            __strong __typeof(weakSelf)strongSelf = weakSelf;
//            
//            NSMutableArray *muArr = [NSMutableArray array];
//            for (int count = 0; count < _d_arrCategorys.count; count ++) {
//                NSInteger total = 0;
//                GTOPioneeingProcess *process = [[GTOPioneeingProcess alloc]init];
//                for (GTOQuestion *questE in fetchedObjects) {
//                    if([questE.category isEqualToString:_d_arrCategorys[count]])
//                        total++;
//                }
//                process.totalNumber = total;
//                process.category = _d_arrCategorys[count];
//                [muArr addObject:process];
//            }
//            strongSelf.d_arrProcesses = [NSArray arrayWithArray:muArr];
//
//        };
//        
//        ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//        [dbCtrl runFetchForClass:[GTOQuestion class]
//                      fetchBlock:fetchBlk
//               fetchResultsBlock:fetchResultsBlk];
//    }
//    
    
    //答案的个数
    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_pioneering.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_pioneering.arrDisplayResults.count; count ++) {
           // NSInteger finiseNumber = 0;
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_pioneering.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_pioneering.arrDisplayResults = muArrDisplayRs;
        [_d_pioneering saveToDBWithHandleData:nil complete:^{
            [self initSubViews];
            [_c_tableView reloadData];
        } fail:nil];

    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}



#pragma UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return  _d_pioneering.arrDisplayResults.count;//_d_arrCategorys.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    [self configureCell:cell forRowAtIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIView *contentView = cell.contentView;
    GTOCategoryItemView *categoryItem = [contentView viewWithClass:[GTOCategoryItemView class]];
    if (!categoryItem) {
        categoryItem =  [[GTOCategoryItemView alloc]initWithFrame:contentView.bounds];
        [categoryItem autoresizingWithStrechFullSize];
        [contentView addSubview:categoryItem];
    }
    if (_d_pioneering.arrDisplayResults.count > 0) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[indexPath.row]];
        
       [categoryItem updateWithPioneering:_d_pioneering pioneeringDisplayResults:displayR];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return CELL_HEIGHT;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if([_delegate respondsToSelector:@selector(alertInfoPioneeringViewController:didSelectRowAtIndexPath:)]){
        [_delegate alertInfoPioneeringViewController:self didSelectRowAtIndexPath:indexPath];
    }
    
}

#pragma GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView leftButtonClicked:(UIButton *)leftBtn {

    if ([_delegate respondsToSelector:@selector(alertInfoPioneeringViewController:seeResultClickedWithBtton:)]) {
        [_delegate alertInfoPioneeringViewController:self seeResultClickedWithBtton:leftBtn];
    }
}

- (void)bottomView:(GXFBottomView *)bottomView RightButtonClicked:(UIButton *)rightBtn {
    if ([_delegate respondsToSelector:@selector(alertInfoPioneeringViewController:nextClickedWithBtton:)]) {
        [_delegate alertInfoPioneeringViewController:self nextClickedWithBtton:rightBtn];
    }
}
- (void)closeCliced: (UIButton *)btn {
    if ([_delegate respondsToSelector:@selector(alertInfoPioneeringViewController:closeClickedWithBtton:)]) {
        [_delegate alertInfoPioneeringViewController:self closeClickedWithBtton:btn];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

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