//
//  ICRQResultViewController.m
//  Cruiser
//
//  Created by Xummer on 15/6/10.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRQResultViewController.h"
#import "ICRQuestionHelperView.h"
#import "ICRQResultViewController.h"
#import "ICRAttachmentView.h"

#import "GTOPatrolPlan.h"
#import "ICRAnswer.h"
#import "ICRStoreResult.h"
#import "GTOQuestion.h"
#import "ICRTask.h"
#import "ICRPostTask.h"
#import "ICRQuestionManager.h"

#import "ICRPatrolResultViewController.h"
#import "GTOPatrolPlanResultHeaderItem.h"
#import "GTOPatrolPlanResultProblemItem.h"
#import "GTOPatrolPlanResultTopItem.h"
#import "GTODisplayResult.h"




#define GXF_DETAIL_COLOR        HexColor(@"888888")
#define GXF_CONTENT_COLOR       HexColor(@"444444")

#define KEY_IS_DISPLAY @"isDisplay"
@interface ICRQResultViewController () <UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>//, ICRTaskEditViewDelegate>

@property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo;
@property (strong, nonatomic) ICRQuestionHelperView *m_helperView;

@property (strong, nonatomic) NSString* m_storeID;


@property (strong, nonatomic) NSArray *m_answers;


@property (nonatomic, strong) UITableView *m_tableView;
@property (strong, nonatomic) GTOPatrolPlan *m_patrolPlan;
@property (strong, nonatomic) ICRStoreResult *m_storeResult;
@property (nonatomic, copy) NSArray *m_arrQuestonCategory;//，存的为问题的区域
//@property (nonatomic, copy) NSArray *m_arrCategoryQuestions;//存的为字典，不同区域的问题，key为区域，object为对应区的问题
@property (nonatomic, strong) GTODisplayResult *m_displayResult;
//@property (nonatomic, strong) NSArray *m_arrDisplayResults;
@property (nonatomic, strong) NSMutableArray *m_arrDisplayResults;
@property (nonatomic, strong) NSIndexPath *m_clickedIndexPath;
@property (strong, nonatomic) ICRStoreResult *m_result;
@property (nonatomic, assign)  NSInteger m_finishCategorys;
@end

@implementation ICRQResultViewController

#pragma mark - Life Cycle
- (instancetype)initWithPatrolPlan:(id)plan andStoreResult:(id)result {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([plan isKindOfClass:[GTOPatrolPlan class]]) {
        self.m_patrolPlan = plan;
        //[self p_problemsCategory];
    }
    
    if ([result isKindOfClass:[ICRStoreResult class]]) {
        
        ICRStoreResult *res = result;
        
        NSMutableArray *mArr = [NSMutableArray array];
        NSMutableArray *mArrAns = [NSMutableArray array];
        for (NSDictionary *dict in res.answers) {
            ICRAnswer *ans = [ICRAnswer DBObject];
            [ans praseFromLocalDict:dict];
            [mArr safeAddObject:ans];
            [mArrAns safeAddObject:[ans dictForCommit]];
        }
        self.m_answers = mArr;
        self.m_storeID = res.store_uuid;
        res.answers = mArrAns;
        self.m_storeResult = res;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"巡店结果";
    
    [self initTableView];
    [self initBottomBtn];
    [self initData];
}
- (void)initData {
    self.m_finishCategorys = 0;
    
    if (!_m_displayResult) {
        self.m_displayResult = [[GTODisplayResult alloc]init];
    }
    if (!_m_arrDisplayResults) {
        self.m_arrDisplayResults = [NSMutableArray array];
    }
    
    if (!_m_arrQuestonCategory) {
        NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
        if (_m_patrolPlan) {
            self.m_arrQuestonCategory = [NSArray arrayWithArray:[userDef objectForKey:_m_patrolPlan.uuid]];
            [self.m_tableView reloadData];
        }
        
    }
    
    [self p_everyCategoryProblemsWithCategory:_m_arrQuestonCategory];
    
    
}
- (void)initTableView {
    self.m_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 50 - 64) style:UITableViewStylePlain];
    self.m_tableView.delegate = self;
    self.m_tableView.dataSource = self;
    [self.m_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.m_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headerFooter"];
    [self.view addSubview:_m_tableView];

}
- (void)initBottomBtn {
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, _m_tableView.bottom, self.view.width - 100, 40)];
    btn.backgroundColor = ICR_ORANGE_BTN_COLOR;
    [btn setTitle:@"提交结果" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(sumbitResultClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2 +  _m_arrDisplayResults.count;//_m_arrQuestonCategory.count + 2 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 0;
    } else {

        for (int count = 0; count < _m_arrQuestonCategory.count; count ++) {
            if (section == count + 2) {

                GTODisplayResult *displayR = _m_arrDisplayResults[count];
                return   displayR.isDisplay ? displayR.arrAnswers.count : 0;

            }
        }

        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *cellID ;
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        cellID = @"topCell";
        cell = [tableView dequeueReusableCellWithIdentifier: cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            GTOPatrolPlanResultTopItem *topItem = [[GTOPatrolPlanResultTopItem alloc]initWithFrame:cell.bounds];
            [topItem updateWithPatrolPlan:_m_patrolPlan storeResult:_m_storeResult finishCategorysNumber:_m_finishCategorys totalCategorys:_m_arrQuestonCategory.count];
            [cell.contentView addSubview:topItem];
        } else {
            while ([cell.contentView.subviews lastObject] != nil) {
                [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
            }
            GTOPatrolPlanResultTopItem *topItem = [[GTOPatrolPlanResultTopItem alloc]initWithFrame:cell.bounds];
            [topItem updateWithPatrolPlan:_m_patrolPlan storeResult:_m_storeResult finishCategorysNumber:_m_finishCategorys totalCategorys:_m_arrQuestonCategory.count];
            [cell.contentView addSubview:topItem];
        }
    } else {
        cellID = @"questionCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            GTOPatrolPlanResultProblemItem *problemItem = [[GTOPatrolPlanResultProblemItem alloc]initWithFrame:cell.bounds];
            self.m_clickedIndexPath = indexPath;
            problemItem.m_modifyBtn.tag = indexPath.row;
            [problemItem.m_modifyBtn addTarget:self action:@selector(modifyClicked:) forControlEvents:UIControlEventTouchUpInside];
            [problemItem updateWithDisplayResult:_m_arrDisplayResults[indexPath.section - 2] andIndex:indexPath.row];
            [cell.contentView addSubview:problemItem];
           // cell.textLabel.text = @"1111";
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}
#pragma UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 106;
    } else {
        return 55;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HEADER_HEIGHT;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view;
    CGFloat padding = 10;
    static NSString *headerID;
    CGRect rect = CGRectMake(0, 0, tableView.width, 50);
    
    if (section == 0) {
        headerID = @"addressID";
        view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
        if (!view) {
            view = [[UIView alloc]initWithFrame:rect];//tableView.tableHeaderView.bounds];
            CGRect rect = CGRectMake(padding, 0, 150, view.height);
            UILabel *lblTitle = [self p_labelWithFrame:rect title:@"每月例行巡检" font:[UIFont systemFontOfSize:18] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentLeft];
           rect = CGRectMake( view.width - 10 - 100, 0, 100, lblTitle.height);//
            UILabel *lblAddress = [self p_labelWithFrame:rect title:@"杨高油站" font:[UIFont systemFontOfSize:18] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentLeft];//self.m_storeResult.store_name
            [view addSubview:lblTitle];
            [view addSubview:lblAddress];
            view.backgroundColor = XXFBgColor;
        }
    } else if (section == 1) {
        headerID = @"stateID";
        view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
        if (!view) {
            view = [[UIView alloc]initWithFrame:rect];//tableView.tableHeaderView.bounds];
            CGRect rect = CGRectMake(padding, 0, 100, view.height);
            UILabel *lblState = [self p_labelWithFrame:rect title:@"巡检状态" font:[UIFont systemFontOfSize:18] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentLeft];

            [view addSubview:lblState];
        }
         view.backgroundColor = XXFBgColor;
    } else {
       headerID = @"categoryID";
        view =[tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
       // view.tag = section;
        if (!view) {
            GTOPatrolPlanResultHeaderItem *resultHeader = (GTOPatrolPlanResultHeaderItem *)[[GTOPatrolPlanResultHeaderItem alloc]initWithFrame:rect];//
            GTODisplayResult *displayR = _m_arrDisplayResults[section - 2];
           
            resultHeader.isDisplay = displayR.isDisplay;//isDisplay;
            [resultHeader setDelegate:(id<GTOPatrolPlanResultHeaderItemDelegate>)self];
            resultHeader.backgroundColor = [UIColor whiteColor];
            [resultHeader updateWithDisplayResult:displayR];
            resultHeader.tag = section ;
            view = resultHeader;
        }
        
    }
    
    return view;
    
}

#pragma Button Action
- (void)modifyClicked: (UIButton *)btn {
    
}
#pragma GTOPatrolPlanResultHeaderItemDelegate
- (void)patrolPlanResultHeaderItem: (GTOPatrolPlanResultHeaderItem *)resultHeaderItem
                      andIsDisplay: (BOOL)isDisplay {
     NSInteger aIndex = resultHeaderItem.tag - 2;
    GTODisplayResult *displayR = _m_arrDisplayResults[aIndex];
    displayR.isDisplay = !displayR.isDisplay;
    [self.m_arrDisplayResults replaceObjectAtIndex:aIndex withObject:displayR];
//   // _m_arrCategoryQuestions
//    NSMutableArray *muArr = [NSMutableArray arrayWithArray:_m_arrCategoryQuestions];
//    NSInteger aIndex = resultHeaderItem.tag - 2;
//    NSMutableDictionary *muDict = _m_arrCategoryQuestions[aIndex];
//    NSInteger aisDisplay = [muDict[KEY_IS_DISPLAY] integerValue];
//    [muDict setObject:[NSString stringWithFormat:@"%d",!aisDisplay] forKey:KEY_IS_DISPLAY];
//    NSDictionary *dictQuestions = muDict[[_m_arrQuestonCategory objectAtIndex:aIndex]];
//    [muDict setObject:dictQuestions forKey:[_m_arrQuestonCategory objectAtIndex:aIndex]];
////    [muArr replaceObjectAtIndex:aIndex withObject:muDict];
////    [self.m_arrCategoryQuestions addObject:muDict];  即使我把m_arrCategoryQuestions定义为可变的，为什么打印出来确实不可变的<__NSArray 0x7fcf50659750>，而且不能执行这种操作，但是muArr却可以？？？？不懂？？？
////    [self.m_arrCategoryQuestions removeObjectAtIndex:aIndex];
//
//    self.m_arrCategoryQuestions = nil;
//    self.m_arrCategoryQuestions = [NSArray arrayWithArray:muArr];
//    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:aIndex + 2];
//    [_m_tableView reloadSections:indexSet withRowAnimation:YES];
    [_m_tableView reloadData];
}
- (UILabel *)p_labelWithFrame: (CGRect)a_frame
                      title: (NSString *)a_title
                       font: (UIFont *)a_font
                  textColor: (UIColor *)a_textColor
              textAlignment: (NSTextAlignment)a_textAlignment {
    UILabel *lbl = [[UILabel alloc]initWithFrame:a_frame];
    lbl.text = a_title;
    lbl.font = a_font;
    lbl.textColor = a_textColor;
    lbl.textAlignment = a_textAlignment;
    return lbl;
}
- (void)p_everyCategoryProblemsWithCategory: (NSArray *)arrCagegory {
    
    NSUInteger uiQuestionsCount = [_m_patrolPlan.questions count];
    NSArray *arrQuestIDs = [_m_patrolPlan.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 < arrCagegory.count; count ++) {
          GTODisplayResult *displayR = [[GTODisplayResult alloc]init];
            NSMutableArray *questions = [NSMutableArray array];
            for (GTOQuestion *questE in fetchedObjects) {  //符合区域分类的，（其实可以用数据表查询的，但是还没实现？？？？？？）
                if ([questE.category isEqualToString:arrCagegory[count]]) {
                    [questions addObject:questE];
                }
            }
           
            NSMutableDictionary *muditct = [NSMutableDictionary dictionaryWithObjects:@[questions,@"0"] forKeys:@[arrCagegory[count],KEY_IS_DISPLAY]];
            displayR.category = arrCagegory[count];
            displayR.isDisplay = 0;
            displayR.arrQuestions = questions;
            [muArr addObject:displayR];
        }
        
        strongSelf.m_arrDisplayResults = [NSMutableArray arrayWithArray:muArr];//[NSArray arrayWithArray:muArr];
         [self.m_tableView reloadData];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOQuestion class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
    __block NSMutableArray *muArrDS = [NSMutableArray array];
    for(int count = 0;count  < _m_arrQuestonCategory.count;count ++){
   
    //Answer
    ICRDatabaseFetchBlock srFetchBlk = ^FMResultSet *(FMDatabase *db) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? and  %@ = ? and %@ = ?", [ICRStoreResult TableName], @"uuid", @"store_uuid",@"category"];//根据油站找对应的答案
        return [db executeQuery:sql,strongSelf.m_patrolPlan.uuid ,strongSelf.m_storeID,_m_arrQuestonCategory[count]];
    };
    ICRDatabaseFetchResultsBlock srFetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_result = [fetchedObjects firstObject];
        NSMutableArray *mArr = [NSMutableArray array];
        for(GTODisplayResult *displayR in _m_arrDisplayResults) {
            if ([displayR.category isEqualToString:_m_arrQuestonCategory[count]]) {
                  NSMutableArray *arrAnswers = [NSMutableArray array];
                for (NSDictionary *dict in _m_result.answers)  {
                     ICRAnswer *answer = [ICRAnswer DBObject];
                    [answer praseFromJsonDict:dict];
                    [arrAnswers addObject:answer];
                }
                displayR.arrAnswers = arrAnswers; //这里已经把self.m_arrDisplayResults中的值给换了
                [muArrDS addObject:displayR];
                
                if(displayR.arrQuestions.count == displayR.arrAnswers.count)
                    strongSelf.m_finishCategorys ++;
                
            }
        }

    };
    
    [dbCtrl runFetchForClass:[ICRStoreResult class]
                  fetchBlock:srFetchBlk
           fetchResultsBlock:srFetchResultsBlk];
     
 };
    
}

- (void)sumbitResultClicked {
        __weak typeof(self)weakSelf = self;
        void(^succ)(id) = ^(id data) {
    //        __strong __typeof(weakSelf)strongSelf = weakSelf;
    //        [strongSelf uploadTaskAndAttachesWithComplete:^{
    //            UIViewController *pvc = self.navigationController.presentingViewController;
    //            ICRAppViewControllerManager *appVCtrl = [ICRAppViewControllerManager getAppViewControllerManager];
    //            UIViewController *VC = [appVCtrl getTabBarBaseViewController:[appVCtrl getCurTabBarIndex]];
    //            [VC PopViewControllerAnimated:NO];
    //
    //            [pvc dismissViewControllerAnimated:YES completion:NULL];
    //        }];
        };
    
//        void(^fail)(id) = ^(id data) {
//            [IBTLoadingView showTips:data];
//            _m_result.isNotUploaded = YES;
//    
//            [_m_result saveToDBWithHandleData:NULL complete:NULL fail:NULL];
//        };
//    
//        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
//        [httpCtrl doSubmitAnswerPatrolPlanWithID: _m_plan.uuid  infoData:[_m_result dictForCommit]
//                                   success:succ
//                                   failure:fail];



}

- (void)onSubmitBtnAction:(__unused id)sender {
    
//    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
//    
//    [_m_helperView.m_inputTxtF resignFirstResponder];
//    _m_result.remark = _m_helperView.m_inputTxtF.text ? : @"";
//    
//    __weak typeof(self)weakSelf = self;
//    void(^succ)(id) = ^(id data) {
////        __strong __typeof(weakSelf)strongSelf = weakSelf;
////        [strongSelf uploadTaskAndAttachesWithComplete:^{
////            UIViewController *pvc = self.navigationController.presentingViewController;
////            ICRAppViewControllerManager *appVCtrl = [ICRAppViewControllerManager getAppViewControllerManager];
////            UIViewController *VC = [appVCtrl getTabBarBaseViewController:[appVCtrl getCurTabBarIndex]];
////            [VC PopViewControllerAnimated:NO];
////            
////            [pvc dismissViewControllerAnimated:YES completion:NULL];
////        }];
//    };
//    
//    void(^fail)(id) = ^(id data) {
//        [IBTLoadingView showTips:data];
//        _m_result.isNotUploaded = YES;
//        
//        [_m_result saveToDBWithHandleData:NULL complete:NULL fail:NULL];
//    };
//    
//    [httpCtrl doSubmitAnswerPatrolPlanWithID: _m_plan.uuid  infoData:[_m_result dictForCommit]
//                               success:succ
//                               failure:fail];
}

@end
