//
//  ChatsStore.m
//  AIIM
//
//  Created by gan on 2025/4/1.
//

#import <Foundation/Foundation.h>
#import "ChatsStore.h"
#import "GDBManager.h"
#import "ChatNetApi.h"
#import "GroupNetApi.h"
#import "UDManager.h"
#import "GWebSocket.h"
#import "ChatListStore.h"
#import "CryptoAES.h"


@implementation ChatsStore

+ (ChatsStore *_Nonnull)shareInstance{
    static id gShareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      gShareInstance = [[self alloc] init];
    });
    return gShareInstance;
}

- (instancetype)init {
    if (self = [super init]) {
        self.msgList = [[NSMutableArray alloc] init];
    }
    return self;
}


-(void)reciveMsg:(NSDictionary *_Nonnull)msg{
    
    msg = [self encodingMsg:msg];
    
    NSString *mine = msg[@"mine"];
    if(mine.boolValue){
        [self deleteMineTmpMsg:msg];
    }
    [GDBManager.shareInstance insertRplaceLocalmsg:msg succ:^(NSArray * _Nullable array) {
        //插入数据库成功
        if([self.chatId isEqualToString:msg[@"chatId"]]){
//            NSLog(@"----------------------2");
            if(self.delegate){
                [self.msgList addObject:msg];
                NSLog(@"----------------------3:%lu",(unsigned long)self.msgList.count);
                [self.delegate ChatsChange:self.msgList type:1];
            }
        }
        NSString *m =  msg[@"mine"];
        if(!m.boolValue){
            [[GWebSocket shareInstance] sendRecNote:msg];
        }
        else{
//            [[GWebSocket shareInstance] sendRecNote:msg];
        }
    } fail:^(NSString * _Nullable error) {
        //插入数据库成功
    }];
}

-(void)addMg:(NSArray *_Nonnull)array chatId:(NSString *)chatId{
//    NSLog(@"addMg:%@",array);
    NSArray *newArray = [self deletebadeData:array];
//    NSLog(@"addMg:%@",newArray);
    [GDBManager.shareInstance batchInsertLocalMessages:newArray success:^(NSArray * _Nullable resultArray) {
        [self reloadData:chatId];
        for (NSDictionary * dict in array) {
            [[GWebSocket shareInstance] sendRecNote:dict];
        }
    } failure:^(NSString * _Nullable error) {
        NSLog(@"%@",error);
        [self reloadData:chatId];
    }];
}


-(void)addQunNextMg:(NSArray *_Nonnull)array chatId:(NSString *)chatId timestp:(NSInteger)timestp{
    
    NSArray *newArray = [self deletebadeData:array];
    
    [GDBManager.shareInstance batchInsertLocalMessages:newArray success:^(NSArray * _Nullable resultArray) {
        [self loadNextData:chatId timestp:timestp];
        for (NSDictionary * dict in array) {
            [[GWebSocket shareInstance] sendRecNote:dict];
        }
    } failure:^(NSString * _Nullable error) {
        NSLog(@"%@",error);
    }];
}


-(void)deleteMineTmpMsg:(NSDictionary *_Nonnull)msg{
//    NSLog(@"deleteMineTmpMsg:%@",msg);
    NSString *localtime =msg[@"localtime"];
    if([localtime isKindOfClass:[NSString class]]){
        NSMutableArray * temp = self.msgList.copy;
        for (NSDictionary *dis in temp) {
            //NSString *oldtimestamp = dis[@"localtime"];
            NSString *timestamp = dis[@"timestamp"];
            if([localtime isEqualToString:timestamp]){
                [self.msgList removeObjectAtIndex:[temp indexOfObject:dis]];
                NSLog(@"----------------------12");
                break;
            }
        }
        [GDBManager.shareInstance deleteMyLocalmsg:msg];
    }
}


-(void)reloadData:(NSString *_Nonnull)chatId type:(NSInteger)type{
//    NSLog(@"chatId:%@,%ld",chatId,(long)type);
    [self reloadData:chatId];
    _reloadC=0;
    [self loadOutLineMsg:chatId type:type];
}

-(void)loadOutLineMsg:(NSString *_Nonnull)chatId type:(NSInteger)type{
    [ChatNetApi getOutLineMsg:chatId type:type succ:^(int code, NSDictionary *res) {
        self->_reloadC=4;
        NSArray *array = res[@"data"];
//        NSLog(@"getOutLineMsg2 res:%lu",(unsigned long)array.count);
        if(array.count>0){
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (NSDictionary *msg in array) {
                NSDictionary *enmsg = [self encodingMsg:msg];
                NSMutableDictionary *mutablemsg = [enmsg mutableCopy];
                if([self.userid isEqual:mutablemsg[@"fromId"]]){
                    [mutablemsg setObject:[NSNumber numberWithBool:YES] forKey:@"mine"];
                }else{
                    if([@"0" isEqual:enmsg[@"type"]]){//友聊
                        [mutablemsg setObject:enmsg[@"fromId"] forKey:@"chatId"];
//                        NSLog(@"-----1-------友聊:%@",mutablemsg);
                    }
                }
                [tempArray addObject:mutablemsg];
                [ChatListStore.shareInstance reciveMsg:(NSDictionary *)mutablemsg];
            }
            NSLog(@"chatId:%@,%ld",chatId,(long)type);
            [self addMg:tempArray chatId:chatId];
        }
        else{
            [self reloadData:chatId];
        }
        
    } fail:^(NSError * _Nonnull error) {
//        [MBProgressHUD showWithText:@"网络错误"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(self->_reloadC<3){
                self->_reloadC=self->_reloadC+1;
                [self loadOutLineMsg:chatId type:type];
            }
        });
    }];
}




-(void)reloadQunData:(NSString *_Nonnull)chatId type:(NSInteger)type{
    
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSLog(@"getqunOutLineMsg----");
    [ChatNetApi getqunOutLineMsg:chatId timestamp:time size:16 succ:^(int code, NSDictionary * res) {
//        NSLog(@"getqunOutLineMsg res:%@",res);
        NSArray *array = res[@"data"];
        NSLog(@"getqunOutLineMsg res:%lu",(unsigned long)array.count);
        if(array.count>0){
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (NSDictionary *msg in array) {
                NSDictionary *enmsg = [self encodingMsg:msg];
                NSMutableDictionary *mutablemsg = [enmsg mutableCopy];
                if([self.userid isEqual:mutablemsg[@"fromId"]]){
                    [mutablemsg setObject:[NSNumber numberWithBool:YES] forKey:@"mine"];
                }
                [tempArray addObject:mutablemsg];
                [ChatListStore.shareInstance reciveMsg:(NSDictionary *)mutablemsg];
            }
            [self addMg:tempArray chatId:chatId];
        }
        else{
            [self reloadData:chatId];
        }
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)reloadData:(NSString *_Nonnull)chatId{
    [GDBManager.shareInstance selectLocalmsg:chatId page:1 succ:^(NSArray * _Nullable array) {
        NSLog(@"array------:%@",chatId);
        if([self.chatId isEqualToString:chatId]){
            if(self.delegate){
                NSMutableOrderedSet *orderedSet = [[NSMutableOrderedSet alloc] initWithArray:array];//去重，顺序不变
                NSArray *msgs = [orderedSet array];
                msgs=[self arraysort:msgs];
                [self.msgList removeAllObjects];
                [self.msgList addObjectsFromArray:msgs];
                [self.delegate ChatsChange:self.msgList type:1];
            }
        }
//        NSMutableOrderedSet *orderedSet = [[NSMutableOrderedSet alloc] initWithArray:array];//去重，顺序不变
//        NSArray *msgs = [orderedSet array];
//        msgs=[self arraysort:msgs];
//        [self.msgList removeAllObjects];
//        [self.msgList addObjectsFromArray:msgs];
//        if(self.delegate){
//            [self.delegate ChatsChange:self.msgList];
//        }
    } fail:^(NSString * _Nullable error) {
        
    }];
}

-(void)loadNextData:(NSString *)chatId timestp:(NSInteger)timestp{
    [GDBManager.shareInstance selectnextmsg:chatId timestp:timestp succ:^(NSArray * _Nullable array) {
//        NSLog(@"loadNextData:%lu",(unsigned long)[array count]);
        
        if([array count]>0){
            NSLog(@"loadNextData1:%lu",(unsigned long)[array count]);
            
            if(self.msgList.count>0){
                NSArray *newArray = [array arrayByAddingObjectsFromArray:self.msgList];
                newArray=[self arraysort:newArray];
                self.msgList = [newArray mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            else{
                array=[self arraysort:array];
                self.msgList = [array mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            if([self.chatId isEqualToString:chatId]){
                if(self.delegate){
                    [self.delegate ChatsChange:self.msgList type:2];
                }
            }
            
            
        }
    } fail:^(NSString * _Nullable error) {
        ;
    }];
}


-(void)loadQunNextData:(NSString *)chatId timestp:(NSInteger)timestp{
    
    [ChatNetApi getqunOutLineMsg:chatId timestamp:timestp size:16 succ:^(int code, NSDictionary * res) {
//        NSLog(@"loadQunNextData res:%@",res);
        NSArray *array = res[@"data"];
        NSLog(@"getqunOutLinNextData res:%lu",(unsigned long)array.count);
        if(array.count>0){
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (NSDictionary *msg in array) {
                NSMutableDictionary *mutablemsg = [msg mutableCopy];
                if([self.userid isEqual:mutablemsg[@"fromId"]]){
                    [mutablemsg setObject:[NSNumber numberWithBool:YES] forKey:@"mine"];
                }
                [tempArray addObject:mutablemsg];
            }
            [self addQunNextMg:tempArray chatId:chatId timestp:timestp];
        }
        else{
            [self loadNextData:chatId timestp:timestp];
        }
    } fail:^(NSError * _Nonnull error) {
        [self loadNextData:chatId timestp:timestp];
    }];
}

-(void)getGroupUserList:(NSString *_Nonnull)chatId{
    [self reloadData:chatId];//先加载本地
//    NSLog(@"getqunOutLineMsg------------");
    [GroupNetApi getGroupUserList:chatId succ:^(int code, NSDictionary *res) {
//        NSLog(@"getqunOutLineMsgres:%@",res);
        self.groupUserList = res[@"data"];
//        [self reloadData:self.chatId type:1];
        [self reloadQunData:chatId type:1];
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"getqunOutLineMsgerrer");
    }];
}

//获取群组历史记录 先获取群成员列表
-(void)getGroupHistory:(NSString *_Nonnull)groupId type:(NSString *_Nullable)type{
    
    if([type isEqualToString:@""]){
        [GroupNetApi getGroupUserList:groupId succ:^(int code, NSDictionary *res) {
            //NSLog(@"res:%@",res);
            self.groupUserList = res[@"data"];
            [self reloadData:self.chatId];
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"errer");
        }];
    }
    else{
        [self reloadDataWithType:groupId type:type];
    }
}

//按消息分类查询本消息
-(void)reloadDataWithType:(NSString *_Nonnull)chatId type:(NSString *)type{
    
    [GDBManager.shareInstance selectLocalmsgType:chatId messageType:type succ:^(NSArray * _Nullable array) {
        //NSLog(@"array:%@",array);
        
        if([self.chatId isEqualToString:chatId]){
            if(self.delegate){
                NSArray *msgs=[self arraysort:array];
                [self.msgList removeAllObjects];
                [self.msgList addObjectsFromArray:msgs];
                [self.delegate ChatsChange:self.msgList type:1];
            }
        }
        
//        NSArray *msgs=[self arraysort:array];
//        [self.msgList removeAllObjects];
//        [self.msgList addObjectsFromArray:msgs];
//        if(self.delegate){
//            [self.delegate ChatsChange:self.msgList];
//        }
    } fail:^(NSString * _Nullable error) {
        
    }];
}
//查询本地所有类型消息下一页
-(void)loadNextDataAll:(NSString *)chatId timestp:(NSInteger)timestp{
    [GDBManager.shareInstance selectnextmsg:chatId timestp:timestp succ:^(NSArray * _Nullable array) {
//        NSLog(@"loadNextData:%lu",(unsigned long)[array count]);
        
        if([self.chatId isEqualToString:chatId]){
            if(self.msgList.count>0){
                NSArray *newArray = [array arrayByAddingObjectsFromArray:self.msgList];
                newArray=[self arraysort:newArray];
                self.msgList = [newArray mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            else{
                array=[self arraysort:array];
                self.msgList = [array mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            if(self.delegate){
                [self.delegate ChatsChange:self.msgList type:2];
            }
        }
        
        
    } fail:^(NSString * _Nullable error) {
        ;
    }];
}


//安消息分类查询本地消息下一页
-(void)loadNextDataWithType:(NSString *_Nonnull)chatId type:(NSString *_Nullable)type timestp:(NSInteger)timestp{
    
    [GDBManager.shareInstance selectNextmsgType:chatId messageType:type timestp:timestp succ:^(NSArray * _Nullable array) {
        if([self.chatId isEqualToString:chatId]){
            if(self.msgList.count>0){
                NSArray *newArray = [array arrayByAddingObjectsFromArray:self.msgList];
                newArray=[self arraysort:newArray];
                self.msgList = [newArray mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            else{
                array=[self arraysort:array];
                self.msgList = [array mutableCopy]; // 注意这里使用了 mutableCopy 来转换回 NSMutableArray
            }
            if(self.delegate){
                [self.delegate ChatsChange:self.msgList type:2];
            }
        }
        
        
    } fail:^(NSString * _Nullable error) {
        if([self.chatId isEqualToString:chatId]){
            if(self.delegate){
                [self.delegate ChatsChange:self.msgList type:2];
            }
        }
    }];
}

//删除废数据
-(NSArray *)deletebadeData:(NSArray *)array{
    
    NSMutableArray *marray = [NSMutableArray new];
    NSInteger index = 0;
    for (NSDictionary *msgA in array) {
        BOOL msrk = true;
        NSString *idA=msgA[@"id"];
        index++;
        if(index==array.count){
            [marray addObject:msgA];
            break;
        }
        if([idA isKindOfClass:[NSNull class]]){
            msrk=false;
        }
        else{
            for (NSInteger i = index;i<array.count;i++) {
                NSDictionary *msgB = [array objectAtIndex:i];
                NSString *idB=msgB[@"id"];
                if([idA isEqualToString:idB]){
                    NSDictionary * extendB = [msgB[@"extend"] isKindOfClass:NSDictionary.class]?msgB[@"extend"]:@{};
                    NSString *urlB = extendB[@"url"] ?: @"";
                    if(urlB.length>0){
                        msrk=false;
                    }
                    break;
                }
            }
        }
        if(msrk){
            [marray addObject:msgA];
        }
    }
    
    if(marray.count>0){
        return marray;
    }
    else{
        return array;
    }
}

//替换指定数据数据
-(NSArray *_Nullable)replaydisData:(NSDictionary *_Nullable)dis inarray:(NSArray *_Nullable)array{
    
    NSMutableArray *marray = [NSMutableArray new];
    NSString *locatTime = dis[@"localtime"];
    for (NSDictionary *msgA in array) {
        if(![locatTime isEqualToString:msgA[@"localtime"]]){
            [marray addObject:msgA];
        }
        else{
            [marray addObject:dis];
        }
    }
    return [marray copy];
}




-(NSArray *)arraysort:(NSArray *)array{
    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
        
        NSString *newtime =obj1[@"timestamp"];
        NSString *dtime =obj2[@"timestamp"];
//        NSLog(@"newtime:%@",newtime);
//        NSLog(@"dtime:%@",[dtime class]);
        if([newtime isKindOfClass:[NSNull class]]){
            return NSOrderedAscending;
        }
        if([dtime isKindOfClass:[NSNull class]]){
            return NSOrderedDescending;
        }
        
        if(newtime.longLongValue<dtime.longLongValue){
            return NSOrderedAscending;
        }
        else if(newtime.longLongValue==dtime.longLongValue){
            return NSOrderedSame;
        }
        else{
            return NSOrderedDescending;
        }
    }];
    return sortedArray;
}


-(void)updatereadTime:(NSDictionary *)dis{
    if(self.delegate){
        NSString *nstr = dis[@"userId"];
        NSInteger time = [dis[@"timestamp"] longLongValue];
        if([self.chatId isEqualToString:nstr]){
            self.lastreadTime = time;
            if(self.delegate){
                [self.delegate ChatsChange:self.msgList type:3];
            }
        }
    }
    
    [GDBManager.shareInstance insertLastreadtime:dis succ:^(NSArray * _Nullable array) {
        
    } fail:^(NSString * _Nullable error) {
    }];
}

-(NSDictionary *)getchatReadTime:(NSString *)chatId{
    [GDBManager.shareInstance selectchatLastreadtime:chatId succ:^(NSArray * _Nullable array) {
        NSLog(@"getchatReadTime:%@",chatId);
        NSLog(@"getchatReadTime:%@",array);
        if(array.count>0){
            NSDictionary *dic = array[0];
            NSString *temp =dic[@"timestamp"];
            self.lastreadTime = temp.integerValue;
        }
    } fail:^(NSString * _Nullable error) {
        
    }];
    return nil;
}

//消息列表中删除消息操作
-(void)deleteMyLocalMsg:(NSDictionary *_Nonnull)msg{
    [GDBManager.shareInstance deleteLocalmsg:msg];
    NSString *localtime =msg[@"localtime"];
    NSString * msgId = msg[@"id"];
    NSMutableArray * temp = self.msgList.copy;
    for (NSDictionary *dis in temp) {
        NSString *timestamp = dis[@"localtime"];
        NSString *tempMsgId = dis[@"id"];
        
        if (temp.lastObject == dis) {
            NSMutableDictionary * deleteMsg = [NSMutableDictionary dictionaryWithDictionary:msg];
            [deleteMsg setValue:@"【已删除】" forKey:@"content"];
            [ChatListStore.shareInstance reciveMsg:deleteMsg];
        }
        
        if([localtime isEqual:timestamp] && [msgId isEqualToString:tempMsgId]){
            [self.msgList removeObjectAtIndex:[temp indexOfObject:dis]];
            break;
        }
    }
    
    if(self.delegate){
        [self.delegate ChatsChange:self.msgList type:3];
    }
}


//信息解密存储
-(NSDictionary *)encodingMsg:(NSDictionary *)msg{
    NSMutableDictionary *temp = [msg mutableCopy];
    NSString *content = msg[@"content"];
    content = [CryptoAES.shareInstance decryptDataL:content?: @""];
    [temp setObject:content forKey:@"content"];
    return [temp copy];
}



@end
