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

#import "SDTimeLineCell.h"

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

#import "SDTimeLineCellCommentView.h"

#import "SDWeiXinPhotoContainerView.h"

#import "SDTimeLineCellOperationMenu.h"

#import "SLFriensInfoVc.h"
#import "SLMikeSegment.h"
#import "SLMomentsVc.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;
    UIView *_transSpaceLineView;
    UILabel *_contentTransLabel;
    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.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;
    _contentLabel.userInteractionEnabled = YES;
    _nameLable.isAttributedContent = YES;
    if (maxContentLabelHeight == 0) {
        maxContentLabelHeight = (_contentLabel.font.lineHeight + 8) * 3;
    }
    UILongPressGestureRecognizer *gesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(contentLabelHandleLongPressGestures:)];
    gesture.minimumPressDuration= 0.5f;
    [_contentLabel addGestureRecognizer:gesture];
    
    _contentTransLabel = [UILabel new];
    _contentTransLabel.font = [UIFont systemFontOfSize:contentLabelFontSize];
    _contentTransLabel.numberOfLines = 0;
    _contentTransLabel.userInteractionEnabled = YES;
    _contentTransLabel.isAttributedContent = YES;
    UILongPressGestureRecognizer *gesture1=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(contentLabelHandleLongPressGestures:)];
    gesture.minimumPressDuration= 0.5f;
    [_contentTransLabel addGestureRecognizer:gesture1];
    _transSpaceLineView = [UIView new];
    _transSpaceLineView.backgroundColor = SLColLine;
    _transSpaceLineView.hidden = YES;
    
    
    _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, _contentTransLabel, _transSpaceLineView, _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);
    
    _contentTransLabel.sd_layout
    .leftEqualToView(_contentLabel)
    .topSpaceToView(_moreButton, 2)
    .rightSpaceToView(contentView, 12)
    .autoHeightRatio(0);
    
    _transSpaceLineView.sd_layout
    .leftEqualToView(_contentLabel)
    .topSpaceToView(_moreButton, 8)
    .rightSpaceToView(contentView, 12)
    .heightIs(1);
    
//    _contentTransLabel.text = @"我没有\n是的";
    
    _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)contentLabelHandleLongPressGestures:(UILongPressGestureRecognizer *)paramSender {
    if (paramSender.state == UIGestureRecognizerStateBegan) {
        paramSender.view.backgroundColor = SLCol205;
    }
    if (paramSender.state == UIGestureRecognizerStateEnded) {
        [self showMsgSegmentWith:paramSender.view];
        paramSender.view.backgroundColor = [UIColor clearColor];
    }
}

- (void)showMsgSegmentWith:(UIView *)bgView {
    UIViewController *vc = self.viewController;
    if ([vc isKindOfClass:SLMomentsVc.class]) {
        CGRect rect = [self convertRect:bgView.frame toView:self.viewController.view];
        //加一个蒙层
        __block UIView *bView = [[UIView alloc] initWithFrame:vc.view.frame];
        bView.backgroundColor = [UIColor clearColor];
        __block UIView *blockBgView = bView;
        [bView addTapWithBlock:^{
            [blockBgView removeFromSuperview];
        }];
        [vc.view addSubview:bView];
        NSMutableArray *arr = [NSMutableArray new];
        
        [arr addObject:[SLMikeSegmentModel initWithSegTitle: @"复制" segImage:@"" mikeType:SLMsgCopy]];
        if (bgView == _contentLabel) {
            if (_model.showTrans) {
                [arr addObject:[SLMikeSegmentModel initWithSegTitle: @"原文" segImage:@"" mikeType:SLMikeInputTransHidden]];
            }else {
                [arr addObject:[SLMikeSegmentModel initWithSegTitle: @"翻译" segImage:@"" mikeType:SLMikeInputTrans]];
            }
        }
       
        CGFloat width = arr.count * 45 + 20;
        CGFloat x = bgView.frame.origin.x + MAX(0, (rect.size.width - width) / 2.0);
        x = MIN((kSCREEN_WIDTH - width) / 2.0 , x);
        SLMikeSegment *mikeSegment = [[SLMikeSegment alloc] initWithFrame:CGRectMake(x, rect.origin.y - 39, width, 30) titleArray:arr];
        WS(weakSelf);
        mikeSegment.mikeSegmentBlock = ^(SLMikeSegmentModel *model) {
            [bView removeFromSuperview];
            switch (model.mikeType) {
                case SLMsgCopy:
                {
                    NSString *str = (bgView == self->_contentLabel) ? self->_model.friendContent : self->_model.friendContentTrans;
                    [[UIPasteboard generalPasteboard] setString:str];
                }
                    break;
                case SLMikeInputTransHidden:
                {
                    self->_model.showTrans = NO;
                    [weakSelf.delegate didClickTransInCell:self];
                }
                    break;
                case SLMikeInputTrans:
                {
                    if (self->_model.friendContentTrans) {
                        self->_model.showTrans = YES;
                        [weakSelf.delegate didClickTransInCell:self];
                    }else {
                        //百度智能云
                        [[SLHttpCenter SharedInstance] getWithUrl:@"https://aip.baidubce.com/oauth/2.0/token" parameter:@{@"grant_type":@"client_credentials", @"client_id":@"0VhDeLqdcbLamGENfw4c24aq", @"client_secret": @"92qphFKyc0uXGktqFLtfdmqlojt9MsgG"} success:^(id responseObject) {
                            NSString *accessToken = [responseObject objectForKey:@"access_token"];
                            if (accessToken) {
                                NSString *bdUrl = [NSString stringWithFormat:@"https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=%@",accessToken];
                                NSDictionary *dict = @{@"q":self->_model.friendContent,
                                                       @"from":@"auto",
                                                       @"to":@"zh"};
                                [[SLHttpCenter SharedInstance] postWithUrl:bdUrl parameter:dict success:^(id responseObject) {
                                    NSDictionary *reslut = [responseObject objectForKey:@"result"];
                                    NSArray *arr = [reslut objectForKey:@"trans_result"];
                                    if (arr && arr.count) {
                                        NSDictionary *resultDict = arr.firstObject;
                                        NSString *dst = [resultDict objectForKey:@"dst"];
                                        self->_model.friendContentTrans = dst;
                                        self->_contentTransLabel.text = self->_model.friendContentTrans;
                                        self->_model.showTrans = YES;
                                        [weakSelf.delegate didClickTransInCell:self];
                                    }else {
                                        [ZFToast ShowWithMessage:@"翻译失败"];
                                    }
                                } failure:^(SPRequestError *error) {
                                    [ZFToast ShowWithMessage:@"翻译失败"];
                                }];
                            }else {
                                [ZFToast ShowWithMessage:@"翻译失败"];
                            }
                        } failure:^(SPRequestError *error) {
                            [ZFToast ShowWithMessage:@"翻译失败"];
                        }];
                    }
                }
                    break;
                default:
                    break;
            }
        };
        [bView addSubview:mikeSegment];
        UIImageView *imgView = [[UIImageView alloc] initWithImage:ImageName(@"icon_dsjx")];
        [bView addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(mikeSegment);
            make.top.equalTo(mikeSegment.mas_bottom).offset(0);
            make.width.mas_equalTo(16);
            make.height.mas_equalTo(8);
        }];
    }
}


-  (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.userId = _model.userId;
    _contentTransLabel.text = _model.showTrans ? _model.friendContentTrans : @"";
    _contentTransLabel.sd_layout
    .topSpaceToView(_moreButton, _model.showTrans ? 16 : 2);
    
    _transSpaceLineView.hidden = !_model.showTrans;
    [_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 && !model.showTrans) { // 如果文字高度超过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 {
        _contentLabel.sd_layout.maxHeightIs(MAXFLOAT);
        _moreButton.sd_layout.heightIs(0);
        _moreButton.hidden = YES;
    }
    
    CGFloat picContainerTopMargin = 0;
    if (friendImgUrls.count) {
        picContainerTopMargin = 10;
    }
    _picContainerView.sd_layout.topSpaceToView(_contentTransLabel, 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

