//
//  SDTimeLineCell.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 "SDTimeLineCell.h"

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

#import "SDTimeLineCellCommentView.h"

#import "SDWeiXinPhotoContainerView.h"

#import "SDTimeLineCellOperationMenu.h"

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

const CGFloat contentLabelFontSize = 16;
CGFloat maxContentLabelHeight = 0; // 根据具体font而定

NSString *const kSDTimeLineCellOperationButtonClickedNotification = @"SDTimeLineCellOperationButtonClickedNotification";


@interface SDTimeLineCell()

@property (nonatomic, strong)UIButton *operationLikeButton;

@end

@implementation SDTimeLineCell

{
    UIImageView *_iconView;
    UILabel *_nameLable;
    UILabel *_contentLabel;
    SDWeiXinPhotoContainerView *_picContainerView;
    UILabel *_timeLabel;
    UIButton *_moreButton;
    UIButton *_operationCommentButton;
    UIButton *_delButton;
    SDTimeLineCellCommentView *_commentView;
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        [self setup];
        
        //设置主题
        [self configTheme];
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

- (void)setup
{
        
    _iconView = [UIImageView new];
    _iconView.clipsToBounds = YES;
    _iconView.contentMode = UIViewContentModeScaleAspectFill;
    
    _nameLable = [UILabel new];
    _nameLable.font = [UIFont boldSystemFontOfSize:18];
    _nameLable.textColor = SLColor(@"#080F1B");
    _nameLable.userInteractionEnabled = YES;
    WS(weakSelf);
    [_nameLable addTapWithBlock:^{
        SLFriensInfoVc *vc = [[SLFriensInfoVc alloc] init];
        SLFriendsModel *model = [[SLFriendsModel alloc] init];
        model.userId = weakSelf.model.userId;
        model.userName = weakSelf.model.userName;
        model.userHead = weakSelf.model.userImg;
        vc.friendModel = model;
        [weakSelf.viewController navPushViewController:vc animated:YES];
    }];
    
    _contentLabel = [UILabel new];
    _contentLabel.font = [UIFont systemFontOfSize:contentLabelFontSize];
    _contentLabel.numberOfLines = 0;
    _nameLable.isAttributedContent = YES;
    if (maxContentLabelHeight == 0) {
        maxContentLabelHeight = (_contentLabel.font.lineHeight + 8) * 3;
    }
    
    _moreButton = [UIButton new];
    [_moreButton setTitle:@"全文" forState:UIControlStateNormal];
    [_moreButton setTitleColor:TimeLineCellHighlightedColor forState:UIControlStateNormal];
    [_moreButton addTarget:self action:@selector(moreButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _moreButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    _operationLikeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_operationLikeButton setTitle:@"点赞" forState:UIControlStateNormal];
    _operationLikeButton.titleLabel.font = [UIFont systemFontOfSize:10];
    [_operationLikeButton setTitleColor:SLColor(@"#8E8E93") forState:UIControlStateNormal];
    [_operationLikeButton setImage:[UIImage imageNamed:@"icon_heart"] forState:UIControlStateNormal];
    [_operationLikeButton setImage:[UIImage imageNamed:@"icon_heart_sel"] forState:UIControlStateSelected];
    [_operationLikeButton handleEvent:UIControlEventTouchUpInside withBlock:^{
        weakSelf.operationLikeButton.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.operationLikeButton.userInteractionEnabled = YES;
        });
        if ([weakSelf.delegate respondsToSelector:@selector(didClickLikeButtonInCell:)]) {
            [weakSelf.delegate didClickLikeButtonInCell:weakSelf];
        }
    }];

    _operationCommentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_operationCommentButton setTitle:@"评论" forState:UIControlStateNormal];
    _operationCommentButton.titleLabel.font = [UIFont systemFontOfSize:10];
    [_operationCommentButton setTitleColor:SLColor(@"#8E8E93") forState:UIControlStateNormal];
    [_operationCommentButton setImage:[UIImage imageNamed:@"icon_moents_chat"] forState:UIControlStateNormal];
    [_operationCommentButton handleEvent:UIControlEventTouchUpInside withBlock:^{
        if ([weakSelf.delegate respondsToSelector:@selector(didClickcCommentButtonInCell:)]) {
            [weakSelf.delegate didClickcCommentButtonInCell:weakSelf];
        }
    }];
    
    _delButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _delButton.hidden = YES;
    [_delButton setImage:[UIImage imageNamed:@"icon_del_b"] forState:UIControlStateNormal];
    [_delButton handleEvent:UIControlEventTouchUpInside withBlock:^{
        if ([weakSelf.delegate respondsToSelector:@selector(didClickDelButtonInCell:)]) {
            [weakSelf.delegate didClickDelButtonInCell:weakSelf];
        }
    }];

    
    _picContainerView = [SDWeiXinPhotoContainerView new];
    
    _commentView = [SDTimeLineCellCommentView new];
    
    _timeLabel = [UILabel new];
    _timeLabel.textColor = SLColor(@"#8E8E93");
    _timeLabel.font = [UIFont systemFontOfSize:10];
    

    NSArray *views = @[_iconView, _nameLable, _contentLabel, _moreButton, _picContainerView, _timeLabel, _operationLikeButton, _operationCommentButton, _delButton, _commentView];
    
    [self.contentView sd_addSubviews:views];
    
    UIView *contentView = self.contentView;
    
    _iconView.sd_layout
    .leftSpaceToView(contentView, 14)
    .topSpaceToView(contentView, 8)
    .widthIs(42)
    .heightIs(42);
    _iconView.layer.cornerRadius = 21.0f;
    
    _nameLable.sd_layout
    .leftSpaceToView(_iconView, 12)
    .topEqualToView(_iconView)
    .heightIs(24);
    [_nameLable setSingleLineAutoResizeWithMaxWidth:200];
    
    _contentLabel.sd_layout
    .leftEqualToView(_nameLable)
    .topSpaceToView(_nameLable, 3)
    .rightSpaceToView(contentView, 12)
    .autoHeightRatio(0);
    
    // morebutton的高度在setmodel里面设置
    _moreButton.sd_layout
    .leftEqualToView(_contentLabel)
    .topSpaceToView(_contentLabel, 0)
    .widthIs(30);
    
    
    _picContainerView.sd_layout
    .leftEqualToView(_contentLabel); // 已经在内部实现宽度和高度自适应所以不需要再设置宽度高度，top值是具体有无图片在setModel方法中设置
    
    _timeLabel.sd_layout
    .leftEqualToView(_contentLabel)
    .topSpaceToView(_picContainerView, 8)
    .heightIs(16);
    [_timeLabel setSingleLineAutoResizeWithMaxWidth:200];
    
    _delButton.sd_layout
    .leftSpaceToView(_timeLabel, 8)
    .centerYEqualToView(_timeLabel)
    .heightIs(16)
    .widthIs(16);
    
    _operationLikeButton.sd_layout
    .rightSpaceToView(contentView, 14)
    .centerYEqualToView(_timeLabel)
    .heightIs(16)
    .widthIs(40);
    
    _operationCommentButton.sd_layout
    .rightSpaceToView(_operationLikeButton, 8)
    .centerYEqualToView(_timeLabel)
    .heightIs(16)
    .widthIs(40);
    
    _commentView.sd_layout
    .leftEqualToView(_contentLabel)
    .rightSpaceToView(self.contentView, 14)
    .topSpaceToView(_timeLabel, 4); // 已经在内部实现高度自适应所以不需要再设置高度
}

- (void)configTheme{
    self.lee_theme
    .LeeAddBackgroundColor(DAY , [UIColor whiteColor])
    .LeeAddBackgroundColor(NIGHT , [UIColor blackColor]);
    
    _contentLabel.lee_theme
    .LeeAddTextColor(DAY , [UIColor blackColor])
    .LeeAddTextColor(NIGHT , [UIColor grayColor]);

    _timeLabel.lee_theme
    .LeeAddTextColor(DAY , SLColor(@"#8E8E93"))
    .LeeAddTextColor(NIGHT , SLColor(@"#8E8E93"));
}

-  (void)setDidClickCommentLabelBlock:(void (^)(NSString *, CGRect, NSIndexPath *))didClickCommentLabelBlock {
    _didClickCommentLabelBlock = didClickCommentLabelBlock;
    _commentView.didClickCommentLabelBlock = _didClickCommentLabelBlock;
}

- (void)setDidLongTouchCommentLabelBlock:(void (^)(NSString *, CGRect, NSIndexPath *))didLongTouchCommentLabelBlock {
    _didLongTouchCommentLabelBlock = didLongTouchCommentLabelBlock;
    _commentView.didLongTouchCommentLabelBlock = _didLongTouchCommentLabelBlock;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setModel:(SDTimeLineCellModel *)model
{
    _model = model;
    [_commentView setupWithLikeItemsArray:model.likeItemsArray commentItemsArray:model.list];
    NSString *userImg = [NSString stringWithFormat:@"%@%@",[SLHttpCenter SharedInstance].serverUrl, model.userImg];
    [_iconView sd_setImageWithURL:[NSURL URLWithString:userImg] placeholderImage:ImageName(@"icon_ellipse")];
    _nameLable.text = model.userName;
    _contentLabel.isAttributedContent = YES;
    _contentLabel.attributedText = model.attributedFriendContent;
    NSString *userOwnId = [SLGlobalInfo SharedInstance].loginInfo.user.userId;
    _delButton.hidden = ![model.userId isEqualToString:userOwnId];
//    _contentLabel.attributedText = [self generateAttributedStringWithFriendContent:model.friendContent];
    NSArray *friendImgUrls = [model.friendImgUrl componentsSeparatedByString:@","];
    _picContainerView.cellModel = _model;
    _picContainerView.picPathStringsArray = friendImgUrls;
    
    if (model.shouldShowMoreButton) { // 如果文字高度超过60
        _moreButton.sd_layout.heightIs(20);
        _moreButton.hidden = NO;
        if (model.isOpening) { // 如果需要展开
            _contentLabel.sd_layout.maxHeightIs(MAXFLOAT);
            [_moreButton setTitle:@"收起" forState:UIControlStateNormal];
        } else {
            _contentLabel.sd_layout.maxHeightIs(maxContentLabelHeight);
            [_moreButton setTitle:@"全文" forState:UIControlStateNormal];
        }
    } else {
        _moreButton.sd_layout.heightIs(0);
        _moreButton.hidden = YES;
    }
    
    CGFloat picContainerTopMargin = 0;
    if (friendImgUrls.count) {
        picContainerTopMargin = 10;
    }
    _picContainerView.sd_layout.topSpaceToView(_moreButton, picContainerTopMargin);
    
    UIView *bottomView;
    
    if (!model.list.count && !model.likeItemsArray.count) {
        bottomView = _timeLabel;
    } else {
        bottomView = _commentView;
    }
    
    [self setupAutoHeightWithBottomView:bottomView bottomMargin:15];
    
    _timeLabel.text = model.time;
    _operationLikeButton.selected = _model.isLike;
    _commentView.indexPath = self.indexPath;
}

- (NSMutableAttributedString *)generateAttributedStringWithFriendContent:(NSString *)friendContent
{
    NSString *text = friendContent;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 4.0f;
    [attString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    return attString;
}

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

#pragma mark - private actions

- (void)moreButtonClicked
{
    if (self.moreButtonClickedBlock) {
        self.moreButtonClickedBlock(self.indexPath);
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
//    [self postOperationButtonClickedNotification];
}

@end

