//
//  OffcnIMZYJFMDBHandler.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2019/4/9.
//  Copyright © 2019年 中公教育. All rights reserved.
//

#import "OffcnIMZYJFMDBHandler.h"
#import "ZYJZYJFMDB.h"
#import "OffcnIMModel.h"

@interface OffcnIMZYJFMDBHandler()

@property (nonatomic,strong) ZYJZYJFMDatabaseQueue *database;
@end

@implementation OffcnIMZYJFMDBHandler

static OffcnIMZYJFMDBHandler *FMDBHandler;
+ (OffcnIMZYJFMDBHandler *)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        FMDBHandler = [[self alloc] init];
        
    });
    return FMDBHandler;
}

- (instancetype)init{
    if (self = [super init]) {
    }
    return self;
}

//登陆创建表格
- (void)getUserDB{
    _database = getFMDBInstance();
    [self createTable];
}

- (void)createTable{
    if (!_database) {
        _database = getFMDBInstance();
    }
    
    NSString *creatChatListSqlStr = @"create table chatlist(msg_fromId varchar(100), msg_toId varchar(100),tid varchar(100),session_id varchar(100),msg_id varchar (100),msg_type varchar(10),lastmessage varchar (500),lastSendtime varchar (50),msg_seq varchar(100),unread_number integer,primary key(msg_fromId))";

    NSString *creatChatInfoSqlStr = @"create table chatinfo(ID integer PRIMARY KEY AUTOINCREMENT,msg_fromId varchar(100),msg_toId varchar(100),tid varchar(100),session_id varchar(100),msg_id varchar (100),version varchar(10),send_time varchar(50),msg_seq varchar(100),msg_scope varchar (10),msg_type varchar(10),msg varchar(500),dur varchar(30),name varchat(500),md5 varchar(500),url varchar (500),thumb_url varchar(500),cover_url varchar(500),ext varchar(30),w varchar (10),h varchar(10),size varchar(10),isSentSuccess integer,bymyself integer,isRead integer)";
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        if (![db tableExists:@"chatlist"] && ![db tableExists:@"chatinfo"]) {
            BOOL resCreatChatListSqlStr = [db executeUpdate:creatChatListSqlStr];
            BOOL resCreatChatInfoSqlStr = [db executeUpdate:creatChatInfoSqlStr];
            
            if (!resCreatChatListSqlStr || !resCreatChatInfoSqlStr) {
                NSLog(@"error when creating database table");
                NSLog(@"%d",db.lastErrorCode);
                NSLog(@"%@",db.lastErrorMessage);
            }
        }
    }];
}

//发送,收到消息写入
- (void)insertChatInfoToFMDBWithModel:(OffcnIMBodyModel *)chatModel{
    if (!_database) {
        getFMDBInstance();
    }
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        NSString *sqlStr = @"insert into chatinfo(msg_fromId,msg_toId,tid,session_id,msg_id,version,send_time,msg_seq,msg_scope,msg_type,msg,dur,name,md5,url,thumb_url,cover_url,ext,w,h,size,isSentSuccess,bymyself,isRead) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        BOOL result = [db executeUpdate:sqlStr,chatModel.msg_from,chatModel.msg_to,chatModel.tid,chatModel.session_id,chatModel.msg_id,chatModel.version,chatModel.send_time,[NSNumber numberWithInteger:chatModel.msg_seq],[NSNumber numberWithInteger:chatModel.msg_scope],[NSNumber numberWithInteger:chatModel.msg_type],chatModel.msg.msg,[NSNumber numberWithInteger:chatModel.msg.dur],chatModel.msg.name,chatModel.msg.md5,chatModel.msg.url,chatModel.msg.thumb_url,chatModel.msg.cover_url,chatModel.msg.ext,[NSNumber numberWithInteger:chatModel.msg.w],[NSNumber numberWithInteger:chatModel.msg.h],[NSNumber numberWithInteger:chatModel.msg.size],[NSNumber numberWithInteger:chatModel.isSentSuccess],[NSNumber numberWithInteger:chatModel.bymyself],[NSNumber numberWithInteger:chatModel.isRead]];
        
        if (!result) {
            NSLog(@"error when insert into database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
    }];
}

//拉取更新消息列表
- (void)updateChatInfoCacheInfo:(OffcnIMBodyModel *)chatModel callback:(callBackIsSuccess)isSucess{
    if (!_database) {
        getFMDBInstance();
    }
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //查询是否存在
        NSString * sql = @"SELECT * FROM chatinfo where msg_fromId = ? and msg_id = ?";
        NSMutableArray *tmpDataArray = [NSMutableArray array];
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,chatModel.msg_from,chatModel.msg_id];
        
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc] init];
            [tmpDataArray addObject:tmpModel];
            break;
        }
        
        //存在
        BOOL result = NO;
        if (tmpDataArray.count) {
            
            NSString *sqlStr = @"update chatinfo set isSentSuccess = ?,bymyself = ?,isRead = ? where msg_fromId = ? and msg_id = ?";
            result = [db executeUpdate:sqlStr,[NSNumber numberWithInteger:chatModel.isSentSuccess],[NSNumber numberWithInteger:chatModel.bymyself],[NSNumber numberWithInteger:chatModel.isRead],chatModel.msg_from,chatModel.msg_id];
            
        //不存在,插库
        }else{
            
            NSString *sqlStr = @"insert into chatinfo(msg_fromId,msg_toId,tid,session_id,msg_id,version,send_time,msg_seq,msg_scope,msg_type,msg,dur,name,md5,url,thumb_url,cover_url,ext,w,h,size,isSentSuccess,bymyself,isRead) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            result = [db executeUpdate:sqlStr,chatModel.msg_from,chatModel.msg_to,chatModel.tid,chatModel.session_id,chatModel.msg_id,chatModel.version,chatModel.send_time,[NSNumber numberWithInteger:chatModel.msg_seq],[NSNumber numberWithInteger:chatModel.msg_scope],[NSNumber numberWithInteger:chatModel.msg_type],chatModel.msg.msg,[NSNumber numberWithInteger:chatModel.msg.dur],chatModel.msg.name,chatModel.msg.md5,chatModel.msg.url,chatModel.msg.thumb_url,chatModel.msg.cover_url,chatModel.msg.ext,[NSNumber numberWithInteger:chatModel.msg.w],[NSNumber numberWithInteger:chatModel.msg.h],[NSNumber numberWithInteger:chatModel.msg.size],[NSNumber numberWithInteger:chatModel.isSentSuccess],[NSNumber numberWithInteger:chatModel.bymyself],[NSNumber numberWithInteger:chatModel.isRead]];
        }
        
        [rs close];
        
        if (isSucess) {
            isSucess(result);
        }
    }];
}

//消息发送成功更新状态
- (void)updateChatInfoIsSendStatusToFMDBWithModel:(OffcnIMBodyModel *)messageModel isSuccess:(callBackIsSuccess)isSuccess{
    if (!_database) {
        getFMDBInstance();
    }
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        
        NSString *sql  = @"update chatinfo set isSentSuccess = ?,msg_id = ?,send_time = ?,msg_seq = ?,session_id = ?,msg = ?,name = ?,md5 = ?,url = ?,thumb_url = ?,cover_url = ?,ext = ?,w = ?,h = ?,size = ?,dur = ? where tid = ?";
        BOOL result = [db executeUpdate:sql,[NSNumber numberWithInteger:messageModel.isSentSuccess],messageModel.msg_id,messageModel.send_time,[NSNumber numberWithInteger:messageModel.msg_seq],messageModel.session_id,messageModel.msg.msg,messageModel.msg.name,messageModel.msg.md5,messageModel.msg.url,messageModel.msg.thumb_url,messageModel.msg.cover_url,messageModel.msg.ext,[NSNumber numberWithInteger:messageModel.msg.w],[NSNumber numberWithInteger:messageModel.msg.h],[NSNumber numberWithInteger:messageModel.msg.size],[NSNumber numberWithInteger:messageModel.msg.dur],messageModel.tid];
        
        if (!result) {
            NSLog(@"error when insert into database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
        
        if (isSuccess) {
            isSuccess(result);
        }
    }];
}

//发送,接受消息更新聊天列表
- (void)chatlistCacheInfo:(OffcnIMBodyModel *)chatlistModel callback:(callBackIsSuccess)isSucess{
    if (!_database) {
        getFMDBInstance();
    }
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //查询是否存在
        NSString * sql = @"SELECT * FROM chatlist where msg_fromId = ? and msg_toId = ?";
        NSMutableArray *tmpDataArray = [NSMutableArray array];
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,chatlistModel.msg_from,chatlistModel.msg_to];
        
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc] init];
            [tmpDataArray addObject:tmpModel];
            break;
        }
        
        //存在
        BOOL result = NO;
        if (tmpDataArray.count) {
            
            NSString *sqlStr = @"update chatlist set lastmessage = ?,lastSendtime = ?,msg_seq = ?,session_id = ?,tid = ?,msg_id = ?,msg_type = ? where msg_fromId = ? and msg_toId = ?";
            NSString *lastmessage = [self lastMessage:chatlistModel];
            result = [db executeUpdate:sqlStr,lastmessage,chatlistModel.send_time,[NSNumber numberWithInteger:chatlistModel.msg_seq],chatlistModel.session_id,chatlistModel.tid,chatlistModel.msg_id,[NSNumber numberWithInteger:chatlistModel.msg_type],chatlistModel.msg_from,chatlistModel.msg_to];
            
        //不存在,插库
        }else{
            
            NSString *sqlStr = @"insert into chatlist(msg_fromId,msg_toId,tid,session_id,msg_id,msg_type,lastmessage,lastSendtime,msg_seq)values(?,?,?,?,?,?,?,?,?)";
            NSString *lastmessage = [self lastMessage:chatlistModel];
            result = [db executeUpdate:sqlStr,chatlistModel.msg_from,chatlistModel.msg_to,chatlistModel.tid,chatlistModel.session_id,chatlistModel.msg_id,[NSNumber numberWithInteger:chatlistModel.msg_type],lastmessage,chatlistModel.send_time,[NSNumber numberWithInteger:chatlistModel.msg_seq]];
        }
        
        [rs close];
        
        if (isSucess) {
            isSucess(result);
        }
    }];
}

//拉取更新聊天列表
- (void)updateChatlistCacheInfo:(OffcnIMBodyModel *)chatlistModel callback:(callBackIsSuccess)isSucess{
    if (!_database) {
        getFMDBInstance();
    }
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //查询是否存在
        NSString * sql = @"SELECT * FROM chatlist where session_id = ?";
        NSMutableArray *tmpDataArray = [NSMutableArray array];
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,chatlistModel.session_id];
        
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc] init];
            [tmpDataArray addObject:tmpModel];
            break;
        }
        
        //存在
        BOOL result = NO;
        if (tmpDataArray.count) {
            
            NSString *sqlStr = @"update chatlist set msg_fromId = ?,msg_toId = ?,lastmessage = ?,lastSendtime = ?,msg_seq = ?,session_id = ?,tid = ?,msg_id = ?,msg_type = ?,unread_number = ? where session_id = ?";
            NSString *lastmessage = [self lastMessage:chatlistModel];
            result = [db executeUpdate:sqlStr,chatlistModel.msg_from,chatlistModel.msg_to,lastmessage,chatlistModel.send_time,[NSNumber numberWithInteger:chatlistModel.msg_seq],chatlistModel.session_id,chatlistModel.tid,chatlistModel.msg_id,[NSNumber numberWithInteger:chatlistModel.msg_type],[NSNumber numberWithInteger:chatlistModel.unread_number],chatlistModel.session_id];
            
        //不存在,插库
        }else{
            
            NSString *sqlStr = @"insert into chatlist(msg_fromId,msg_toId,tid,session_id,msg_id,msg_type,lastmessage,lastSendtime,msg_seq,unread_number)values(?,?,?,?,?,?,?,?,?,?)";
            NSString *lastmessage = [self lastMessage:chatlistModel];
            result = [db executeUpdate:sqlStr,chatlistModel.msg_from,chatlistModel.msg_to,chatlistModel.tid,chatlistModel.session_id,chatlistModel.msg_id,[NSNumber numberWithInteger:chatlistModel.msg_type],lastmessage,chatlistModel.send_time,[NSNumber numberWithInteger:chatlistModel.msg_seq],[NSNumber numberWithInteger:chatlistModel.unread_number]];
        }
        
        [rs close];
        
        if (isSucess) {
            isSucess(result);
        }
    }];
}

//更新和某个用户所有聊天为已读状态
- (void)updateChatInfoIsRead:(OffcnIMBodyModel *)model callBack:(callBackIsSuccess)isSuccess{
    if (!_database) {
        getFMDBInstance();
    }
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //插入记录到表中
        NSString *sqlStr = @"update chatinfo set isRead = ? where (msg_fromId =? and msg_toId = ?) or (msg_fromId =? and msg_toId = ?)";
        BOOL result = [db executeUpdate:sqlStr,[NSNumber numberWithInteger:model.isRead],model.msg_from,model.msg_to,model.msg_to,model.msg_from];
        if (!result) {
            NSLog(@"error when insert into database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
        if (isSuccess) {
            isSuccess(result);
        }
    }];
}
//更新和某个用户的聊天未读数
- (void)updateChatListUnread_number:(OffcnIMBodyModel *)model callBack:(callBackIsSuccess)isSuccess{
    
    if (!_database) {
        getFMDBInstance();
    }
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //插入记录到表中
        NSString *sqlStr = @"update chatlist set unread_number = ? where (msg_fromId =? and msg_toId = ?) or (msg_fromId =? and msg_toId = ?)";
        BOOL result = [db executeUpdate:sqlStr,[NSNumber numberWithInteger:model.unread_number],model.msg_from,model.msg_to,model.msg_to,model.msg_from];
        if (!result) {
            NSLog(@"error when insert into database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
        if (isSuccess) {
            isSuccess(result);
        }
    }];
}

//删除个人聊天记录
- (void)deleteUserChatDataWithFromUser:(NSString *)fromUser toUser:(NSString *)toUser clearStyle:(UIClearStyle)clearStyle callBack:(callBackIsSuccess)callbackBool{
    if (!_database) {
        getFMDBInstance();
    }
    
    NSString *updateStr = @"update chatlist set lastmessage = ?,lastSendtime = ?,msg_seq = ?,msg_type = ? where msg_fromId = ? and msg_toId = ?";
    NSString * listSql = [NSString stringWithFormat:@"delete  FROM chatlist where msg_fromId = ? and msg_toId = ?"];
    NSString * infoSql = [NSString stringWithFormat:@"delete  FROM chatinfo where (msg_fromId =? and msg_toId = ?) or (msg_fromId =? and msg_toId = ?)"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        [db beginTransaction];
        BOOL isRollBack = YES;
        
        @try {
            switch (clearStyle) {
                case UIClearStyleAll: {
                    [db executeUpdate:listSql,fromUser,toUser];
                    [db executeUpdate:infoSql,fromUser,toUser,toUser,fromUser];
                }
                    break;
                case UIClearStyleList: {
                    [db executeUpdate:listSql,fromUser,toUser];
                }
                    
                    break;
                case UIClearStylePart: {
                    [db executeUpdate:updateStr,@"",@"",@"",@"",fromUser,toUser];
                    [db executeUpdate:infoSql,fromUser,toUser,toUser,fromUser];
                }
                    break;
                    
                default:
                    break;
            }
        }
        @catch (NSException *exception) {
            isRollBack = NO;
            [db rollback];
        }
        @finally {
            if (isRollBack) {
                [db commit];
            }
        }
        callbackBool(isRollBack);
    }];
}

//删除消息,并更新消息列表最后一条消息
- (void)deleteMessage:(OffcnIMBodyModel *)messageModel dataSource:(NSMutableArray<OffcnIMBodyModel *> *)array callback:(callBackIsSuccess)isSuccess{
    
    if (!_database) {
        getFMDBInstance();
    }
    
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        //删除
        NSString * sql = @"delete from chatinfo where msg_id = ? and msg_fromId = ?";
        BOOL isSucceed = [db executeUpdate:sql,messageModel.msg_id,messageModel.msg_from];
        NSLog(@"");
        if (isSucceed) {
            
//            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sendTime = %@ ",messageModel.sendTime];
//            NSArray * refreshModel = [array filteredArrayUsingPredicate:predicate];
//            JYChatMessageModel *model = refreshModel.firstObject;
            [array removeObject:messageModel];
            
            if (!array.count) {
                NSString *sqlStr = @"update chatlist set lastmessage = ?,lastSendtime = ?,msg_seq = ?,msg_type = ? where msg_fromId =? and msg_toId = ?";
                BOOL updateSucceed    = [db executeUpdate:sqlStr,@"",@"",@"",@"",messageModel.msg_from,messageModel.msg_to];
                if (isSuccess) {
                    isSuccess(updateSucceed);
                }
            }else{
            //更新chatlist
            for (NSInteger index = array.count - 1; index > 0; index --) {
                
                OffcnIMBodyModel *lastModel = array[index];
                if (lastModel.isSentSuccess) {
                    
                    NSString *sqlStr = @"update chatlist set lastmessage = ?,lastSendtime = ?,msg_seq = ?,msg_type = ?,tid = ?,session_id = ?,msg_id = ? where msg_fromId =? and msg_toId = ?";
                    NSString *lastmessage = [self lastMessage:lastModel];
                    BOOL updateSucceed    = [db executeUpdate:sqlStr,lastmessage,lastModel.send_time,[NSNumber numberWithInteger:lastModel.msg_seq],[NSNumber numberWithInteger:lastModel.msg_type],lastModel.tid,lastModel.session_id,lastModel.msg_id,lastModel.msg_from,lastModel.msg_to];
                    
                    if (isSuccess) {
                        isSuccess(updateSucceed);
                    }
                    break;
                }
            }
        }
      }
    }];
}

//删除表格
- (void)deleteDataTable{
    NSString *sqlListStr = @"DROP TABLE chatlist";
    NSString *sqlInfostr = @"DROP TABLE chatinfo";

    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        BOOL resCreatChatListSqlStr = [db executeUpdate:sqlListStr];
        BOOL resCreatChatInfoSqlStr = [db executeUpdate:sqlInfostr];
        
        if (!resCreatChatListSqlStr || !resCreatChatInfoSqlStr) {
            NSLog(@"error when drop database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
    }];
}

//查询聊天记录(按时间戳倒叙排序)
- (void)getChatRecordArrayWithFromUser:(NSString *)fromUser toUser:(NSString *)toUser limit:(NSString *)limit startIndex:(NSString *)startIndex callback:(getFMDBHistoryMessagesBlock)messagesBack{
    if (!_database) {
        getFMDBInstance();
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM chatinfo where (msg_fromId =? and msg_toId = ?) or (msg_fromId =? and msg_toId = ?) order by msg_seq desc limit ?,?"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,fromUser,toUser,toUser,fromUser,startIndex,limit];
        NSMutableArray *tmpArray = [NSMutableArray array];
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc]init];
            OffcnIMMsgModel *tmpContentModel = [[OffcnIMMsgModel alloc]init];
            tmpModel.msg_from = [rs stringForColumn:@"msg_fromId"];
            tmpModel.msg_to = [rs stringForColumn:@"msg_toId"];
            tmpModel.tid = [rs stringForColumn:@"tid"];
            tmpModel.session_id = [rs stringForColumn:@"session_id"];
            tmpModel.msg_id = [rs stringForColumn:@"msg_id"];
            tmpModel.version = [rs stringForColumn:@"version"];
            tmpModel.send_time = [rs stringForColumn:@"send_time"];
            tmpModel.msg_seq = [rs longLongIntForColumn:@"msg_seq"];
            tmpModel.msg_scope = [rs intForColumn:@"msg_scope"];
            tmpModel.msg_type = [rs intForColumn:@"msg_type"];
            tmpModel.isSentSuccess = [rs intForColumn:@"isSentSuccess"];
            tmpModel.bymyself = [rs intForColumn:@"bymyself"];
            tmpModel.isRead = [rs intForColumn:@"isRead"];
            
            tmpContentModel.msg = [rs stringForColumn:@"msg"];
            tmpContentModel.dur = [rs longLongIntForColumn:@"dur"];
            tmpContentModel.name = [rs stringForColumn:@"name"];
            tmpContentModel.md5 = [rs stringForColumn:@"md5"];
            tmpContentModel.url = [rs stringForColumn:@"url"];
            tmpContentModel.thumb_url = [rs stringForColumn:@"thumb_url"];
            tmpContentModel.cover_url = [rs stringForColumn:@"cover_url"];
            tmpContentModel.ext = [rs stringForColumn:@"ext"];
            tmpContentModel.w = [rs longLongIntForColumn:@"w"];
            tmpContentModel.h = [rs longLongIntForColumn:@"h"];
            tmpContentModel.size = [rs longLongIntForColumn:@"size"];
            tmpModel.msg = tmpContentModel;
            [tmpArray addObject:tmpModel];
        }
        
        [rs close];
        //回调历史消息记录
        if (messagesBack) {
//            NSArray* reversedArray = [[tmpArray reverseObjectEnumerator] allObjects];
            messagesBack(tmpArray);
        }
    }];
}

//查询聊天列表
- (void)getChatListArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack{
    if (!_database) {
        getFMDBInstance();
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM chatlist order by lastSendtime asc"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc]init];
            tmpModel.msg_from = [rs stringForColumn:@"msg_fromId"];
            tmpModel.msg_to = [rs stringForColumn:@"msg_toId"];
            tmpModel.msg_type = [rs intForColumn:@"msg_type"];
            tmpModel.lastmessage = [rs stringForColumn:@"lastmessage"];
            tmpModel.lastSendtime = [rs stringForColumn:@"lastSendtime"];
            tmpModel.tid = [rs stringForColumn:@"tid"];
            tmpModel.session_id = [rs stringForColumn:@"session_id"];
            tmpModel.msg_id = [rs stringForColumn:@"msg_id"];
            tmpModel.msg_seq = [rs longLongIntForColumn:@"msg_seq"];
            tmpModel.unread_number = [rs longLongIntForColumn:@"unread_number"];
            [tmpArray addObject:tmpModel];
        }
        
        [rs close];
        //回调历史消息记录
        if (messagesBack) {
            
            messagesBack(tmpArray);
        }
    }];
}

//查询聊天列表其中一个会话信息
- (void)getChatListOneMessageWithFromUser:(NSString *)fromUser toUser:(NSString *)toUser callback:(getFMDBOneMessageBlock)messagesBack{
    if (!_database) {
        getFMDBInstance();
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM chatlist where (msg_fromId =? and msg_toId = ?) or (msg_fromId =? and msg_toId = ?)"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,fromUser,toUser,toUser,fromUser];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            OffcnIMBodyModel *tmpModel = [[OffcnIMBodyModel alloc]init];
            tmpModel.msg_from = [rs stringForColumn:@"msg_fromId"];
            tmpModel.msg_to = [rs stringForColumn:@"msg_toId"];
            tmpModel.msg_type = [rs intForColumn:@"msg_type"];
            tmpModel.lastmessage = [rs stringForColumn:@"lastmessage"];
            tmpModel.lastSendtime = [rs stringForColumn:@"lastSendtime"];
            tmpModel.tid = [rs stringForColumn:@"tid"];
            tmpModel.session_id = [rs stringForColumn:@"session_id"];
            tmpModel.msg_id = [rs stringForColumn:@"msg_id"];
            tmpModel.msg_seq = [rs longLongIntForColumn:@"msg_seq"];
            tmpModel.unread_number = [rs longLongIntForColumn:@"unread_number"];
            [tmpArray addObject:tmpModel];
        }
        
        [rs close];
        //回调历史消息记录
        if (messagesBack) {
            if (tmpArray.count) {
                messagesBack(tmpArray.lastObject);
            }else{
                messagesBack(nil);
            }
        }
    }];
}

//消息内容
- (NSString *)lastMessage:(OffcnIMBodyModel *)messageModel{
    NSString *lastMessage = nil;
    if (messageModel.msg_type == 1) {
        //文本消息
        lastMessage   = messageModel.msg.msg;
        return lastMessage;
    }else if (messageModel.msg_type == 2){
         //图片消息
        lastMessage   = messageModel.msg.url;
        return lastMessage;
    }else if (messageModel.msg_type == 3){
         //音频消息
        lastMessage   = messageModel.msg.url;
        return lastMessage;
    }else if (messageModel.msg_type == 4){
         //视频消息
        lastMessage   = messageModel.msg.url;
        return lastMessage;
    }else if (messageModel.msg_type == 5){
        //文件消息
        lastMessage   = messageModel.msg.url;
        return lastMessage;
    }
    return @"";
}
#pragma mark - 聊天本地数据库
//创建聊天本地数据库
NS_INLINE ZYJZYJFMDatabaseQueue * getFMDBInstance(){
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"ZYJFMDBIMChat.db"];
    ZYJZYJFMDatabaseQueue *database = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:filePath];
    return database;
}
@end
