//
//  ALTopicCommentListController.m
//  GMAlpha
//
//  Created by Mikasa on 2018/11/7.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALTopicCommentListController.h"
#import "ALTopicCommentTableView.h"
#import "ALTopicReplyCell.h"
#import "ALTopicCommentCell.h"
#import "WMPostInputView.h"
#import <GMRefresh/GMRefreshFooter.h>

@interface ALTopicCommentListController ()<WMPostInputViewDelegate>
@property (nonatomic, strong) WMPostInputView *postInputView;
@property (nonatomic, strong) GMLabel *titleLabel;
@property (nonatomic, strong) GMView *endView;
@end

@implementation ALTopicCommentListController

#pragma mark - lazy loading
- (GMView *)endView {
    if (!_endView) {
        // 底部结束end line
        GMView *endView = [[GMView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, 20)];
        GMImageView *endImageView = [[GMImageView alloc]
                                     initWithFrame:CGRectMake((MAINSCREEN_WIDTH - 85)/2, 5, 85, 10)];
        endImageView.image = [UIImage imageNamed:@"topic_comment_end_icon"];
        [endView addSubview:endImageView];
        _endView = endView;
    }
    return _endView;
}

- (void)initController{
    
    [super initController];
    self.viewModel = [[ALTopicCommentListViewModel alloc] init];
    _needHeaderRefresh = NO;
    self.immediateLoad = NO;
    self.pageName = @"";
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self hideNavigationBar];
    [self setupSubView];
}

- (void)setupSubView {
    
    GMView *topBackView = [GMView new];
    topBackView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topBackView];
    
    [topBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(48);
    }];
    UIView *line = [topBackView addBottomLine];
    line.backgroundColor = RGBCOLOR_HEX(0xE5E5E5);
    [line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];
    
    /** 关闭按钮
    GMButton *closeButton = [GMButton new];
    [closeButton setImage:[UIImage imageNamed:@"answer_close"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeButton];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.right.mas_equalTo(-5);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];*/
    
    /** 标题 */
    GMLabel *titleLabel = [GMLabel labelWithTextColor:UIColor.headlineText fontSize:16];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"全部评论";
    [topBackView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(0);
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    self.titleLabel = titleLabel;
 
    WMUser *user = [GMLoginManager shareInstance].user;
    // 底部输入框
    WMPostInputView *postInputView = [WMPostInputView new];
    postInputView.placeHolder = @"添加评论";
    postInputView.delegate = self;
    postInputView.backgroundColor = RGBCOLOR_HEX(0xffffff);
    postInputView.layer.shadowOffset = CGSizeMake(0, -1);
    postInputView.layer.shadowRadius = 6.0f;
    postInputView.layer.shadowOpacity = 0.1;
    postInputView.layer.shadowColor = RGBCOLOR_HEX(0x000000).CGColor;
    [postInputView.iconImgeView sd_setImageWithURL:[NSURL URLWithString:user.portrait] placeholderImage:[UIImage imageNamed:@"user_setter_default_icon_new"]];
    [self.view addSubview:postInputView];
    self.postInputView = postInputView;
    
    [_postInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
        make.right.left.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    [_table mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topBackView.mas_bottom).mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-(UIView.safeAreaInsetsBottom + 50));
    }];
    
    _table.tableFooterView = nil;
    
    [_table registerCell:[ALTopicReplyCell class]];
    [_table registerCell:[ALTopicCommentCell class]];
}

- (void)updateOtherUIData {
    [super updateOtherUIData];
    
    if (self.viewModel.commentTotal > 0) {
        self.titleLabel.text = [NSString stringWithFormat:@"全部%zd条评论",self.viewModel.commentTotal];
    } else {
        self.titleLabel.text = @"全部评论";
    }
    
    if (self.emptyView.type == GMEmptyViewTypeEmpty) {
        [self.view bringSubviewToFront:self.postInputView];
    } else {
        [self.view bringSubviewToFront:self.emptyView];
    }
    
    if (self.viewModel.page == 1) {
        _table.tableFooterView = nil;
        // 回复评论直接调起键盘
        if (self.commentHandle == WMCommentHandleReply) {
            
            [self.postInputView show];
            
            // 之后的操作都是不弹出键盘
            self.commentHandle = WMCommentHandleLook;
        } else {
            [self.postInputView hide];
        }
        // 回到顶部
        [self.table scrollsToTop];
    }
    // 如果获取到数据少于要请求的数量 直接去掉后续请求
    if (self.viewModel.dataArray.count < (self.viewModel.page * self.viewModel.count)) {
        _table.mj_footer.userInteractionEnabled = NO;
        _table.tableFooterView = self.endView;

    } else {
        _table.mj_footer.userInteractionEnabled = YES;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //返回行数
    ALTopicCommentObject *topicCommentObject = self.viewModel.dataArray[section];
    return topicCommentObject.comments.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ALTopicCommentObject *topicCommentObject = self.viewModel.dataArray[indexPath.section];
    // 用户评论内容
    if (indexPath.row == 0) {
        ALTopicCommentCell *cell = [tableView dequeueCell:[ALTopicCommentCell class]
                                             forIndexPath:indexPath];
        cell.isFirst = indexPath.section == 0;
        cell.commentObject = topicCommentObject;
        __weak __typeof(self)weakSelf = self;
        cell.tralateClickBlock = ^{
            // 评论列表点击翻译
            [Phobos track:@"comment_list_click_translate"
               attributes:@{@"from": SafeString(weakSelf.fromPage),
                            @"busniess_id":SafeString(weakSelf.viewModel.topicId)}];
        };
        cell.translateBlock = ^(ALTopicCommentObject *commentObject, BOOL comment, NSInteger replyIndex) {
            NSInteger section = [self.viewModel.dataArray indexOfObject:commentObject];
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:comment?0:(replyIndex+1) inSection:section];
            [tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:0];
        };
        return cell;
        
    } else { // 用户回复
        
        ALTopicCommentReplyObject *replyObject = topicCommentObject.comments[indexPath.row-1];
        ALTopicReplyCell *cell = [tableView dequeueCell:[ALTopicReplyCell class]
                                           forIndexPath:indexPath];
        cell.replyObject = replyObject;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ALTopicCommentObject *topicCommentObject = self.viewModel.dataArray[indexPath.section];
    
    if (indexPath.row == 0) {
        [self trackInputAreaAction:topicCommentObject.user
                        commentId:[NSString stringWithFormat:@"%@",topicCommentObject.id]];
        [self.postInputView show];
    } else {
         ALTopicCommentReplyObject *replyObject = topicCommentObject.comments[indexPath.row-1];
        [self trackInputAreaAction:replyObject.user
                        commentId:[NSString stringWithFormat:@"%@",replyObject.id]];
        [self.postInputView show];
    }
}

#pragma mark - inputView
- (void)hide {
    if (self.didClickCloseBlock) {
        self.didClickCloseBlock();
    }
}

- (void)trackInputAreaAction:(ALTopicCommentUserObject *)userObject commentId:(NSString *)commentId {
    
    if (userObject) {
        self.viewModel.replied_id = [NSString stringWithFormat:@"%@",commentId]?:@"";
        self.postInputView.placeHolder = [NSString stringWithFormat:@"回复:%@",userObject.name];
        
        [Phobos track:@"comment_list_click_reply" attributes:@{@"from": SafeString(self.fromPage),
                                                               @"busniess_id":SafeString(self.viewModel.topicId),
                                                               @"comment_id":SafeString(commentId)
                                                               }];
    } else {
        self.postInputView.placeHolder = @"添加评论";
        [Phobos track:@"comment_list_click_comment" attributes:@{@"from": SafeString(self.fromPage),
                                                                @"busniess_id":SafeString(self.viewModel.topicId)}];
    }
}

#pragma mark - WMPostInputViewDelegate

- (void)inputView:(WMPostInputView *)inputView sendText:(NSString *)text {
    
    if (text.length == 0) {
        [self toast:@"请输入内容"];
        return;
    }
    self.viewModel.content = text;
    [self.viewModel excuteReplyTopic:^(id responseObject) {

        [self toast:@"评论成功"];
        self.postInputView.placeHolder = @"添加评论";
        self.postInputView.text = @"";
        self.viewModel.content = @"";
        self.viewModel.replied_id = @"";
        
        // 刷新第一页
        self.viewModel.page = 1;
        [self loadRemoteData];
    } failBlock:^(NSString *message) {
        [self toast:message];
    }];
}

- (void)inputViewBeginEdit:(WMPostInputView *)inputView {
    
    if ([inputView.placeHolder isEqualToString:@"添加评论"]) {
        [self trackInputAreaAction:nil commentId:nil];
    }
}


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

@end
