//
//  GTOAlertInfoLicenceViewController.m
//  total
//
//  Created by freecui on 15/11/2.
//  Copyright © 2015年 free. All rights reserved.
//

#import "GTOAlertInfoLicenceViewController.h"
#import "GTOPioneering.h"
#import "GXFBottomView.h"
#import "GTOCategoryItemView.h"
#import "GTOLicence.h"
#import "GTOQuestion.h"
#import "GTOAnswer.h"
//#import "GTORepair.h"
#define CELL_HEIGHT 65
static NSString * cellID = @"cellId";
@interface GTOAlertInfoLicenceViewController ()
<UITableViewDataSource,UITableViewDelegate,GXFBottomViewDelegate,
UITextFieldDelegate>
@property (nonatomic, strong) GTOLicence *d_licence;
//@property (nonatomic, strong) GTORepair *d_repair;
//@property (nonatomic, copy) NSArray *d_arrProcesses;
@property (nonatomic, strong) UIView *c_alertInfo;
@property (nonatomic, strong) UITableView *c_tableView;

@end

@implementation GTOAlertInfoLicenceViewController
//- (instancetype)initWithLicence:(GTOLicence *)licence andRepair: (GTORepair *)repair{
//    self = [super init];
//    if(!self) return nil;
//    self.d_licence = licence;
//    self.d_repair = repair;
//    return self;
//}
- (instancetype)initWithLicence: (GTOLicence *)licence {
    self = [super init];
    if(!self) return nil;
    self.d_licence = licence;

    return self;
}
- (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_licence.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 = [[UIView alloc]initWithFrame:CGRectMake(padding, ScreenSize.height - alertInfoH, self.view.width - 2* padding,alertInfoH )];
    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_licence.licenceType;
    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_licence.repairNumber] 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_licence.store_name] 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_licence.engineer_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,_c_alertInfo.height - planInfoView.bottom - 70)];// _d_licence.arrDisplayResults.count * CELL_HEIGHT)];
    [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 {    //答案的个数
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ?", [GTOAnswer TableName], @"licenceUuid" ];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_licence.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_licence.arrDisplayResults.count; count ++) {
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_licence.arrDisplayResults[count]];
            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_licence.arrDisplayResults = muArrDisplayRs;
        [_d_licence 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_licence.arrDisplayResults.count;//_d_arrCategorys.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    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;
    GTOCategoryItemView *categoryItem = [contentView viewWithClass:[GTOCategoryItemView class]];
    if (!categoryItem) {
        categoryItem =  [[GTOCategoryItemView alloc]initWithFrame:contentView.bounds];
        [categoryItem autoresizingWithStrechFullSize];
        [contentView addSubview:categoryItem];
    }

    if (_d_licence.arrDisplayResults.count > 0) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_licence.arrDisplayResults[indexPath.row]];
        [categoryItem updateWithLicence:_d_licence licenceDisplayResults:displayR];
        
    }
    
}

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

#pragma GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView leftButtonClicked:(UIButton *)leftBtn {
    
    if ([_delegate respondsToSelector:@selector(alertInfoLicenceViewController:seeResultClickedWithBtton:)]) {
        [_delegate alertInfoLicenceViewController:self seeResultClickedWithBtton:leftBtn];
    }
}

- (void)bottomView:(GXFBottomView *)bottomView RightButtonClicked:(UIButton *)rightBtn {
    if ([_delegate respondsToSelector:@selector(alertInfoLicenceViewController:nextClickedWithBtton:)]) {
        [_delegate alertInfoLicenceViewController:self nextClickedWithBtton:rightBtn];
    }
}

- (void)closeCliced: (UIButton *)btn {
    if ([_delegate respondsToSelector:@selector(alertInfoLicenceViewController:closeClickedWithBtton:)]) {
        [_delegate alertInfoLicenceViewController: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
