//
//  ICRPatrolResultViewController.m
//  XFFruit
//
//  Created by Xummer on 15/6/8.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRPatrolResultViewController.h"
#import "ICRPatrolPlan.h"
#import "ICRStoreResult.h"
#import "ICRQuestion.h"

@interface ICRPatrolResultViewController ()

@property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo;

@property (strong, nonatomic) ICRPatrolPlan *m_plan;
@property (copy, nonatomic) NSString * m_storeID;
@property (strong, nonatomic) ICRStoreResult *m_result;

@end

@implementation ICRPatrolResultViewController

#pragma mark - Life Cycle
- (instancetype)initWithPatrolPlan:(id)plan storeID:(NSString *)storeID {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([plan isKindOfClass:[ICRPatrolPlan class]]) {
        self.m_plan = plan;
    }
    
    self.m_storeID = storeID;
    
    return self;
}

- (instancetype)initWithPatrolPlan:(id)plan andStoreResult:(id)result {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([plan isKindOfClass:[ICRPatrolPlan class]]) {
        self.m_plan = plan;
    }
    
    if ([result isKindOfClass:[ICRStoreResult class]]) {
        self.m_result = result;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"巡店结果";
    
    [self initTableViewInfo];
    
    if (!_m_result) {
        [self fetchLocalData];
        
        __weak typeof(self)weakSelf = self;
        void(^succ)(id) = ^(id data) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf fetchLocalData];
        };
        
        void(^fail)(id) = ^(id data) {
            [IBTLoadingView showTips:data];
        };
        
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        [httpCtrl doGetStoreResultWithPlanID:_m_plan.pID storeID:_m_storeID success:succ failure:fail];
    }
    else {
        [self updateTableViewInfo];
    }
}

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

#pragma mark - Private Method
- (void)fetchLocalData {
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRStoreResult TableName], @"uuid"];
        return [db executeQuery:sql,strongSelf.m_plan.pID];
    };
    
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_result = [fetchedObjects firstObject];
        [strongSelf updateTableViewInfo];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRStoreResult class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

- (void)initTableViewInfo {
    self.m_tableViewInfo = [[IBTTableViewInfo alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    IBTTableView *tableV = [_m_tableViewInfo getTableView];
    [self.view addSubview:tableV];
}

- (void)updateTableViewInfo {
    [self.m_tableViewInfo removeSectionAt:0];
    
    if (_m_result) {
        
        NSArray *arrQuestions = _m_plan.questions;
        NSArray *arrAnswers = _m_result.answers;
        
//        if ([arrQuestions count] != [arrAnswers count]) {
//            return;
//        }
        
        IBTTableViewSectionInfo *secInfo = [IBTTableViewSectionInfo sectionInfoDefaut];
        IBTTableViewCellInfo *cellInfo;
        for (NSUInteger i = 0; i < [arrQuestions count]; i++) {
            NSDictionary *dictQ = arrQuestions[ i ];
            NSDictionary *dictA = arrAnswers[ i ];
            
            NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"lineNo" ascending:YES];
            NSArray *arrAnswerDetails = dictA[ @"answerDetails" ];
            
            NSString *nsTitle = [NSString stringWithFormat:@"%@.%@", @( i+1 ), dictQ[ @"title" ]];
            NSString *nsRightValue = nil;
            
            ICRQestionType eType = [dictQ[ @"type" ] integerValue];
            switch (eType) {
                case kICRQestionTypeSingleSel:
                {
                    NSDictionary *dictDetail = [arrAnswerDetails firstObject];
//                    NSUInteger uiAnswer = [dictDetail[ @"numberValue" ] integerValue] - 1;
//                    
//                    NSDictionary *dictOption = [arrOptions safeObjectAtIndex:uiAnswer];
//                    
//                    nsRightValue = dictOption[ @"content" ];
                }
                    break;
                case kICRQestionTypeMultipleSel:
                {
//                    NSArray *arrAnswers = [arrAnswerDetails valueForKeyPath:@"answer"];
                    
//                    NSMutableArray *tmpArr = [NSMutableArray array];
//                    for (NSNumber *answer in arrAnswers) {
//                        NSUInteger uiAnswer = [answer integerValue] - 1;
//                        NSDictionary *dictOption = [arrOptions safeObjectAtIndex:uiAnswer];
//                        [tmpArr safeAddObject:dictOption[ @"content" ]];
//                    }
                    
//                    nsRightValue = [tmpArr componentsJoinedByString:@"/"];
                }
                    break;
                case kICRQestionTypeReply:
                {
                    nsRightValue = dictA[ @"content" ];
                }
                    break;
                case kICRQestionTypeScore:
                {
                    NSNumber *numScore = dictA[ @"score" ];
                    
                    nsRightValue = [NSString stringWithFormat:@"%@分", @( [numScore integerValue])];
                }
                    break;
                case kICRQestionTypeStoreInv:
                {
                    nsRightValue = @"点击查看";
                }
                    break;
                case kICRQestionTypeSpeciesInv:
                {
                    nsRightValue = @"点击查看";
                }
                    break;
                case kICRQestionTypeStarNum:
                {
                    NSNumber *numScore = dictA[ @"score" ];
                    NSNumber *numMaxScore = dictQ[ @"star" ];
                    nsRightValue = [NSString stringWithFormat:@"%@/%@", @( [numScore integerValue]), @([numMaxScore integerValue]) ];
                }
                    break;
                default:
                    break;
            }
            
            cellInfo = [self cellWithLeft:nsTitle right:nsRightValue sel:NULL];
            
            [secInfo addCell:cellInfo];
        }
        
        if ([secInfo getCellCount] > 0) {
            [_m_tableViewInfo addSection:secInfo];
        }
    }
    
    [[self.m_tableViewInfo getTableView] reloadData];
    
}

- (IBTTableViewCellInfo *)cellWithLeft:(NSString *)nsLeftValue
                                 right:(NSString *)nsRightValue sel:(SEL)sel
{
    IBTTableViewCellInfo *cellInfo = [IBTTableViewCellInfo normalCellForSel:sel target:self title:nsLeftValue rightValue:nsRightValue accessoryType:UITableViewCellAccessoryNone];
    
    return cellInfo;
}

@end
