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

#import "OffcnZYJFMDBHandler.h"

@implementation FMDBSensitiveWordsModel

@end


@interface OffcnZYJFMDBHandler()

@property (nonatomic,strong) ZYJZYJFMDatabaseQueue *chatDBDatabase;
@end
@implementation OffcnZYJFMDBHandler
static OffcnZYJFMDBHandler *FMDBHandler;
+ (OffcnZYJFMDBHandler *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        FMDBHandler = [[self alloc] init];
        
    });
    return FMDBHandler;
}

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

- (void)getUserDBWithItemSqlitePath:(NSString *)itemSqlitePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:itemSqlitePath]) {
        _database = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:itemSqlitePath];
    }
}

//@"SELECT * FROM xyu_room_chat order by time asc limit ?,?"
//ZYJFMResultSet *rs = [db executeQuery:sql,time,limit];
- (void)getChatInfoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_database) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat WHERE time==?"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
        
            messagesBack(tmpArray);
        }
    }];
}
- (void)getChatInfoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_database) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat WHERE time<=? order by time asc"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
//            NSArray *reversedArray = [[tmpArray reverseObjectEnumerator] allObjects];
            messagesBack(tmpArray);
        }
    }];
}
- (void)getChatInfoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_database) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_room_chat order by time asc"];
    [_database inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
            
            messagesBack(tmpArray);
        }
    }];
}

- (void)getUserGongGaoDBWithItemSqlitePath:(NSString *)itemSqlitePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:itemSqlitePath]) {
        _gongGaoDataBase = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:itemSqlitePath];
    }
}
- (void)getGongGaoArrayWithTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_gongGaoDataBase) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce WHERE time==? order by time desc"];
    [_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
        
            messagesBack(tmpArray);
        }
    }];
}
- (void)getGongGaoArrayFromTime:(NSString *)time limit:(NSString *)limit callback :(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_gongGaoDataBase) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce WHERE time<=? order by time desc"];
    [_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,time];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
//            NSArray *reversedArray = [[tmpArray reverseObjectEnumerator] allObjects];
            messagesBack(tmpArray);
        }
    }];
}
- (void)getGongGaoAllDataArrayCallback:(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_gongGaoDataBase) {
        return;
    }
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * FROM xyu_announce order by time desc"];
    [_gongGaoDataBase inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调历史消息记录
        if (messagesBack) {
            
            messagesBack(tmpArray);
        }
    }];
}

#pragma mark - 聊天本地数据库
//创建聊天本地数据库
NS_INLINE ZYJZYJFMDatabaseQueue * getFMDBInstance(){
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"ZYJFMDBChat.db"];
    ZYJZYJFMDatabaseQueue *database = [ZYJZYJFMDatabaseQueue databaseQueueWithPath:filePath];
    return database;
}

-(void)createChatDB{
    _chatDBDatabase = getFMDBInstance();
    [self createTable];
}
-(void)createTable{
    if (!_chatDBDatabase) {
        _chatDBDatabase = getFMDBInstance();
    }
//    [self deleteSensitiveWordsDataTable];
    //敏感词更新表
    NSString *creatSensitiveWordsSqlStr = @"create table sensitiveWords(wordsBase64 varchar(1000000),originalWords varchar(1000000));";
    [_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
        if (![db tableExists:@"sensitiveWords"]) {
            BOOL resCreatSensitiveWordsSqlStr = [db executeUpdate:creatSensitiveWordsSqlStr];
            if (!resCreatSensitiveWordsSqlStr) {
                NSLog(@"error when creating database table");
                NSLog(@"%d",db.lastErrorCode);
                NSLog(@"%@",db.lastErrorMessage);
            }
        }
    }];
}
-(void)deleteSensitiveWordsDataTable{
    if (!_chatDBDatabase) {
        _chatDBDatabase = getFMDBInstance();
    }
    
    NSString *sqlSensitiveWordsStr = @"DROP TABLE sensitiveWords";
    [_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
        BOOL resSensitiveWordsSqlStr = [db executeUpdate:sqlSensitiveWordsStr];
        if (!resSensitiveWordsSqlStr) {
            NSLog(@"error when drop database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
    }];
}
-(void)updateSensitiveWords:(FMDBSensitiveWordsModel *)model callBack:(callBackIsSuccess)isSuccess{
    if (!_chatDBDatabase) {
        _chatDBDatabase = getFMDBInstance();
    }
    
    [_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
        //插入记录到表中
        NSString *sqlStr = @"update sensitiveWords set originalWords = ? where wordsBase64 = ?";
        BOOL result = [db executeUpdate:sqlStr,model.originalWords,model.wordsBase64];
        if (!result) {
            NSLog(@"error when insert into database table");
            NSLog(@"%d",db.lastErrorCode);
            NSLog(@"%@",db.lastErrorMessage);
        }
        if (isSuccess) {
            isSuccess(result);
        }
    }];
}
-(void)getSensitiveWordsArrayWithWordsBase64:(NSString *)wordsBase64 callback:(getFMDBHistoryMessagesBlock)messagesBack{
    
    if (!_chatDBDatabase) {
        _chatDBDatabase = getFMDBInstance();
    }
    
    NSString * sql = @"SELECT * FROM sensitiveWords where wordsBase64 = ?";
    [_chatDBDatabase inDatabase:^(ZYJZYJFMDatabase *db) {
        ZYJZYJFMResultSet *rs = [db executeQuery:sql,wordsBase64];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
        while ([rs next]) {
            
            [tmpArray addObject:rs.resultDictionary];
        }
        //回调匹配的敏感词
        if (messagesBack) {
            messagesBack(tmpArray);
        }
    }];
}
@end
