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

#import "ICRTaskDetailContentView.h"

#define TASK_CONTENT_LABEL_VERTICAL_MARGIN  (10.0f)
#define TASK_CONTENT_LABEL_HORIZON_MARGIN   (15.0f)
#define TASK_CONTENT_LABEL_INNER_GAP        (5.0f)

@interface ICRTaskDetailContentView ()
{
    BOOL m_bIsAttach;
}

@property (strong, nonatomic) IBTUILabel *m_titleLabel;
@property (strong, nonatomic) IBTUILabel *m_titleValueLabel;
@property (strong, nonatomic) IBTUILabel *m_storeLabel;
@property (strong, nonatomic) IBTUILabel *m_storeValueLabel;
@property (strong, nonatomic) IBTUILabel *m_contentLabel;
@property (strong, nonatomic) IBTUILabel *m_contentValueLabel;
@property (strong, nonatomic) IBTUILabel *m_deadlineLabel;
@property (strong, nonatomic) IBTUILabel *m_deadlineValueLabel;
@property (strong, nonatomic) IBTUILabel *m_createTimeLabel;
@property (strong, nonatomic) IBTUILabel *m_createTimeValueLabel;
@property (strong, nonatomic) IBTUILabel *m_creatorLabel;
@property (strong, nonatomic) IBTUILabel *m_creatorValueLabel;

@property (strong, nonatomic) UIImageView *m_attachImageView;

@end

@implementation ICRTaskDetailContentView

#pragma mark - Life Cycle
- (instancetype)initWithIsAttach:(BOOL)bIsAttach {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    m_bIsAttach = bIsAttach;
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    
    [self initSubviews];
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat fMaxW = self.width - 2 * TASK_CONTENT_LABEL_HORIZON_MARGIN;
    
    [_m_titleLabel sizeToFit];
    _m_titleLabel.origin = (CGPoint){
        .x = TASK_CONTENT_LABEL_HORIZON_MARGIN,
        .y = TASK_CONTENT_LABEL_VERTICAL_MARGIN
    };
    
    [self updateFrameWithBaseView:_m_titleLabel ForView:_m_titleValueLabel];
    
    [_m_storeLabel sizeToFit];
    _m_storeLabel.origin = (CGPoint){
        .x = _m_titleLabel.left,
        .y = _m_titleValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP
    };
    
    [self updateFrameWithBaseView:_m_storeLabel ForView:_m_storeValueLabel];

    [_m_contentLabel sizeToFit];
    _m_contentLabel.origin = (CGPoint){
        .x = _m_titleLabel.left,
        .y = _m_storeValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP
    };
    
    [self updateFrameWithBaseView:_m_contentLabel ForView:_m_contentValueLabel];
    
    [_m_deadlineLabel sizeToFit];
    _m_deadlineLabel.origin = (CGPoint){
        .x = _m_titleLabel.left,
        .y = _m_contentValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP
    };
    
    [self updateFrameWithBaseView:_m_deadlineLabel ForView:_m_deadlineValueLabel];
    
    [_m_createTimeLabel sizeToFit];
    _m_createTimeLabel.origin = (CGPoint){
        .x = _m_titleLabel.left,
        .y = _m_deadlineValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP
    };
    
    [self updateFrameWithBaseView:_m_createTimeLabel ForView:_m_createTimeValueLabel];
    
    [_m_creatorLabel sizeToFit];
    _m_creatorLabel.origin = (CGPoint){
        .x = _m_titleLabel.left,
        .y = _m_createTimeValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP
    };
    
    [self updateFrameWithBaseView:_m_creatorLabel ForView:_m_creatorValueLabel];
    
    CGFloat dy = _m_creatorValueLabel.bottom + TASK_CONTENT_LABEL_INNER_GAP;
    
    if (!_m_attachImageView.hidden) {
        
        UIImage *image = _m_attachImageView.image;
        CGFloat hWRatio =  image ? (image.size.height / image.size.width) : 1;
        
        _m_attachImageView.frame = (CGRect){
            .origin.x = _m_titleLabel.left,
            .origin.y = dy,
            .size.width = fMaxW,
            .size.height = fMaxW * hWRatio
        };
        
        dy = _m_attachImageView.bottom + TASK_CONTENT_LABEL_INNER_GAP;
    }
    
    if (!_m_startBtn.hidden) {
        CGFloat dx = TASK_CONTENT_LABEL_HORIZON_MARGIN;
        self.m_startBtn.frame = (CGRect){
            .origin.x = dx,
            .origin.y = dy + 20,
            .size.width = fMaxW,
            .size.height = IBT_GROUP_CELL_BUTTON_HEIGHT
        };
        
        dy = _m_startBtn.bottom + 20;
    }
    
    self.height = dy;
}

#pragma mark - Private Method
- (void)initSubviews {
    
    self.m_titleLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Task Title"]];
    [self addSubview:_m_titleLabel];
    
    self.m_storeLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Store"]];
    [self addSubview:_m_storeLabel];
    
    self.m_contentLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Task Content"]];
    [self addSubview:_m_contentLabel];
    
    self.m_deadlineLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Task Deadline"]];
    [self addSubview:_m_deadlineLabel];
    
    self.m_createTimeLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Create Date"]];
    [self addSubview:_m_createTimeLabel];
    
    self.m_creatorLabel =
    [[self class] titleLabelWithText:[IBTCommon localizableString:@"Creator"]];
    [self addSubview:_m_creatorLabel];
    
    self.m_titleValueLabel = [[self class] valueLabel];
    [self addSubview:_m_titleValueLabel];
    
    self.m_storeValueLabel = [[self class] valueLabel];
    [self addSubview:_m_storeValueLabel];
    
    self.m_contentValueLabel = [[self class] valueLabel];
    [self addSubview:_m_contentValueLabel];
    
    self.m_deadlineValueLabel = [[self class] valueLabel];
    [self addSubview:_m_deadlineValueLabel];
    
    self.m_createTimeValueLabel = [[self class] valueLabel];
    [self addSubview:_m_createTimeValueLabel];
    
    self.m_creatorValueLabel = [[self class] valueLabel];
    [self addSubview:_m_creatorValueLabel];
    
    self.m_attachImageView = [[UIImageView alloc] init];
    [self addSubview:_m_attachImageView];
    
    self.m_startBtn = [IBTCustomButtom buttonWithTitle:[IBTCommon localizableString:@"Start Process"] color:ICR_ORANGE_BTN_COLOR target:nil action:nil];
    [self addSubview:_m_startBtn];
}

+ (IBTUILabel *)titleLabelWithText:(NSString *)nsTitle {
    IBTUILabel *label = [[IBTUILabel alloc] init];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor grayColor];
    label.font = [UIFont systemFontOfSize:15.0f];
    label.text = nsTitle;
    return label;
}

+ (IBTUILabel *)valueLabel {
    IBTUILabel *label = [[IBTUILabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:17.0f];
    return label;
}

- (void)updateFrameWithBaseView:(UIView *)baseView ForView:(UIView *)view {
    CGFloat fX, fY;
    CGFloat fMaxX = self.width - TASK_CONTENT_LABEL_HORIZON_MARGIN;
    if (m_bIsAttach) {
        fX = baseView.right + TASK_CONTENT_LABEL_INNER_GAP;
        fY = baseView.top;
    }
    else {
        fX = baseView.left;
        fY = baseView.bottom + TASK_CONTENT_LABEL_INNER_GAP;
    }
    
    CGSize size = CGSizeMake(fMaxX - fX, MAXFLOAT);
    size = [view widthLimitedSizeThatFits:size];
    
    view.frame = (CGRect){
        .origin.x = fX,
        .origin.y = fY,
        .size.width = size.width,
        .size.height = MAX(size.height, baseView.height)
    };
}


@end

#import "ICRTask.h"
#import "ICRAttachment.h"
@implementation ICRTaskDetailContentView (Configure)

- (void)updateWithTask:(ICRTask *)task {
    self.m_titleValueLabel.text = task.title;
    self.m_storeValueLabel.text = task.storeCode;
    self.m_contentValueLabel.text = task.content;
    self.m_deadlineValueLabel.text = task.requireDate;

        
   

    self.m_createTimeValueLabel.text =task.createInfo[@"time"];
    self.m_creatorValueLabel.text =task.createInfo[@"operator"][@"operName"] ;
    
    if (task.processResult) {

        self.m_startBtn.hidden = YES;
    }
    else if ([task.state isEqualToString:TaskState[ kICRTaskLocalAlloted ]])
    {
        self.m_startBtn.hidden = NO;
    }
    else if (task.state.length > 0) {
        self.m_startBtn.hidden = YES;
    }
    else {
        
        if([task.state isEqualToString:TaskState[kICRTaskStatusAlloted]])
        {
             self.m_startBtn.hidden = NO;

        }
        else
        {
              self.m_startBtn.hidden = YES;
        }
          }
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? ORDER BY %@", [ICRAttachment TableName], @"objectId", @"seq"];
        return [db executeQuery:sql, task.uuid ];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        ICRAttachment *attach = [fetchedObjects firstObject];
        if ([attach.fileName extensionIsImageType]) {
            strongSelf.m_attachImageView.hidden = NO;
            NSString *imgeUrl = [ICRHTTPController AttachmentUrlWithID:@( attach.aID )];
            [strongSelf.m_attachImageView sd_setImageWithURL:[NSURL URLWithString:imgeUrl]
                                            placeholderImage:[UIImage imageWithColor:ICR_IMAGE_BG_COLOR]
                                                   completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                                [strongSelf layoutSubviews];
                                            }];
        }
        else {
            strongSelf.m_attachImageView.hidden = YES;
        }
        
        [strongSelf layoutSubviews];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAttachment class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
}

@end
