IVTMyChatContentListViewController.m 12.1 KB
//
//  IVTMyChatContentListViewController.m
//  IVTMeLiveTwo
//
//  Created by XRG on 16/8/28.
//  Copyright © 2016年 QLQ. All rights reserved.
//

#import "IVTMyChatContentListViewController.h"
#import "IVTMyChatContentListTableViewCell.h"
#import "IVTFriendChatContentListTableViewCell.h"
#import "DBManager.h"
#import "AppDelegate.h"
#import "IVTUserInfoCenterViewController.h"

#define kKeyboardToolHeight 45

static NSString *myCellIdentifier = @"myFriendListCellIdentifier";
static NSString *friendCellIdentifier = @"friendFriendListCellIdentifier";


@interface IVTMyChatContentListViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,XMPPManagerPrivateChatDelegate>
{
    NSMutableArray *chatContentArray;
    UITableView *chatContentTableView;
    UIView *keyboardToolView;
    UITextView *sendTextField;
}
@end

@implementation IVTMyChatContentListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [AppDelegate appDelegate].isChatting = YES;
    [[DBManager sharedInstance] updataChatMessageToReadedToUserId:self.chatToUserId];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [AppDelegate appDelegate].isChatting = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavigationBar];
    
    chatContentArray = [[NSMutableArray alloc]initWithCapacity:10];
    [XMPPManager sharedInstance].delegateForPrivateChat = self;
    
    __weak typeof(self) wself = self;

    //keyboard
    keyboardToolView = [[UIView alloc]init];
    keyboardToolView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:keyboardToolView];
    [keyboardToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wself.view.mas_left);
        make.right.equalTo(wself.view.mas_right);
        make.bottom.equalTo(wself.view.mas_bottom);
        make.height.mas_equalTo(kKeyboardToolHeight);
    }];
    
    UIImageView *line = [[UIImageView alloc]init];
    line.backgroundColor = UIColorFromRGBAlphaHex(0xdcdcdc, 1.0);
    line.alpha = 0.5;
    [keyboardToolView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(keyboardToolView.mas_left);
        make.right.equalTo(keyboardToolView.mas_right);
        make.top.equalTo(keyboardToolView.mas_top);
        make.height.mas_equalTo(0.5);
    }];
    
    UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sendButton setBackgroundImage:[UIImage imageNamed:@"私信发送按钮"] forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [keyboardToolView addSubview:sendButton];
    [sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(55, 30));
        make.top.equalTo(keyboardToolView.mas_top).with.offset((kKeyboardToolHeight - 30)/2);
        make.right.equalTo(keyboardToolView.mas_right).with.offset(-10);
    }];
    
    sendTextField = [[UITextView alloc]init];
    sendTextField.font = [UIFont systemFontOfSize:14];
    sendTextField.textColor = [UIColor blackColor];
    sendTextField.returnKeyType = UIReturnKeySend;
    sendTextField.layer.cornerRadius = 4;
    sendTextField.layer.borderWidth = 1;
    sendTextField.layer.borderColor = UIColorFromRGBAlphaHex(0xdcdcdc, 1.0).CGColor;
    sendTextField.layer.masksToBounds = YES;
    sendTextField.delegate = self;
    sendTextField.backgroundColor = [UIColor whiteColor];
    [keyboardToolView addSubview:sendTextField];
    [sendTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(keyboardToolView.mas_left).offset(5);
        make.top.equalTo(keyboardToolView.mas_top).offset(5);
        make.bottom.equalTo(keyboardToolView.mas_bottom).offset(-5);
        make.right.equalTo(sendButton.mas_left).offset(-10);
    }];
    
    //message
    chatContentTableView = [[UITableView alloc]init];
    chatContentTableView.delegate = self;
    chatContentTableView.dataSource = self;
    chatContentTableView.showsHorizontalScrollIndicator = NO;
    chatContentTableView.showsVerticalScrollIndicator = NO;
    chatContentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    chatContentTableView.scrollEnabled = YES;
    chatContentTableView.rowHeight = UITableViewAutomaticDimension;
    chatContentTableView.estimatedRowHeight = 50;
    [self.view addSubview:chatContentTableView];
    [chatContentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wself.view.mas_top);
        make.left.equalTo(wself.view.mas_left);
        make.right.equalTo(wself.view.mas_right);
        make.bottom.equalTo(keyboardToolView.mas_top);
    }];
    
    [chatContentTableView registerNib:[UINib nibWithNibName:@"IVTMyChatContentListTableViewCell" bundle:nil] forCellReuseIdentifier:myCellIdentifier];
    [chatContentTableView registerNib:[UINib nibWithNibName:@"IVTFriendChatContentListTableViewCell" bundle:nil] forCellReuseIdentifier:friendCellIdentifier];


    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap)];
    [chatContentTableView addGestureRecognizer:tap];
    
    
    RLMResults<ChatObject *> *list = [[DBManager sharedInstance] getAllChatMessageListToUserId:self.chatToUserId];
    if (list.count > 0) {
        for (NSInteger i=0; i<list.count; i++) {
            [chatContentArray addObject:[list objectAtIndex:i]];
        }
        [chatContentTableView reloadData];
        [self scrollToBottomAnimated:NO];
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}




- (void)setNavigationBar{
    self.navigationItem.title = [self.chatToUserNickName base64DecodedToString];
    
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"私信顶部-我的图标"] style:UIBarButtonItemStylePlain target:self action:@selector(pushChatToUserCenter)];
    rightBarButton.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)doTap{
    [self.view endEditing:YES];
}

- (void)pushChatToUserCenter{
    IVTUserInfoCenterViewController *userInfoCenterVC = [[IVTUserInfoCenterViewController alloc]init];
    userInfoCenterVC.userId = self.chatToUserId;
    [self.navigationController pushViewController:userInfoCenterVC animated:YES];
}

#pragma --mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return chatContentArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatObject *object = [chatContentArray objectAtIndex:indexPath.row];
    if (object.isMySend) {
        IVTMyChatContentListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCellIdentifier];
        if (!cell) {
            cell = [[IVTMyChatContentListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myCellIdentifier];
            cell.backgroundColor = [UIColor whiteColor];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.userAvatarUrl = [IVTAccountTool getAvatarUrl];
        cell.contentText = object.content;
        cell.sendDate = object.time;
        [cell setNeedsLayout];
        [cell layoutIfNeeded];
        return cell;
    }
    else{
        IVTFriendChatContentListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:friendCellIdentifier];
        if (!cell) {
            cell = [[IVTFriendChatContentListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendCellIdentifier];
            cell.backgroundColor = [UIColor whiteColor];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.userAvatarUrl = self.chatToUserAvatarUrl;
        cell.contentText = object.content;
        cell.sendDate = object.time;
        [cell setNeedsLayout];
        [cell layoutIfNeeded];
        return cell;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self sendMessage];
        return NO;
    }
    return YES;
}

- (void)sendMessage{
    NSString *sendTextString = [sendTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (sendTextString.length > 0) {
        [[XMPPManager sharedInstance] sendMessage:sendTextString toUserId:self.chatToUserId toUserNickName:self.chatToUserNickName toUserAvatarUrl:self.chatToUserAvatarUrl toUserSex:self.chatToUserSex toUserLevel:self.chatToUserLevel toUserSignature:self.chatToUserSignature];
        ChatObject *object = [[ChatObject alloc]init];
        object.chatToUserId = self.chatToUserId;
        object.content = sendTextString;
        object.time = [NSDate date];
        object.isMySend = YES;
        [chatContentArray addObject:object];
        [chatContentTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:chatContentArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self scrollToBottomAnimated:YES];
        
        sendTextField.text = @"";
    }
    else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入聊天内容" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceivePrivateChatMessage:(NSString *)messageText type:(ChatMessageType)msgType giftId:(NSInteger)giftId eachPrice:(CGFloat)price totalNumber:(NSInteger)totalNumber userInfo:(NSDictionary *)userInfo{
    //插入数据库
    if ([userInfo[@"userId"] integerValue] == [self.chatToUserId integerValue]) {
        ChatObject *object = [[ChatObject alloc]init];
        object.chatToUserId = self.chatToUserId;
        object.content = messageText;
        object.time = [NSDate date];
        object.isMySend = NO;
        [chatContentArray addObject:object];
        dispatch_async(dispatch_get_main_queue(), ^{
            [chatContentTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:chatContentArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [self scrollToBottomAnimated:YES];
        });
    }
}

- (void)keyboardWillChange:(NSNotification *)notification{
    NSValue *rectValue = [notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect rect = [rectValue CGRectValue];
    
    __weak typeof(self) wself = self;

    [keyboardToolView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(wself.view.mas_bottom).offset(-kScreenHeight + rect.origin.y);
    }];
    
    CGFloat time = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)scrollToBottomAnimated:(BOOL)isAnimated{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [chatContentTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:chatContentArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:isAnimated];
    });
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end