//
//  ICRQReseachViewController.m
//  XFFruit
//
//  Created by Xummer on 6/7/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRQReseachViewController.h"
#import "ICRQuestionManager.h"

#import "NALLabelsMatrix.h"
#import "ICRQInputPopup.h"

#define LEFT_MARGIN                  (15)

@interface ICRQReseachViewController ()
<
    ICRQInputPopupDelegate
>
{
    NSUInteger uiColCount;
}
@property (strong, nonatomic) NALLabelsMatrix *m_form;
@property (strong, nonatomic) UIButton *m_addRowBtn;
@property (strong, nonatomic) NSMutableArray *m_arrAnswers;
@end

@implementation ICRQReseachViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.m_arrAnswers = [NSMutableArray array];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"seq" ascending:YES];
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"answer" ascending:YES];
    NSArray *aDetails = [self.m_answer.details sortedArrayUsingDescriptors:@[ sort, sort2 ]];
    
    [_m_arrAnswers addObjectsFromArray:aDetails];

    NSMutableArray *mArr = [NSMutableArray array];
    
    NSUInteger rInd, cInd;
    NSUInteger cMaxInd = uiColCount - 1;
    NSString *value = nil;
    for (NSDictionary *dict in _m_arrAnswers) {
        rInd = [dict[ @"seq" ] unsignedIntegerValue];
        cInd = [dict[ @"answer"] unsignedIntegerValue];
        if (cInd == 1) {
            [mArr addObject:[NSString stringWithFormat:@"%@", @( rInd )]];
            value = dict[ @"stringResult"];
            [mArr safeAddObject:value];
        }
        else if (cInd == cMaxInd) {
            value = dict[ @"intResult" ];
            [mArr safeAddObject:value];
            
            [_m_form addRecord:mArr];
            
            [mArr removeAllObjects];
        }
        else {
            value = dict[ @"stringResult"];
            [mArr safeAddObject:value];
        }
    }
}

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

#pragma mark - Private Method

- (void)initScrollViewWithRect:(CGRect)rect {
    [super initScrollViewWithRect:rect];
    
    self.m_addRowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m_addRowBtn setTitleColor:[UIColor whiteColor]
                       forState:UIControlStateNormal];
    [_m_addRowBtn setTitle:@"+ 添加一条" forState:UIControlStateNormal];
    [_m_addRowBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithR:60 g:212 b:115 a:1]]
                            forState:UIControlStateNormal];
    _m_addRowBtn.layer.cornerRadius = 3;
    _m_addRowBtn.layer.masksToBounds = YES;
    _m_addRowBtn.frame = (CGRect){
        .origin.x = CGRectGetWidth(rect) - LEFT_MARGIN - 90,
        .origin.y = 5,
        .size.width = 90,
        .size.height = 30
    };
    
    _m_addRowBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_m_addRowBtn addTarget:self action:@selector(onAddNewRow:)
           forControlEvents:UIControlEventTouchUpInside];
    [self.m_contentScrollView addSubview:_m_addRowBtn];
    
    CGFloat fW = CGRectGetWidth(rect) - 2 * LEFT_MARGIN;
    
    NSMutableArray *arrTitles = [NSMutableArray array];
    [arrTitles addObject:@"序号"];
    
    for (NSDictionary *dict in self.m_arrOptions) {
        [arrTitles addObject:dict[ @"content"] ];
    }
    
    [arrTitles addObject:@"零售价"];
    
    NSUInteger uiItemsCount = [arrTitles count];
    uiColCount = uiItemsCount;
    CGFloat fCW = ceilf( fW / (CGFloat)uiItemsCount );
    NSMutableArray *arrCWidths = [NSMutableArray array];
    for (NSUInteger i = 0; i < uiItemsCount; i ++) {
        [arrCWidths addObject:@( fCW )];
    }
    
    _m_form = [[NALLabelsMatrix alloc] initWithFrame:CGRectMake(LEFT_MARGIN, _m_addRowBtn.bottom + 5, fW, 100) andColumnsWidths:arrCWidths];
    _m_form.m_bIsEditable = YES;
    
    [_m_form addRecord:arrTitles];
    
    [self.m_contentScrollView addSubview:_m_form];
}

#pragma mark - Actions
- (void)onAddNewRow:(id)sender {
    ICRQInputPopup *popUp = [[ICRQInputPopup alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = self.view.width,
        .size.height = 300
    }];
    
    NSMutableArray *arrTitles = [NSMutableArray array];
    for (NSDictionary *dict in self.m_arrOptions) {
        [arrTitles addObject:dict[ @"content"] ];
    }
    
    [popUp updateSuervyData:arrTitles];
    popUp.m_delegate = self;
    
    [popUp showInView:self.view.window];
}

#pragma mark - ICRQInputPopupDelegate
- (void)inputPopup:(ICRQInputPopup *)popup didAddRecords:(NSArray *)arrRecords {
    NSMutableArray *mArr = [NSMutableArray array];
    NSUInteger colIndex = [_m_form rowsCount];
    NSNumber *numInd = @( colIndex );
    [mArr addObject:[NSString stringWithFormat:@"%@", numInd]];
    [mArr addObjectsFromArray:arrRecords];
    [_m_form addRecord:mArr];
    
    NSUInteger i = 1;
    for (NSString *str in arrRecords) {
        ICRAnswerDetail *aE = [ICRAnswerDetail DBObject];
        aE.uuid = [[ICRUserUtil sharedInstance] mobileID];
        aE.numberValue = i;
        aE.index = colIndex;
        
        if (i == [arrRecords count]) {
            aE.numberValue = [str integerValue];
            
        }
        else {
            aE.stringValue = str;
        }
        
        [_m_arrAnswers addObject:[aE dictForCommit]];

        i ++;
    }
    
}

#pragma mark - Actions
- (void)onNextBtnAction:(__unused id)sender {
    
    if ([_m_arrAnswers count] == 0) {
        self.m_answer.bIsAnswered = NO;
        return;
    }
    
    self.m_answer.details = _m_arrAnswers;
    
    self.m_answer.bIsAnswered = YES;
    
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    UIViewController *qVC = [mgr questionViewControlAtIndex:self.m_uiIndex + 1];
    if (qVC) {
        [self PushViewController:qVC animated:YES];
    }
    else {
        [self openResultView];
    }
}


@end
