//
//  ICRTaskProcessViewController.m
//  XFFruit
//
//  Created by Xummer on 4/12/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRTaskProcessViewController.h"
#import "ICRPlaceholderTextView.h"
#import "ICRAttachmentView.h"
#import "ICRAttachmentUnit.h"
#import "IBTImagePicker.h"
#import "ICRTask.h"
#import "ICRPostAttachment.h"

#import "ICRTaskDetailViewController.h"
#import "ICRTaskResultViewController.h"

#define LABEL_LEFT_PANDING    (20)
#define SUBMIT_BUTTON_HEIGHT  (44)
#define GRAY_LINE_WIDTH       (0.5)
#define TEXTVIEW_TOP_PANDING  (10)
#define TEXTVIEW_HEIGHT       (120)

@interface ICRTaskProcessViewController ()
<
    IBTImagePickerDelegate
>
@property (strong, nonatomic) IBTUIScrollView *m_scrollView;
@property (strong, nonatomic) ICRPlaceholderTextView *m_textView;
@property (strong, nonatomic) ICRAttachmentView *m_photoView;
@property (strong, nonatomic) UIButton *m_submitButton;

@property (strong, nonatomic) IBTImagePicker *m_imagePicker;

@property (strong, nonatomic) ICRTask *m_task;
@end

@implementation ICRTaskProcessViewController

#pragma mark - Life Cycle
- (instancetype)initWithTaskData:(id)task {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([task isKindOfClass:[ICRTask class]]) {
        self.m_task = task;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = [IBTCommon localizableString:@"HandleTask"];
    
    [self setupSubviews];
}

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

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - Private Method
- (void)setupSubviews {
    
    self.m_scrollView = [[IBTUIScrollView alloc] initWithFrame:self.view.bounds];
    [_m_scrollView autoresizingWithStrechFullSize];
    [self.view addSubview:_m_scrollView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){
        .origin.x = LABEL_LEFT_PANDING,
        .origin.y = LABEL_LEFT_PANDING,
        .size.width = _m_scrollView.width - LABEL_LEFT_PANDING * 2,
        .size.height = SUBMIT_BUTTON_HEIGHT
    }];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:16.0f];
    label.textColor = [UIColor colorWithW:109 a:1];
    label.textAlignment = NSTextAlignmentLeft;
    label.text = [IBTCommon localizableString:@"Process Result Info:"];
    [_m_scrollView addSubview:label];
    
    CGFloat fDx = LABEL_LEFT_PANDING - 4;
    UIView *contentView = [[UIView alloc] initWithFrame:(CGRect){
        .origin.x = fDx,
        .origin.y = label.bottom + TEXTVIEW_TOP_PANDING,
        .size.width = _m_scrollView.width - fDx * 2,
        .size.height = TEXTVIEW_HEIGHT
    }];
    contentView.layer.masksToBounds = YES;
    contentView.layer.cornerRadius = 5;
    contentView.backgroundColor = [UIColor lightGrayColor];
    
    self.m_textView = [[ICRPlaceholderTextView alloc] initWithFrame:(CGRect){
        .origin.x = GRAY_LINE_WIDTH,
        .origin.y = GRAY_LINE_WIDTH,
        .size.width = contentView.width - GRAY_LINE_WIDTH * 2,
        .size.height = contentView.height - GRAY_LINE_WIDTH * 2
    }];
    _m_textView.layer.masksToBounds = YES;
    _m_textView.layer.cornerRadius = 5;
    _m_textView.font = [UIFont systemFontOfSize:16.0f];
    _m_textView.m_placeHolder = nil;
    _m_textView.m_placeholderColor = [UIColor colorWithW:109 a:1];
    
    [contentView addSubview:_m_textView];
    [_m_scrollView addSubview:contentView];
    
    self.m_photoView = [[ICRAttachmentView alloc] initWithType:kAttViewImage];
    _m_photoView.frame = (CGRect){
        .origin.x = label.left,
        .origin.y = contentView.bottom + 5,
        .size.width = label.width,
        .size.height = 80
    };
    _m_photoView.m_uiMaxAttCount = 1;
    [_m_photoView.m_addButton addTarget:self
                                 action:@selector(onShowImagePicker:)
                       forControlEvents:UIControlEventTouchUpInside];
    [_m_scrollView addSubview:_m_photoView];
    
    self.m_submitButton =
    [IBTCustomButtom buttonWithTitle:[IBTCommon localizableString:@"Save and Submit"]
                               color:ICR_ORANGE_BTN_COLOR
                              target:self action:@selector(onSaveAndSubmit:)];
    _m_submitButton.frame = (CGRect){
        .origin.x = label.left,
        .origin.y = _m_photoView.bottom + 10,
        .size.width = _m_scrollView.width - LABEL_LEFT_PANDING * 2,
        .size.height = SUBMIT_BUTTON_HEIGHT
    };
    
    [_m_scrollView addSubview:_m_submitButton];
    
    self.m_scrollView.contentSize = CGSizeMake(_m_scrollView.width, _m_submitButton.bottom + 20);
}

- (IBTImagePicker *)imagePicker {
    if (!_m_imagePicker) {
        self.m_imagePicker = [[IBTImagePicker alloc] init];
    }
    
    return _m_imagePicker;
}

- (void)checkSubmitButton {
    
}

#pragma mark - Actions
- (void)onSaveAndSubmit:(__unused id)sender {

    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];

    NSString *taskID = _m_task.uuid;
    NSString *result = _m_textView.text;
    
    
    void (^afterUpload)(void) = ^(void) {
        void(^succ)(id) = ^(id data) {
            CLog(@"update succ");
            __weak typeof(self)weakSelf = self;
            void(^complete)(void) = ^(void) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                ICRTaskResultViewController *dVC =
                [[ICRTaskResultViewController alloc] initWithTaskData:strongSelf.m_task];
                NSArray *arrVC = strongSelf.navigationController.viewControllers;
                [strongSelf PopToRootViewControllerAnimated:NO];
                UIViewController *vc = [arrVC firstObject];
                [vc PushViewController:dVC animated:YES];
            };
            
            _m_task.state = TaskState[ kICRTaskLocalFinished ];
            _m_task.processResult = result;
            [_m_task saveToDBWithHandleData:NULL
                                   complete:complete
                                       fail:^(NSError * error) {
                                           [IBTLoadingView showTips:error];
                                       }];
        };
        
        void(^fail)(id) = ^(id data) {
            // TODO Save it to local
            [IBTLoadingView showTips:data];

            _m_task.state =TaskState [kICRTaskLocalFinished];
            
            [_m_task saveToDBWithHandleData:NULL
                                   complete:NULL
                                       fail:^(NSError * error) {
                                           [IBTLoadingView showTips:error];
                                       }];
        };
        
        [httpCtrl doUpdateTaskResultID:taskID
                            resultText:result
                           processDate:[[NSDate date] timeIntervalSince1970]
                               success:succ failure:fail];
    };
    
    NSArray *arrAttach =
    [_m_photoView.m_arrAttViews valueForKeyPath:@"m_oAttachmentWrap"];
    NSUInteger uiAttCount = [arrAttach count];
    if (uiAttCount > 0) {
        __block NSUInteger uiSucCount = 0;
        void(^suc)(id) = ^(id data) {
            uiSucCount ++;
            
            if (uiSucCount == uiAttCount) {
                afterUpload();
            }
        };
        
        void(^fai)(id) = ^(id data) {
            [IBTLoadingView showTips:@"上传失败"];
        };
        
        for (UIImage *img in arrAttach) {
            
            IBTFileData *imgFile = [IBTCommon saveImageToLocal:img];
            
            ICRPostAttachment *attE = [[ICRPostAttachment alloc] init];
////            attE.type = @"task";
//            attE.objectId = taskID;
//            attE.filename = imgFile.fileName;
//            attE.content = [imgFile.fileData base64EncodedString];
//            attE.seq = @(1);
//            attE.attachmentType = @"ask";
            
            [httpCtrl doAddAttachment:[attE dictForCommit]
                              success:suc
                              failure:fai];
        }
        
        
    }
    else {
        afterUpload();
    }
}

- (void)onShowImagePicker:(__unused id)sender {
    [[self imagePicker] showImagePickerTitle:nil
                                   mediaType:kIBTMediaBImage
                                    editable:NO
                          fromViewController:self];
}

#pragma mark - IBTImagePickerDelegate
- (void)imagePicker:(IBTImagePickerController *)picker
     didImagePicked:(UIImage *)image referenceURL:(NSURL *)imageUrl {
    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:image title:nil];
    attV.m_oAttachmentWrap = image;
    [self.m_photoView addContentAttachmentView:attV];
}

- (void)imagePicker:(IBTImagePickerController *)picker
didVideoPickedWithURL:(NSURL *)videoUrl {
    
}

#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
    [_m_scrollView setContentInsetTop:_m_scrollView.contentInset.top
                            andBottom:CGRectGetHeight(keyboardBounds)];
    
    // 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_scrollView setContentInsetTop:_m_scrollView.contentInset.top
                            andBottom:0];
    
    // commit animations
    [UIView commitAnimations];
}


@end
