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

#import "GTOAlertInfoPatrolPlanViewController.h"
#import "GTOPioneering.h"
#import "GXFBottomView.h"
#import "GTOCategoryItemView.h"
#import "GTOLicence.h"
#import "GTOQuestion.h"


#import "ICRAnswer.h"
#import "ICRStoreResult.h"
#import "GTOPatrolPlan.h"
static NSString * cellID = @"cellId";
#define CELL_HEIGHT 65
@interface  GTOAlertInfoPatrolPlanViewController ()
<UITableViewDataSource,UITableViewDelegate,GXFBottomViewDelegate,
UITextFieldDelegate>
//@property (nonatomic, strong) GTOLicence *d_licence;

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

//avatar
@property (nonatomic, strong) ICRStoreResult *d_storeResult;
@property (nonatomic, strong) GTOPatrolPlan *d_patrolPlan;
@end

@implementation  GTOAlertInfoPatrolPlanViewController
- (instancetype)initWithStoreResult:(ICRStoreResult *)storeResult
                      andPatrolPlan: (GTOPatrolPlan *)patrolPlan {
    self = [super init];
    if(!self) return nil;
    self.d_storeResult = storeResult;
    self.d_patrolPlan = patrolPlan;
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   // [self initData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    
}
- (void)initSubViews {
    CGFloat padding = 0;//整个alertInfo距离阴影部分
    CGFloat topVH = 50;

    CGFloat alertInfoH = topVH + (17 + GTO_TOP_VERTICAL_PADDING ) * 4 + 1 + _d_storeResult.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_storeResult.store_name;
    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 ) * 4 + 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_patrolPlan.name] 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_patrolPlan.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_storeResult.user_name] font:font tintColor:nil backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    
    UILabel *positionLabel = [ [IBTUILabel alloc]initWithFrame:CGRectMake(patrolNameLabel.x, inspectorLabel.bottom + GTO_TOP_VERTICAL_PADDING , planInfoView.width - 60, lblH) text:[NSString stringWithFormat:@"签到坐标: (%@,%@)",[GTOCommonTools nullChangedWithId:_d_storeResult.latitude],[GTOCommonTools nullChangedWithId:_d_storeResult.longitude]] font:font tintColor:nil backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    
    [_c_alertInfo addSubview:planInfoView];
    [planInfoView addSubview:patrolNameLabel];
    [planInfoView addSubview:timeLabel];
    [planInfoView addSubview:inspectorLabel];
    [planInfoView addSubview:positionLabel];
    
    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 {    //答案的个数
//    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? AND  %@ = ?  ", [ICRAnswer TableName], @"plan_uuid",@"store_uuid" ];
//        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
//        NSLog(@"%@",sql);
//        return [db executeQuery:sql,_d_storeResult.patrolUuid,_d_storeResult.store_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:[ICRAnswer class]
//                  fetchBlock:fetchBlk
//           fetchResultsBlock:fetchResultsBlk];
//}



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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
//    static NSString * Id = @"cellId";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
//    
//    if (!cell) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Id];
//        
//    } else {
//        while ([cell.contentView.subviews lastObject] != nil) {
//            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
//        }
//        
//    }
//    
//    GTOCategoryItemView *categoryItem = [[GTOCategoryItemView alloc]initWithFrame:CGRectMake(0, 0, cell.contentView.width - 20, cell.contentView.height)];//cell.bounds];
//    //        if (_d_arrProcesses.count > 0) {
//    // GTOPioneeingProcess *process = _d_arrProcesses[indexPath.row];
//    if (_d_storeResult.arrDisplayResults.count > 0) {
//        GTODisplayResult *displayR = [GTODisplayResult DBObject];
//        [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[indexPath.row]];
//        
//        [categoryItem updateWithStoreResult:_d_storeResult storeResultDisplayResults:displayR];
//        
//    }
//    
//    [cell.contentView addSubview:categoryItem];
//    return cell;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];//[tableView cellForRowAtIndexPath: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];
    }
    
    //    GTOCategoryItemView *categoryItem = [[GTOCategoryItemView alloc]initWithFrame:CGRectMake(0, 0, cell.contentView.width - 20, cell.contentView.height)];//cell.bounds];
    //    //        if (_d_arrProcesses.count > 0) {
    //    // GTOPioneeingProcess *process = _d_arrProcesses[indexPath.row];
    if (_d_storeResult.arrDisplayResults.count > 0) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[indexPath.row]];
        
        [categoryItem updateWithStoreResult:_d_storeResult storeResultDisplayResults:displayR];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.backgroundColor = [UIColor clearColor];
    
}

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

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

- (void)bottomView:(GXFBottomView *)bottomView RightButtonClicked:(UIButton *)rightBtn {
    if ([_delegate respondsToSelector:@selector(alertInfoPatrolPlanViewController:nextClickedWithBtton:)]) {
        [_delegate alertInfoPatrolPlanViewController:self nextClickedWithBtton:rightBtn];
    }
}
- (void)closeCliced: (UIButton *)btn {
    if ([_delegate respondsToSelector:@selector(alertInfoPatrolPlanViewController:closeClickedWithBtton:)]) {
        [_delegate alertInfoPatrolPlanViewController: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
