//
//  SDTimeLineCellCommentView.m
//  GSD_WeiXin(wechat)
//
//  Created by gsd on 16/2/25.
//  Copyright © 2016年 GSD. All rights reserved.
//

/*
 
 *********************************************************************************
 *
 * GSD_WeiXin
 *
 * QQ交流群: 459274049
 * Email : gsdios@126.com
 * GitHub: https://github.com/gsdios/GSD_WeiXin
 * 新浪微博:GSD_iOS
 *
 * 此“高仿微信”用到了很高效方便的自动布局库SDAutoLayout（一行代码搞定自动布局）
 * SDAutoLayout地址：https://github.com/gsdios/SDAutoLayout
 * SDAutoLayout视频教程：http://www.letv.com/ptv/vplay/24038772.html
 * SDAutoLayout用法示例：https://github.com/gsdios/SDAutoLayout/blob/master/README.md
 *
 *********************************************************************************
 
 */

#import "SDTimeLineCellCommentView.h"
#import "UIView+SDAutoLayout.h"
#import "SDTimeLineCellModel.h"
#import "MLLinkLabel.h"

#import "LEETheme.h"
#import "SLFriensInfoVc.h"

@interface SDTimeLineCellCommentView () <MLLinkLabelDelegate>

@property (nonatomic, strong) NSArray *likeItemsArray;
@property (nonatomic, strong) NSArray *commentItemsArray;

@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic, strong) MLLinkLabel *likeLabel;
@property (nonatomic, strong) UIView *likeLableBottomLine;

@property (nonatomic, strong) NSMutableArray *commentLabelsArray;


@end

@implementation SDTimeLineCellCommentView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self setupViews];
    
        //设置主题
        [self configTheme];

    }
    return self;
}

- (void)setupViews
{
    _bgImageView = [UIImageView new];
    _bgImageView.backgroundColor = SLColor(@"#F5F8F7");
    _bgImageView.userInteractionEnabled = YES;
    [self addSubview:_bgImageView];
    
    _likeLabel = [MLLinkLabel new];
    _likeLabel.font = [UIFont systemFontOfSize:12];
    _likeLabel.linkTextAttributes = @{NSForegroundColorAttributeName : SLColor(@"#384962")};
    _likeLabel.isAttributedContent = YES;
    _likeLabel.backgroundColor = SLColor(@"#F5F8F7");
    [self addSubview:_likeLabel];
    
    _likeLableBottomLine = [UIView new];
    _likeLableBottomLine.backgroundColor = [UIColor whiteColor];
    [self addSubview:_likeLableBottomLine];
    
    _bgImageView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
}

- (void)configTheme{
    
    self.lee_theme
    .LeeAddBackgroundColor(DAY , SLColor(@"#F5F8F7"))
    .LeeAddBackgroundColor(NIGHT , [UIColor blackColor]);
    
    _bgImageView.lee_theme
    .LeeAddTintColor(DAY , SDColor(230, 230, 230, 1.0f))
    .LeeAddTintColor(NIGHT , SDColor(30, 30, 30, 1.0f));
    
    _likeLabel.lee_theme
    .LeeAddTextColor(DAY , SLColor(@"#384962"))
    .LeeAddTextColor(NIGHT , [UIColor grayColor]);
    
    _likeLableBottomLine.lee_theme
    .LeeAddBackgroundColor(DAY , SDColor(210, 210, 210, 1.0f))
    .LeeAddBackgroundColor(NIGHT , SDColor(60, 60, 60, 1.0f));
    
}

- (void)setCommentItemsArray:(NSArray *)commentItemsArray
{
    _commentItemsArray = commentItemsArray;
    long originalLabelsCount = self.commentLabelsArray.count;
    long needsToAddCount = commentItemsArray.count > originalLabelsCount ? (commentItemsArray.count - originalLabelsCount) : 0;
    for (int i = 0; i < needsToAddCount; i++) {
        MLLinkLabel *label = [MLLinkLabel new];
        UIColor *highLightColor = SLColor(@"#48484A");
        label.linkTextAttributes = @{NSForegroundColorAttributeName : highLightColor, NSFontAttributeName: [UIFont boldSystemFontOfSize:14]};
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = SLColor(@"#48484A");
        label.delegate = self;
        WS(weakSelf);
        label.labelLongTouchBlock = ^{
            NSLog(@"didLongTouchCommentLabelBlock--%d---------commentItemsArray",i);
            if (weakSelf.didLongTouchCommentLabelBlock) {
                weakSelf.didLongTouchCommentLabelBlock(@"123", CGRectZero, [NSIndexPath indexPathForRow:self.indexPath.row inSection:i]);
            }
        };
        label.labelClickedBlock = ^{
            NSLog(@"%d---------commentItemsArray",i);
            if (weakSelf.didClickCommentLabelBlock) {
                weakSelf.didClickCommentLabelBlock(@"123", CGRectZero, [NSIndexPath indexPathForRow:self.indexPath.row inSection:i]);
            }
        };
        [self addSubview:label];
        [self.commentLabelsArray addObject:label];
    }
    
    for (int i = 0; i < commentItemsArray.count; i++) {
        SDTimeLineCellCommentItemModel *model = commentItemsArray[i];
        MLLinkLabel *label = self.commentLabelsArray[i];
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithCommentItemModel:model];
        }
        label.attributedText = model.attributedContent;
    }
}

- (void)setLikeItemsArray:(NSArray *)likeItemsArray
{
    
    _likeItemsArray = likeItemsArray;
    NSTextAttachment *attach = [NSTextAttachment new];
    attach.image = [UIImage imageNamed:@"icon_heart"];
    attach.bounds = CGRectMake(0, -3, 16, 16);
    NSAttributedString *likeIcon = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:likeIcon];
    
    for (int i = 0; i < likeItemsArray.count; i++) {
        SDTimeLineCellLikeItemModel *model = likeItemsArray[i];
        if (i == 0) {
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"  "]];
        }
        if (i > 0) {
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"，"]];
        }
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithLikeItemModel:model];
        }
        [attributedText appendAttributedString:model.attributedContent];
    }
    
    _likeLabel.attributedText = [attributedText copy];
    _likeLabel.userInteractionEnabled = YES;
    [_likeLabel addTapWithBlock:^{
        NSLog(@"------_likeLabel Tap");
    }];
}

- (NSMutableArray *)commentLabelsArray
{
    if (!_commentLabelsArray) {
        _commentLabelsArray = [NSMutableArray new];
    }
    return _commentLabelsArray;
}

- (void)setupWithLikeItemsArray:(NSArray *)likeItemsArray commentItemsArray:(NSArray *)commentItemsArray
{
    
    self.likeItemsArray = likeItemsArray;
    self.commentItemsArray = commentItemsArray;
    
    if (self.commentLabelsArray.count) {
        [self.commentLabelsArray enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL *stop) {
            [label sd_clearAutoLayoutSettings];
            label.hidden = YES; //重用时先隐藏所以评论label，然后根据评论个数显示label
        }];
    }
    
    if (!commentItemsArray.count && !likeItemsArray.count) {
        self.fixedWidth = @(0); // 如果没有评论或者点赞，设置commentview的固定宽度为0（设置了fixedWith的控件将不再在自动布局过程中调整宽度）
        self.fixedHeight = @(0); // 如果没有评论或者点赞，设置commentview的固定高度为0（设置了fixedHeight的控件将不再在自动布局过程中调整高度）
        return;
    } else {
        self.fixedHeight = nil; // 取消固定宽度约束
        self.fixedWidth = nil; // 取消固定高度约束
    }
    
    CGFloat margin = 0;
    
    UIView *lastTopView = nil;
    
    if (likeItemsArray.count) {
        _likeLabel.sd_resetLayout
        .leftSpaceToView(self, margin)
        .rightSpaceToView(self, margin)
        .topSpaceToView(lastTopView, 3)
        .autoHeightRatio(0);
        
        lastTopView = _likeLabel;
    } else {
        _likeLabel.attributedText = nil;
        _likeLabel.sd_resetLayout
        .heightIs(0);
    }
    
    
    if (self.commentItemsArray.count && self.likeItemsArray.count) {
        _likeLableBottomLine.sd_resetLayout
        .leftSpaceToView(self, 0)
        .rightSpaceToView(self, 0)
        .heightIs(5)
        .topSpaceToView(_likeLabel, 3);
        
        lastTopView = _likeLableBottomLine;
    } else {
        _likeLableBottomLine.sd_resetLayout.heightIs(0);
    }
    
    for (int i = 0; i < self.commentItemsArray.count; i++) {
        UILabel *label = (UILabel *)self.commentLabelsArray[i];
        label.hidden = NO;
        CGFloat topMargin = (i == 0 && likeItemsArray.count == 0) ? 10 : 5;
        label.sd_layout
        .leftSpaceToView(self, 8)
        .rightSpaceToView(self, 5)
        .topSpaceToView(lastTopView, topMargin)
        .autoHeightRatio(0);
        
        label.isAttributedContent = YES;
        lastTopView = label;
    }
    
    [self setupAutoHeightWithBottomView:lastTopView bottomMargin:6];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    // 1.这是当前点击的视图，如果没有找到合适的响应操作的视图，则直接返回这个
    UIView *hitView = [super hitTest:point withEvent:event];
//    NSLog(@"---%@",hitView);
    if(hitView == self){
        return nil;
    }
    return hitView;
}


- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

#pragma mark - private actions

- (NSMutableAttributedString *)generateAttributedStringWithCommentItemModel:(SDTimeLineCellCommentItemModel *)model
{
    NSString *text = model.userName;
    if (model.replyUserName.length) {
        text = [text stringByAppendingString:[NSString stringWithFormat:@" 回复 %@", model.replyUserName]];
    }
    text = [text stringByAppendingString:[NSString stringWithFormat:@"：%@", model.content]];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    [attString setAttributes:@{NSLinkAttributeName : model.userId} range:[text rangeOfString:model.userName]];
    if (model.replyUserName) {
        [attString setAttributes:@{NSLinkAttributeName : model.friendId} range:[text rangeOfString:[@" " stringByAppendingFormat:@"%@", model.replyUserName]]];
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 4.0f;
    [attString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
//    [attString setAttributes:@{NSLinkAttributeName : model.content, NSForegroundColorAttributeName : SLColor(@"#384962"), NSFontAttributeName : [UIFont systemFontOfSize:12]} range:[text rangeOfString:model.content]];
    return attString;
}

- (NSMutableAttributedString *)generateAttributedStringWithLikeItemModel:(SDTimeLineCellLikeItemModel *)model
{
    NSString *text = model.userName;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    UIColor *highLightColor = SLColor(@"#384962");
    [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : model.userId} range:[text rangeOfString:model.userName]];
    
    return attString;
}

#pragma mark - MLLinkLabelDelegate

- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText linkLabel:(MLLinkLabel *)linkLabel
{
    NSLog(@"%@--%@", link.linkValue,linkText);
    if (link.linkValue.length) {
        [[SLHttpCenter SharedInstance] getWithUrl:@"/api/User/GetUserInfo" parameter:@{@"userId":link.linkValue} success:^(id responseObject) {
            SLFriendsModel *model = [SLFriendsModel mj_objectWithKeyValues:[responseObject objectForKey:@"data"]];
            SLFriensInfoVc *vc = [SLFriensInfoVc loadViewControllewWithNib];
            vc.friendModel = model;
            [self.viewController navPushViewController:vc animated:YES];
        } failure:^(SPRequestError *error) {
            
        }];
    }
}

@end
