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

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

#import "ICRPatrolPlan.h"
#import "ICRAnswer.h"
#import "ICRStoreResult.h"
#import "ICRQuestion.h"
#import "ICRTask.h"
#import "ICRPostTask.h"
#import "ICRQuestionManager.h"

#import "ICRTaskEditViewController.h"

@interface ICRQResultViewController () <UITextFieldDelegate, ICRTaskEditViewDelegate>

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

@property (strong, nonatomic) ICRPatrolPlan *m_plan;
@property (assign, nonatomic) NSUInteger m_storeID;
@property (strong, nonatomic) ICRStoreResult *m_result;

@property (strong, nonatomic) NSArray *m_answers;

@end

@implementation ICRQResultViewController

#pragma mark - Life Cycle
- (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]]) {
        
        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;
        res.answers = mArrAns;
        self.m_result = res;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"巡店纪录";
    
    CGFloat fHeight = 210;
    self.m_helperView = [[ICRQuestionHelperView alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = self.view.height - fHeight,
        .size.width = self.view.width,
        .size.height = fHeight
    } isResult:YES];
    _m_helperView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [_m_helperView.m_taskAttachView.m_addButton addTarget:self
                                                    action:@selector(onShowTaskCreateView:)
                                          forControlEvents:UIControlEventTouchUpInside];
    _m_helperView.m_inputTxtF.delegate = self;
    _m_helperView.m_inputTxtF.text = _m_result.remark;
    
    [_m_helperView.m_nextBtn setTitle:@"提交处理" forState:UIControlStateNormal];
    [_m_helperView.m_nextBtn addTarget:self
                                action:@selector(onSubmitBtnAction:)
                      forControlEvents:UIControlEventTouchUpInside];
    
    [self initTableViewInfo];
    
    [self.view addSubview:_m_helperView];
    
    [self registerForKVO];
}

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

- (void)dealloc {
    [self unregisterFromKVO];
}

#pragma mark - Private Method

- (void)initTableViewInfo {
    
    self.view.backgroundColor = [UIColor colorWithR:240 g:246 b:255 a:1];

    self.m_tableViewInfo = [[IBTTableViewInfo alloc] initWithFrame:self.view.bounds
                                                             style:UITableViewStylePlain];
    
    IBTTableView *tableV = [_m_tableViewInfo getTableView];
    tableV.backgroundColor = [UIColor clearColor];
    tableV.bHandleKeyboard = YES;
    
    // Footer
    UIButton *btn = nil;
    UIView *tableFooter =
    [tableV buttonViewWithTitle:@"浏览巡店结果"
                          color:ICR_ORANGE_BTN_COLOR
                         topGap:25
                        pointer:&btn
                         target:self
                         action:@selector(oneRsultButtonAction:)];
    tableV.tableFooterView = tableFooter;
    
    
    [self.view addSubview:tableV];
    
    // # Section 0
    IBTTableViewSectionInfo *sec0Info = [IBTTableViewSectionInfo sectionInfoDefaut];
    
    // User ID
    IBTTableViewCellInfo *titleCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Title"]
                                rightValue:_m_plan.name
                             accessoryType:UITableViewCellAccessoryNone];
    titleCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:titleCellInfo];
    
    IBTTableViewCellInfo *typeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Type"]
                                rightValue:_m_plan.category
                             accessoryType:UITableViewCellAccessoryNone];
    typeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:typeCellInfo];
    
    NSString *nsStart = [[_m_plan.beginDate componentsSeparatedByString:@" "] firstObject];
    NSString *nsEnd = [[_m_plan.endDate componentsSeparatedByString:@" "] firstObject];
    
    IBTTableViewCellInfo *planTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Scheduled Time"]
                                rightValue:[NSString stringWithFormat:@"%@~%@", nsStart, nsEnd]
                             accessoryType:UITableViewCellAccessoryNone];
    planTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:planTimeCellInfo];
    
    IBTTableViewCellInfo *startTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Start Time"]
                                rightValue:_m_result.beginTime
                             accessoryType:UITableViewCellAccessoryNone];
    startTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:startTimeCellInfo];
    
    IBTTableViewCellInfo *endTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:@"结束时间"
                                rightValue:_m_result.endTime
                             accessoryType:UITableViewCellAccessoryNone];
    endTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:endTimeCellInfo];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss"];
    
    NSDate *startDate = [dateFormatter dateFromString:_m_result.beginTime];
    NSDate *endDate = [dateFormatter dateFromString:_m_result.endTime];
    
    NSTimeInterval costTime = [endDate timeIntervalSince1970] - [startDate timeIntervalSince1970];
    NSTimeInterval mins = costTime/60;
    
    NSUInteger h = mins / 60;
    NSUInteger m = mins - h * 60;
    
    NSString *nsCostTime;
    
    if (h > 0) {
        nsCostTime = [NSString stringWithFormat:@"%@小时%@分", @( h ), @( m )];
    }
    else {
        nsCostTime = [NSString stringWithFormat:@"%@分", @( m ? m : 1 )];
    }
    
    IBTTableViewCellInfo *costTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:@"耗时"
                                rightValue:nsCostTime
                             accessoryType:UITableViewCellAccessoryNone];
    endTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:costTimeCellInfo];
    
    [_m_tableViewInfo addSection:sec0Info];
    
}

- (void)uploadTaskAndAttachesWithComplete:(void (^)(void))complete {
    
    NSMutableArray *arrTasks = [NSMutableArray array];
    NSMutableArray *arrAttachs = [NSMutableArray array];
    
    // Result Task
    if ([_m_helperView.m_taskAttachView.m_arrAttViews count] > 0) {
        ICRAttachmentUnit *unit = [_m_helperView.m_taskAttachView.m_arrAttViews firstObject];
        ICRPostTask *pTask = unit.m_oAttachmentWrap;
        
        [arrTasks safeAddObject:[pTask dictForCommit]];
    }
    
    // Answers
    for (ICRAnswer *answer in _m_answers) {
        if (answer.task) {
            ICRPostTask *postTask = [ICRPostTask DBObject];
            [postTask praseFromLocalDict:answer.task];
            
//            [arrAttachs safeAddObject:postTask.photo];
            
            [arrTasks safeAddObject:[postTask dictForCommit]];
        }
        
        [arrAttachs safeAddObject:answer.photo];
        [arrAttachs safeAddObject:answer.voice];
    }
    
    if ([arrAttachs count] == 0 && [arrTasks count] == 0) {
        if (complete) {
            complete();
        }
        
        return;
    }
    
    __block NSUInteger uiTaskCompleteCount = 0;
    __block NSUInteger uiAttachCompleteCount = 0;
    NSUInteger uiAllTaskCount = [arrTasks count];
    NSUInteger uiAllAttachCount = [arrAttachs count];
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    void(^taskSucc)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^taskFail)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attSucc)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attFail)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    for (NSDictionary *dict in arrTasks) {
        [httpCtrl doCreateNewTaskWithInfo:dict success:taskSucc failure:taskFail];
    }
    
    for (NSDictionary *dict in arrAttachs) {
        [httpCtrl doAddAttachment:dict success:attSucc failure:attFail];
    }
}

#pragma mark - Actions
- (void)oneRsultButtonAction:(__unused id)sender {
    ICRPatrolResultViewController *rVC = [[ICRPatrolResultViewController alloc] initWithPatrolPlan:_m_plan andStoreResult:_m_result];
    [self PushViewController:rVC animated:YES];
}

- (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 doAnswerPatrolPlanWithID: _m_plan.pID infoData:[_m_result dictForCommit]
                               success:succ
                               failure:fail];
}

- (void)openEditTaskView:(ICRTask *)task
{
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    
    ICRTaskEditViewController *tVC =
    [[ICRTaskEditViewController alloc] initWithTask:task store:mgr.m_store];
    tVC.m_delegate = self;
    [self PushViewController:tVC animated:YES];
}

- (void)onShowTaskCreateView:(__unused id)sender {
    [self openEditTaskView:nil];
}

- (void)onTapTask:(ICRAttachmentUnit *)unit {
    ICRPostTask *pTask = unit.m_oAttachmentWrap;
    [self openEditTaskView:[ICRTask taskFromPostTask:pTask]];
}

- (void)addAttachment:(id)oAtt {
    
    SEL selector = NULL;
    
    UIImage *iconImg;
    ICRAttachmentView *attachView = nil;
    
    iconImg = [UIImage imageNamed:@"icon_task_default"];
    selector = @selector(onTapTask:);
    attachView = self.m_helperView.m_taskAttachView;
    
    ICRAttachmentUnit *attV = [[ICRAttachmentUnit alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = IBT_ATTACH_UNIT_DEFAULT_WIDTH,
        .size.height = IBT_ATTACH_UNIT_DEFAULT_WIDTH
    }];
    [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil
                   image:iconImg title:nil];
    attV.m_oAttachmentWrap = oAtt;
    
    [attV addTarget:self
             action:selector
   forControlEvents:UIControlEventTouchUpInside];
    
    [attachView addContentAttachmentView:attV];
}

#pragma mark - ICRTaskEditViewDelegate
- (void)taskEditViewCtrl:(ICRTaskEditViewController *)viewCtrl taskData:(id)taskData
{
    ICRPostTask *pTask = taskData;
//    pTask.patrolResult = _m_result.mobileId;
    
    [self addAttachment:pTask];
    
    [viewCtrl PopViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - KVO

- (void)registerForKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_m_helperView addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    }
}

- (void)unregisterFromKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_m_helperView removeObserver:self forKeyPath:keyPath];
    }
}

- (NSArray *)observableKeypaths {
    return @[ @"frame" ];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [[self.m_tableViewInfo getTableView] setContentInsetTop:0 andBottom: self.view.height - _m_helperView.y];
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    
    if ([_m_helperView.m_inputTxtF isFirstResponder]) {
        _m_helperView.y = self.view.height - CGRectGetHeight(keyboardBounds) - 75;
    }
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    _m_helperView.y = self.view.height - _m_helperView.height;
    
    // commit animations
    [UIView commitAnimations];
}

@end
