//
//  ICRQReseachViewController.m
//  Cruiser
// 5 品类调查类
//  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];
    //numberValue: row;   index:column
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"numberValue" ascending:YES];
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"index" 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[ @"numberValue" ] unsignedIntegerValue];
        cInd = [dict[ @"index"] unsignedIntegerValue];//库存或调研题的序号
        if (cInd == 1) {
            [mArr addObject:[NSString stringWithFormat:@"%@", @( rInd )]];
            value = dict[ @"stringValue"];
            [mArr safeAddObject:value];
        }
        else if (cInd == cMaxInd) {
            value = dict[ @"stringValue"];
            [mArr safeAddObject:value];
            
            [_m_form addRecord:mArr];
            
            [mArr removeAllObjects];
        }
        else {
            value = dict[ @"stringValue"];
            [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[ @"value"] ];
    }
    
   // [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];
    if (self.d_notEdit) {
        _m_form.userInteractionEnabled = NO;
    }
}

#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[ @"value"] ];
    }
    
    [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 = colIndex;//行
        aE.index = i;//列
        
        aE.stringValue = str;
//        if (i == [arrRecords count]) {
//            aE.numberValue = [str integerValue];
//            
//        }
//        else {
//            aE.stringValue = str;
//       }
        
        [_m_arrAnswers addObject:[aE dictForCommit]];
        
        i ++;
    }
    //self.m_answer.details = _m_arrAnswers;
    
}

#pragma mark - Actions
- (void)onNextBtnAction:(__unused id)sender {
    if (self.d_notEdit) {
        [super disMissSelf];
        return;
    }
    if ([_m_arrAnswers count] == 0) {
        self.m_answer.bIsAnswered = NO;
        return;
    }
    
    self.m_answer.details = _m_arrAnswers;
    self.m_answer.bIsAnswered = YES;
    self.m_answer.remark = self.m_helperView.m_inputTxtF.text;
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    UIViewController *qVC = [mgr questionViewControlAtIndex:self.m_uiIndex + 1];
    if (qVC) {
        [self PushViewController:qVC animated:YES];
    }
    else {
        [super disMissSelf];
//        [self openResultView];
    }
    [self.m_answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
}


@end

